Skip to content

Commit

Permalink
Merge pull request #583 from UrsMetz/expected-exception-fail-when-ass…
Browse files Browse the repository at this point in the history
…ertion-error-expected-but-not-thown

ExpectedException doesn't fail when an AssertionError is expected but not thrown
  • Loading branch information
David Saff committed Jan 3, 2013
2 parents ef6ee7f + 04218be commit ad0f505
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 7 deletions.
17 changes: 10 additions & 7 deletions src/main/java/org/junit/rules/ExpectedException.java
Original file line number Diff line number Diff line change
Expand Up @@ -179,23 +179,22 @@ public ExpectedExceptionStatement(Statement base) {
public void evaluate() throws Throwable {
try {
fNext.evaluate();
if (fMatcherBuilder.expectsThrowable()) {
failDueToMissingException();
}
} catch (AssumptionViolatedException e) {
optionallyHandleException(e, handleAssumptionViolatedExceptions);
return;
} catch (AssertionError e) {
optionallyHandleException(e, handleAssertionErrors);
return;
} catch (Throwable e) {
handleException(e);
return;
}
if (fMatcherBuilder.expectsThrowable()) {
failDueToMissingException();
}
}
}

private void failDueToMissingException() throws AssertionError {
fail(missingExceptionMessage());
}

private void optionallyHandleException(Throwable e, boolean handleException)
throws Throwable {
if (handleException) {
Expand All @@ -212,6 +211,10 @@ private void handleException(Throwable e) throws Throwable {
throw e;
}
}

private void failDueToMissingException() throws AssertionError {
fail(missingExceptionMessage());
}

private String missingExceptionMessage() {
if (isMissingExceptionMessageEmpty()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,9 @@ public static Collection<Object[]> testsWithEventMatcher() {
{ViolateAssumptionAndExpectException.class,
hasSingleAssumptionFailure()},
{ThrowExpectedAssertionError.class, everyTestRunSuccessful()},
{
DontThrowAssertionErrorButExpectOne.class,
hasSingleFailureWithMessage("Expected test to throw an instance of java.lang.AssertionError")},
{
ThrowUnexpectedAssertionError.class,
hasSingleFailureWithMessage(startsWith("\nExpected: an instance of java.lang.NullPointerException"))},
Expand Down Expand Up @@ -289,6 +292,17 @@ public void wrongException() {
}
}

public static class DontThrowAssertionErrorButExpectOne {
@Rule
public ExpectedException thrown = none();

@Test
public void assertionErrorExpectedButNonIsThrown() {
thrown.handleAssertionErrors();
thrown.expect(AssertionError.class);
}
}

public static class ViolateAssumptionAndExpectException {
@Rule
public ExpectedException thrown = none();
Expand Down

0 comments on commit ad0f505

Please sign in to comment.