Core Java

JUnit vs Mockito: How They Differ

When it comes to developing Java applications, unit testing is an essential practice. Two widely used tools in this domain are JUnit and Mockito. While they serve complementary purposes, understanding their distinct roles and how to use them is crucial for effective unit testing. This article aims to clarify the differences between JUnit and Mockito with illustrative code examples.

1. What is JUnit?

JUnit is a unit testing framework for Java that allows you to write and run repeatable tests. It provides a set of annotations and methods to define test cases, assert expected results, and report test failures. JUnit is primarily used to test the functionality of individual units of code, such as methods or classes.

1.1 JUnit Example

Let’s start with a simple JUnit test case. Consider a Calculator class with an add method:

public class Calculator {
    public int add(int a, int b) {
        return a + b;
    }
}

A JUnit test for the add method might look like this:

import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;

public class CalculatorTest {

    @Test
    public void testAdd() {
        Calculator calculator = new Calculator();
        int result = calculator.add(2, 3);
        assertEquals(5, result, "2 + 3 should equal 5");
    }
}

In this example, we have a simple Calculator class with an add method, and a CalculatorTest class that tests the add method using JUnit.

2. What is Mockito?

Mockito is a mocking framework for Java that allows you to create mock objects for testing purposes. It provides a way to isolate dependencies and focus on the behavior of the code under test. Mockito is primarily used to test the interactions between objects, rather than the functionality of individual units of code.

2.1 Mockito Example

Let’s, consider a UserService class that depends on a UserRepository. Instead of interacting with a real database, we can use Mockito to create a mock UserRepository.

public class UserService {
    private UserRepository userRepository;

    public UserService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    public User findUserById(int id) {
        return userRepository.findById(id);
    }
}

The UserRepository interface might look like this:

public interface UserRepository {
    User findById(int id);
}

A Mockito test for the UserService class might look like this:

import org.junit.jupiter.api.Test;
import static org.mockito.Mockito.*;
import static org.junit.jupiter.api.Assertions.assertEquals;

public class UserServiceTest {

    @Test
    public void testFindUserById() {
        UserRepository mockRepository = mock(UserRepository.class);
        UserService userService = new UserService(mockRepository);

        User user = new User(1, "John Doe");
        when(mockRepository.findById(1)).thenReturn(user);

        User result = userService.findUserById(1);
        assertEquals(user, result);
    }
}

In this example, we have a Service class (UserService) that depends on a Repository class (UserRepository), and a UserServiceTest class that tests the findUserById(int id) method using Mockito. We create a mock object for the Repository class using Mockito’s mock method, and then verify that the findById method was called with the expected argument.

3. Some Key Differences and Working Together

Here’s a table summarizing some of the key distinctions between JUnit and Mockito:

FeatureJUnitMockito
PurposeUnit testing framework. JUnit is a general testing framework.Mocking framework for unit testing. Mockito is specifically for creating mock objects and defining their behavior.
FunctionalityProvides structure and assertions. JUnit provides annotations and assertions for writing tests.Creates mock objects and defines their behavior. Mockito provides methods to create mocks, define their behavior, and verify interactions.
IntegrationIntegrates with build tools and runners.Works seamlessly with JUnit and other frameworks

While JUnit orchestrates the testing process, Mockito empowers you to create controlled environments for testing by isolating your code from external dependencies. They can work effectively together: JUnit providing the testing framework, and using Mockito to enhance your tests by managing dependencies and interactions with mock objects.

4. Conclusion

In this article, we’ve explored the key differences between JUnit and Mockito, two essential tools for unit testing in Java. JUnit provides a framework for writing and running tests, complete with annotations and assertions to ensure your code behaves as expected. Mockito, on the other hand, allows you to create mock objects and define their behavior, making it easier to isolate and test specific components without relying on real dependencies.

5. Download the Source Code

This was an article on Junit vs Mockito.

Download
You can download the full source code of this example here: junit vs mockito

Omozegie Aziegbe

Omos Aziegbe is a technical writer and web/application developer with a BSc in Computer Science and Software Engineering from the University of Bedfordshire. Specializing in Java enterprise applications with the Jakarta EE framework, Omos also works with HTML5, CSS, and JavaScript for web development. As a freelance web developer, Omos combines technical expertise with research and writing on topics such as software engineering, programming, web application development, computer science, and technology.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button