Mocks are structures that mimic the behavior of external dependencies that you / cannot have or that cannot work properly in the context of your test, because they depend on other external systems (for example, connecting to the server). Therefore, the test, as you described, is really not very useful, because you are basically trying to check the simulated behavior of your layouts and nothing more.
A better example is the EmployeeValidator class, which depends on another EmployeeService system that sends a request to an external server. Perhaps the server is not available in the current context of your test, so you need to make fun of the service that makes the request and simulate the behavior of this.
class EmployeeValidator { private final EmployeeService service; public EmployeeValidator(EmployeeService service) { this.service = service; } public List<Employee> employeesWithMaxSalary(int maxSalary) { List<Employee> allEmployees = service.getAll();
You can then write a test that mocks EmployeeService and simulates a call to an external system. After that, you can verify that everything went as planned.
@Test public void shouldContainAllEmployeesWithSalaryFiveThousand() { // Given - Define behaviour EmployeeService mockService = mock(EmployeeService.class); when(mockService.getAll()).thenReturn(createEmployeeList()); // When - Operate the system under test // Inject the mock EmployeeValidator ev = new EmployeeValidator(mockService); // System calls EmployeeService#getAll() internally but this is mocked away here List<Employee> filtered = ev.employeesWithMaxSalary(5000); // Then - Check correct results assertThat(filtered.size(), is(3)); // There are only 3 employees with Salary <= 5000 verify(mockService, times(1)).getAll(); // The service method was called exactly one time. } private List<Employee> createEmployeeList() { // Create some dummy Employees }
QBrute
source share