It's a good practice to divide test cases into 3 sections: Given, When, Then.
But in JUnit common way to handle exceptions is using ExpectedException @Rule.
The problem is ExpectedException::expect() must be declared before //when section.
public class UsersServiceTest {
// Mocks omitted
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void signUp_shouldCheckIfUserExistsBeforeSign() throws ServiceException {
// given - its ok
User user = new User();
user.setEmail(EMAIL);
when(usersRepository.exists(EMAIL)).thenReturn(Boolean.TRUE);
// then ???
thrown.expect(UserAlreadyExistsServiceException.class);
// when???
usersService.signUp(user);
}
}
Does anyone know some good convention or library for better handling exceptions in tests?