Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mockito with void method in JUnit

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;
    }

}
like image 402
NafazBenzema Avatar asked May 09 '26 11:05

NafazBenzema


2 Answers

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());
like image 85
Ahmed Abdelhady Avatar answered May 11 '26 00:05

Ahmed Abdelhady


You can use Mockito.doNothing():

Mockito.doNothing().when(employeeDAO).deleteEmployee(Mockito.any());
like image 40
divilipir Avatar answered May 11 '26 01:05

divilipir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!