From 1759fffe6cc6bae69152da719ef98764f123c249 Mon Sep 17 00:00:00 2001 From: Ulli Hafner Date: Sun, 3 Nov 2024 16:55:05 +0100 Subject: [PATCH] Improve exception handling if metric is missing. --- src/main/java/edu/hm/hafner/coverage/Metric.java | 7 ++++++- src/test/java/edu/hm/hafner/coverage/MetricTest.java | 8 ++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/src/main/java/edu/hm/hafner/coverage/Metric.java b/src/main/java/edu/hm/hafner/coverage/Metric.java index 745e834..d27acb3 100644 --- a/src/main/java/edu/hm/hafner/coverage/Metric.java +++ b/src/main/java/edu/hm/hafner/coverage/Metric.java @@ -8,6 +8,8 @@ import java.util.TreeSet; import java.util.stream.Stream; +import org.apache.commons.lang3.StringUtils; + import com.google.errorprone.annotations.Immutable; import edu.hm.hafner.coverage.Coverage.CoverageBuilder; @@ -79,7 +81,10 @@ public static Metric fromName(final String name) { return metric; } } - throw new IllegalArgumentException("No metric found for name: " + name); + if (StringUtils.isBlank(name)) { + throw new IllegalArgumentException("No metric defined"); + } + throw new IllegalArgumentException("No metric found for name '" + name + "'"); } private static String normalize(final String name) { diff --git a/src/test/java/edu/hm/hafner/coverage/MetricTest.java b/src/test/java/edu/hm/hafner/coverage/MetricTest.java index 5a0cafd..980c40d 100644 --- a/src/test/java/edu/hm/hafner/coverage/MetricTest.java +++ b/src/test/java/edu/hm/hafner/coverage/MetricTest.java @@ -23,6 +23,14 @@ void shouldMapFromName(final String name) { assertThat(Metric.fromName(name)).isSameAs(Metric.CYCLOMATIC_COMPLEXITY); } + @Test + void shouldProvideContextWhenMetricIsWrong() { + assertThatIllegalArgumentException().isThrownBy(() -> Metric.fromName("undefined")) + .withMessageContaining("No metric found for name 'undefined'"); + assertThatIllegalArgumentException().isThrownBy(() -> Metric.fromName("")) + .withMessageContaining("No metric defined"); + } + @EnumSource(Metric.class) @ParameterizedTest(name = "{0} should be converted to a tag name and then back to a metric") void shouldConvertToTags(final Metric metric) {