Mockito, know it and love it
- Mark Kendall
- Mar 18
- 2 min read
Creating tests using Mockito can be straightforward and developer-friendly if you follow a structured approach. Here are the overall steps to create tests for any artifact using Mockito:
1. Add Mockito Dependency
Ensure that Mockito is included in your project's dependencies. If you're using Maven, add the following to your pom.xml:
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>4.0.0</version>
<scope>test</scope>
</dependency>
2. Create the Test Class
Create a test class for the artifact you want to test. Annotate the class with @RunWith(MockitoJUnitRunner.class) to enable Mockito annotations.
3. Mock Dependencies
Use the @Mock annotation to create mock instances of the dependencies your artifact interacts with.
@RunWith(MockitoJUnitRunner.class)
public class MyServiceTest {
@Mock
private MyRepository myRepository;
@InjectMocks
private MyService myService;
// Other setup code
}
4. Initialize Mocks
If you're not using MockitoJUnitRunner, initialize the mocks manually in a setup method annotated with @Before.
@Before
public void setUp() {
MockitoAnnotations.openMocks(this);
}
5. Define Mock Behavior
Use when, thenReturn, doReturn, etc., to define the behavior of your mocks.
@Before
public void setUp() {
MockitoAnnotations.openMocks(this);
when(myRepository.findById(anyInt())).thenReturn(Optional.of(new MyEntity()));
}
6. Write Test Methods
Write test methods to verify the behavior of your artifact. Use assertions to check the expected outcomes.
@Test
public void testMyServiceMethod() {
MyDTO result = myService.myMethod(1);
assertNotNull(result);
assertEquals("ExpectedValue", result.getSomeProperty());
verify(myRepository, times(1)).findById(1);
}
7. Verify Interactions
Use verify to ensure that the expected methods on your mocks were called.
verify(myRepository, times(1)).findById(1);
8. Handle Edge Cases
Write additional tests to cover edge cases and ensure your artifact handles them correctly.
@Test
public void testMyServiceMethodWithInvalidId() {
when(myRepository.findById(anyInt())).thenReturn(Optional.empty());
MyDTO result = myService.myMethod(999);
assertNull(result);
verify(myRepository, times(1)).findById(999);
}
9. Run and Refactor
Run your tests to ensure they pass. Refactor your code and tests as needed to improve readability and maintainability.
Example
Here's a complete example for a service class:
@RunWith(MockitoJUnitRunner.class)
public class CustomerServiceTest {
@Mock
private CustomerRepository customerRepository;
@InjectMocks
private CustomerService customerService;
@Before
public void setUp() {
MockitoAnnotations.openMocks(this);
when(customerRepository.findById(anyInt())).thenReturn(Optional.of(new Customer()));
}
@Test
public void testCreateCustomer() {
CustomerDTO customerDTO = new CustomerDTO();
customerDTO.setCustomerName("New Customer");
Customer customer = new Customer();
customer.setCustomerName("New Customer");
when(customerRepository.save(any(Customer.class))).thenReturn(customer);
CustomerDTO result = customerService.create(customerDTO);
assertNotNull(result);
assertEquals("New Customer", result.getCustomerName());
verify(customerRepository, times(1)).save(any(Customer.class));
}
}
By following these steps, you can create comprehensive and maintainable tests for your artifacts using Mockito. If you have any more questions or need further assistance, feel free to ask! 😊
Commenti