JUnit Testing Exceptions
If your constructor is similar to this one:
public Example(String example) {
if (example == null) {
throw new NullPointerException();
}
//do fun things with valid example here
}
Then, when you run this JUnit test you will get a green bar:
@Test(expected = NullPointerException.class)
public void constructorShouldThrowNullPointerException() {
Example example = new Example(null);
}
are you sure you told it to expect the exception?
for newer junit (>= 4.7), you can use something like (from here)
@Rule
public ExpectedException exception = ExpectedException.none();
@Test
public void testRodneCisloRok(){
exception.expect(IllegalArgumentException.class);
exception.expectMessage("error1");
new RodneCislo("891415",dopocitej("891415"));
}
and for older junit, this:
@Test(expected = ArithmeticException.class)
public void divisionWithException() {
int i = 1/0;
}
@Test(expected = Exception.class)
Tells Junit that exception is the expected result so test will be passed (marked as green) when exception is thrown.
For
@Test
Junit will consider test as failed if exception is thrown, provided it's an unchecked exception. If the exception is checked it won't compile and you will need to use other methods. This link might help.