I'm making scenario tests with JUnit4 for a project.
In one of the tests I need to check for an expected exception. With JUnit4 I do this using the annotation.
@Test(expected=...) Now the problem is that underneath the code in the test that throws the exception there's some other annotations I need to check which doesn't get excecuted. An example given:
@Test(expected=NullPointerException.class) public void nullPointerTest() { Object o = null; o.toString(); assertTrue(false); } This tests passes because it gets the nullpointerexception however there's obviously an assertion error with the asserTrue(false) and thus I want it to fail.
What's the best way to fix this? A solution to this could be the following, but I don't know if this is the correct way to do it.
@Test public void nullPointerTest2() { boolean caught = false; try{ Object o = null; o.toString(); } catch(NullPointerException e) { caught = true; } assertTrue(caught); assertTrue(false); } This second test fails as predicted.
assertTrue(false)? Or does this stand here for some of your real testing code? Does that "real" code depend on the code before it that throws aNullPointerException?