Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Mockito for Unit Testing

1. Introduction

Mockito is a popular mocking framework for Java that allows you to create mock objects for unit testing. It enables the isolation of the class under test by simulating its dependencies.

2. Key Concepts

Key Definitions

  • Mock: A simulated object that mimics the behavior of real objects in controlled ways.
  • Spy: A partial mock that allows you to call real methods while also allowing you to stub some methods.
  • Stub: A method that provides predefined responses to method calls made during the test.

3. Setup

Important: Ensure you have JUnit and Mockito dependencies in your build configuration (e.g., Maven or Gradle).

        // Maven Dependency for Mockito
        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-core</artifactId>
            <version>3.12.4</version>
            <scope>test</scope>
        </dependency>
        

4. Basic Mocking

Mocking a class with Mockito is straightforward. Here's an example:


        import static org.mockito.Mockito.*;

        public class UserServiceTest {
            @Test
            public void testGetUser() {
                UserRepository mockRepo = mock(UserRepository.class);
                User user = new User("John");
                when(mockRepo.findUser("John")).thenReturn(user);

                UserService userService = new UserService(mockRepo);
                User result = userService.getUser("John");

                assertEquals("John", result.getName());
            }
        }
        

5. Advanced Features

Mockito offers advanced functionalities such as argument matchers, verification, and exceptions:


        // Using argument matchers
        when(mockRepo.findUser(anyString())).thenReturn(user);

        // Verifying interactions
        verify(mockRepo).findUser("John");

        // Stubbing to throw exceptions
        when(mockRepo.findUser("Invalid")).thenThrow(new UserNotFoundException());
        

6. Best Practices

  • Keep tests focused on one behavior.
  • Use meaningful names for mocks and tests.
  • Limit the number of interactions in your tests.
  • Use @Mock and @InjectMocks annotations for cleaner tests.

7. FAQ

What is the difference between a mock and a spy?

A mock is a complete fake that simulates the behavior of a real object. A spy, on the other hand, is a real object that you can partially mock.

Can Mockito be used with JUnit 5?

Yes, Mockito is compatible with JUnit 5. You can use the Mockito Extension for JUnit 5.