0

Part of a test fixture checks that no errors were logged during a test:

@After
public void testname() {
    if(accumulatedErrors()) {
        fail("Errors were recorded during test");
    }
}

But for a test that is expected to fail, like this:

@Test(expected = IllegalStateException.class)
public void shouldExplode() throws Exception {
    doExplodingStuff();
}

the @After method should invert the check:

@After
public void testname() {
    if (failureIsExpected()) {
        assertTrue("No errors were recorded during test", accumulatedErrors());
    } else {
        assertFalse("Errors were recorded during test", accumulatedErrors());
    }
}

Is there a way to inspect the expected parameter of the executed test from the @After method?

Of course, the test could specify expectToFail=true or something like that, but I would like to avoid that duplication.

Markus
  • 809
  • 5
  • 10
  • Did you have a look at the JUnit's [ErrorCollector Rule](https://github.com/junit-team/junit/wiki/Rules#errorcollector-rule) and [ExpectedException Rules](https://github.com/junit-team/junit/wiki/Rules#expectedexception-rules)? – halfbit Nov 08 '13 at 10:08

2 Answers2

2

Why you cannot add assertTrue or assertFalse in each test method ? You solution seems to me too complicated. Method annotated with @After should be used to release resources.

Areo
  • 928
  • 5
  • 12
  • The @After method is used to assert that no errors recorded (or logged), which would otherwise be added to every test. – Markus Nov 08 '13 at 09:56
  • Asserting in after / before method is bad : – Areo Nov 08 '13 at 09:59
  • It is normal solution to have assertion at the end of test method. If test fail then you can quickly check which assert was bad. – Areo Nov 08 '13 at 10:41
0

Using catch-exception, you can move the check for an exception inside the method instead of outside the method:

@Test
public void shouldExplode() throws Exception {
    catchException(this).doExplodingStuff();
    assertTrue(caughtException() instanceof IllegalStateException);
}
Adrian Panasiuk
  • 7,249
  • 5
  • 33
  • 54
  • The issue here is that the @After method will fail later. – Markus Nov 08 '13 at 09:54
  • @Markus you mean you want a soft assertion that will not terminate the test case? If that is the case, you already have some sort of non-fatal `checkTrue` method you can substitute the `assertTrue` above with. – Adrian Panasiuk Nov 08 '13 at 09:56
  • No, the test case should fail if an error was logged. Unless we expect the test to throw an exception, then the test would fail if no error was logged. – Markus Nov 08 '13 at 09:58
  • @Markus hm, but the test above does fail when `doExplodingStuff` does not throw? – Adrian Panasiuk Nov 08 '13 at 10:00