Skip to content

Commit

Permalink
Merge pull request #3832 from asmirnov-backend/fix/#3831/exception-ch…
Browse files Browse the repository at this point in the history
…ain-in-expect

Fix wrong exception handling in Expect
  • Loading branch information
yegor256 authored Jan 17, 2025
2 parents 2ffbc31 + 6f9d0d7 commit 37cc4f4
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 5 deletions.
31 changes: 26 additions & 5 deletions eo-runtime/src/main/java/org/eolang/Expect.java
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ public Expect<T> otherwise(final String message) {
try {
return this.sup.get();
} catch (final ExMust ex) {
throw new ExFailure(
throw new ExOtherwise(
String.format(
"%s %s %s",
this.subject,
Expand All @@ -113,7 +113,7 @@ public Expect<T> otherwise(final String message) {
ex
);
} catch (final ExThat ex) {
throw new ExFailure(
throw new ExOtherwise(
String.format(
"%s %s",
this.subject,
Expand Down Expand Up @@ -152,7 +152,11 @@ public Expect<T> must(final Function<T, Boolean> fun) {
* @checkstyle MethodNameCheck (5 lines)
*/
public T it() {
return this.sup.get();
try {
return this.sup.get();
} catch (final ExOtherwise ex) {
throw new ExFailure(ex.getMessage(), ex);
}
}

/**
Expand All @@ -161,7 +165,7 @@ public T it() {
*
* @since 0.51
*/
private static class ExMust extends ExFailure {
private static class ExMust extends RuntimeException {
/**
* Ctor.
* @param cause Exception cause
Expand All @@ -178,7 +182,7 @@ private static class ExMust extends ExFailure {
*
* @since 0.51
*/
private static class ExThat extends ExFailure {
private static class ExThat extends RuntimeException {
/**
* Ctor.
* @param cause Exception cause
Expand All @@ -189,4 +193,21 @@ private static class ExThat extends ExFailure {
}
}

/**
* This exception is used to enhance the error message
* in the {@link Expect#it()} method.
*
* @since 0.51
*/
private static class ExOtherwise extends RuntimeException {
/**
* Ctor.
* @param cause Exception cause
* @param args Arguments for {@link String#format(String, Object...)}
*/
ExOtherwise(final String cause, final Object... args) {
super(String.format(cause, args));
}
}

}
19 changes: 19 additions & 0 deletions eo-runtime/src/test/java/org/eolang/ExpectTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -144,4 +144,23 @@ void failsWithCorrectTraceWithExFailureInThatForParsing() {
Matchers.equalTo("attr must be an integer")
);
}

@Test
void failsWithCorrectTraceForMustAndThat() {
MatcherAssert.assertThat(
"Take error message from must",
Assertions.assertThrows(
ExFailure.class,
() -> new Expect<>("attr", () -> "string")
.must(i -> false)
.otherwise("in must")
.that(i -> i)
.otherwise("in that")
.it(),
"fails on 'must'"
).getMessage(),
Matchers.equalTo("attr (string) in must")
);
}

}

0 comments on commit 37cc4f4

Please sign in to comment.