public class DefaultFooServiceTest {
private FooService fooService = new DefaultFooService();
@Rule
public ExpectedException exception = new ExpectedException();
@Test
public void shouldThrowNpeWhenNullName() throws Exception {
//given
String name = null;
//when
exception.expect(NullPointerException.class);
fooService.echo(name);
//then
}
}
Szczepan claims that ExpectedException fits into given/when/then test template nicely. I disagree! Look at the code snippet above – what is the most natural place to put assertions on exception being thrown? From the obvious reasons it must be the last line before the line that actually throws the exceptions. So you have a choice to put assertion as the last statement in given block or as first in when block. You are right, this is how this test should look like in an ideal world:
@Test
public void shouldThrowNpeWhenNullName() throws Exception {
//given
String name = null;
//when
fooService.echo(name);
//then
exception.expect(NullPointerException.class);
}








