How To Mock Void Methods With Mockito
Part 1 – What is Mockito?
In this tutorial, we will understand below topics –
– What is a Mock Object?
– When should I mock?
– Mockito Framework
– Enable Mockito Annotations
– How to Mock Object with @Mock & @InjectMock annotations in Spring application?
https://www.onlyfullstack.com/what-is-mock-object-what-is-mockito/
1. when/then
2. when/thenThrow
3. when/thenAnswer
https://www.onlyfullstack.com/how-to-mock-methods-with-mockito/
Mocking Void Methods
Let’s add a method which internally calls the void method of another component.
public Customer updateCustomer(Customer customer) { if (customer == null || customer.getId() < 0) { throw new IllegalArgumentException("Invalid Customer details passed."); } repository.updateCustomer(customer); return customer; }
In the above example, updateCustomer is calling the void method of the repository object. Let’s see how to mock this method to write a unit test for updateCustomer() of EmployeeService.
1. doNothing/when –
If you don’t want to check for params and just skip the actual execution then we can use doNothing which will not do anything when this method is called during the test case.
@Test public void updateCustomer_doNothing_when() { Customer customer = new Customer(6, "QQQ", "Mumbai"); doNothing().when(repository).updateCustomer(any(Customer.class)); customerService.updateCustomer(customer); }
2. doAnswer/when –
We have a updateCustomer method in CustomerService class which calls a void method updateCustomer of CustomerRepository. Now we need to mock this void method and make sure the params passed to this method is as per the expectation.
@Test public void updateCustomer_doAnswer_when() { Customer customer = new Customer(6, "QQQ", "Mumbai"); doAnswer((arguments) -> { System.out.println("Inside doAnswer block"); assertEquals(customer, arguments.getArgument(0)); return null; }).when(repository).updateCustomer(any(Customer.class)); customerService.updateCustomer(customer); }
3. doThrow/when-
When we want to throw an exception from the void method or normal method then we can use doThrow/when pattern.
@Test(expected = Exception.class) public void updateCustomer_doNothing_when() { Customer customer = new Customer(6, "QQQ", "Mumbai"); doThrow(new Exception("Database connection issue"))
.when(repository).updateCustomer(any(Customer.class)); customerService.updateCustomer(customer); }
Source Code
Download the source code of JUnit tutorial from below git repository :
unit-testing-and-integration-testing-with-spring-boot
Let’s go to our next tutorial where we will discuss below points :
– Simple verify method
– Variations in verify method
– Verify with the number of times
– Mockito Verify Order of Invocation
https://www.onlyfullstack.com/how-to-verify-the-mocks-in-mockito/
Mockito Tutorial
https://www.onlyfullstack.com/mockito-tutorial/