Reputation: 1688
I have implemented a simple spring boot crud application to write test cases. I have faced a bit of trouble with the delete operation. When I use Mockito.when
method then it is expected a return value and my delete method is non-return type.
Service Class
@Service
public class EmployeeServiceImpl implements EmployeeService {
private EmployeeDAO employeeDAO;
@Autowired
public EmployeeServiceImpl(EmployeeDAO employeeDAO)
{
this.employeeDAO=employeeDAO;
}
@Override
public void deleteEmployee(Employee emp) throws IllegalArgumentException{
employeeDAO.delete(emp);
}
}
ServiceTest class
@ExtendWith(SpringExtension.class)
@SpringBootTest
public class EmployeeServiceImplTest {
@MockBean
private EmployeeDAO employeeDAO;
@Autowired
private EmployeeService employeeService;
@Test
public void testDeleteEmployee()
{
int empId=1054;
Employee employee=employee_2();
employee.setEmpId(empId);
// how to write test case for void method
}
private Employee employee_2()
{
Employee employee=new Employee();
employee.setEmpName("NafazBenzema");
employee.setSalary(12000.00);
return employee;
}
}
Upvotes: 8
Views: 39177
Reputation: 950
You can use Mockito.doNothing()
:
Mockito.doNothing().when(employeeDAO).deleteEmployee(Mockito.any());
Upvotes: 6
Reputation: 749
You can either use doNothing or doThrow on your mock to mock the behaviour of your mock.
Mockito.doNothing().when(employeeDAO).delete(any());
or
Mockito.doThrow(new RuntimeException()).when(employeeDAO).delete(any());
However, doNothing is not actually needed as this would be the default behaviour for a mock function with a void return type.
You may want however to verify
that this method was called. For example:
verify(employeeDAO).delete(any());
Upvotes: 18
Reputation: 1688
Thank you omer.
But in my case, I had to replace employeeService
with employeeDAO
.The employeeService
is annotated with @Autowired
annotation and it throws NotaMockAnnotation
exception.
Mockito.doNothing().when(employeeDAO).delete(employee);
Upvotes: 0