Reputation: 47
I'm new to junit and I'm wondering why assertThrows() works well in both of cases. Why does it throw an exception in the case of findById(1L)? There is an employee with an id 1L, so the assertion should fail. Am I right?
employee service:
public Employee findById(Long id) {
return employeeRepository.findById(id)
.orElseThrow( ()-> new NoSuchElementException("not found"));
}
Test method:
@ExtendWith(MockitoExtension.class)
class EmployeeManagerTest {
@Mock
private EmployeeRepository employeeRepository;
@InjectMocks
private EmployeeManager employeeManager;
@Test
void shouldThrowExceptionWhenEmployeeNotExist() {
Employee employee = new Employee();
employee.setId(1L);
assertThrows(NoSuchElementException.class, ()-> employeeManager.findById(123L) ); // works well
assertThrows(NoSuchElementException.class, ()-> employeeManager.findById(1L) ); // works well, but should fail, because there is an employee with id 1L
}
}
Upvotes: 1
Views: 1479
Reputation: 2384
You should mock your EmployeeRepository
and make it return your employee when your EmployeeManager
calls findById
on the repository, or return nothing when you want to test the failing case. I created two separate tests:
@ExtendWith(MockitoExtension.class)
class EmployeeManagerTest {
@Mock
private EmployeeRepository employeeRepository;
@InjectMocks
private EmployeeManager employeeManager;
@Test
void shouldThrowExceptionWhenEmployeeDoesNotExist() {
// Given
// Make the repo return an empty optional when the id doesn't exit
when(employeeRepository.findById(any())).thenReturn(Optional.empty());
// Then
assertThrows(NoSuchElementException.class, ()-> employeeManager.findById(123L) );
}
@Test
void shouldReturnEmployeeWhenItExists() {
// Given
Employee employee = new Employee();
employee.setId(1L);
// Make the repo return an the employee
when(employeeRepository.findById(1L)).thenReturn(Optional.of(employee));
// When
Employee returnedEmployee = employeeManager.findById(1L);
// Then
assertEquals(employee, returnedEmployee);
}
}
Upvotes: 1