I have a basic unit test for a Service with a mocked repository as follow :
@Test public void deleteEmployeeCallsRepositoryDeleteById() { Employee employee = new Employee(); employee.setName("coolName"); employee.setId(8978L); EmployeeRepository repoSpy = spy(employeeRepository); service.deleteEmployeeById(employee.getId()); verify(repoSpy, atLeastOnce()).deleteById(employee.getId()); }
When running the test, I get the following error :
Wanted but not invoked: employeeRepository.deleteById(8978L); -> at unit.services.EmployeeServiceImplTests.deleteEmployeeCallsRepositoryDeleteById(EmployeeServiceImplTests.java:70) However, there was exactly 1 interaction with this mock: employeeRepository.deleteById(8978L); -> at services.EmployeeServiceImpl.deleteEmployeeById(EmployeeServiceImpl.java:34)
Second sentence saying the exact opposite of the first sentence…
I tried using verify(repoSpy, atLeastOnce()).deleteById(anyLong());
just in case, but same error message.
Advertisement
Answer
spy
doesn’t alter the argument in-place, it decorates it and returns the spying decorator. You need to pass mocks or spies to the code under test in the ordinary manner.