I'm going to take the unusual step of adding another answer after my answer was accepted. The previous answer focused on the question raised in the summary, but I wanted to focus on the code.
I think one of the reasons why you were wondering what to do is because the test sampleTest()
is testing two completely different things. Your test method is testing normal behavior and exceptional behavior in the same test method.
Instead, split out the testing of the exceptional cases into their own test methods. For example:
@RunWith(JUnit4.class)
public class SampleTest {
@Test
public void methodAndWaitShouldAcceptNonNullValue() {
ClassUnderTest.methodAndWait("arg1")
}
@Test
public void methodAndWaitShouldThrowWhenGivenNullValue() {
try {
ClassUnderTest.methodAndWait(null);
fail("NullPointerException was not thrown");
} catch (NullPointerException ex) {
assertTrue(ex.getMessage().contains(ERROR_STRING1));
}
}
}
This has several advantages:
- If
methodAndWait("arg1")
throws an exception, the test will fail with a useful stack trace
- If
methodAndWait(null)
throws something other than NullPointerException
, the test will fail with a useful stack trace
- If
methodAndWait(null)
doesn't throw anything, the test will fail with a useful message
- The intent of both tests is very clear
If you need to test with multiple arguments, you can use the Enclosed
runner:
@RunWith(Enclosed.class)
public class SampleTest {
@RunWith(Parameterized.class)
public static class WhenPassingNonNull {
@Parameters
public static Collection<object[]> methodParams() {
List<Object[]> params = new ArrayList<Object[]>();
/* arg, errorString */
params.add(new Object[] {"arg1", "result1"});
params.add(new Object[] {"arg3", "result3"});
}
public final String arg;
public final String actualResult;
public SampleTest(String arg, String actualResult) {
this.arg = arg;
this.actualResult = actualResult;
}
@Test
public void sampleTest() {
String actualResult = ClassUnderTest.methodAndWait(arg);
assertEquals(expectedResult, actualResult);
}
}
@RunWith(JUnit4.class)
public static class WhenPassingNull {
@Test
public void shouldThrowNullPointerException() {
try {
ClassUnderTest.methodAndWait(null);
fail();
} catch (NullPointerException ex) {
assertTrue(ex.getMessage().contains(ERROR_STRING1));
}
}
}
}