'assertThrows() works well but it should fail
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
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
