Issue
I have UserService
and there GET method which returns the object found by id. Let's say:
@Service
public class UserService {
@Autowired
UserRepository repository;
public User getUserById(Long id) {
return repository.findById(id)
.orElseThrow(() -> new UserNotFoundException(id));
}
}
I made simple test if the user is found:
@ExtendWith(MockitoExtension.class)
class UserServiceTest {
@Mock
private UserRepository userRepository;
@InjectMocks
private UserService userService;
@Test
public void whenGivenId_shouldReturnUser_ifFound() {
User user = new User();
user.setId(89L);
when(userRepository.findById(user.getId())).thenReturn(Optional.of(user));
User expected = userService.getUserById(user.getId());
assertThat(expected).isSameAs(user);
verify(userRepository).findById(user.getId());
}
}
Now I want to make a method, let's say: public void shouldThrowExceptionWhenUserDoesntExist()
. How to make it in JUnit5? In JUnit4 I would make something like this:
@Test(expected = UserNotFoundException.class)
public void shouldThrowExceptionWhenUserDoesntExist() {
User user = new User();
user.setId(89L);
user.setName("Test Name");
given(userRepository.findById(anyLong())).willReturn(Optional.ofNullable(null));
userService.getUserById(user.getId());
}
Since this @Test(expected = UserNotFoundException.class)
is outdated in JUnit5, I can't find anywhere what's the way in handling exception like this one in JUnit5.
Solution
Do like this
Assertions.assertThrows(UserNotFoundException.class, () -> {
userService.getUserById(1234);
});
Answered By - hiren
Answer Checked By - Terry (JavaFixing Volunteer)