0
0
JunitComparisonBeginner · 4 min read

JUnit vs Mockito: Key Differences and When to Use Each

JUnit is a testing framework used to write and run tests for Java code, focusing on test structure and execution. Mockito is a mocking framework used within tests to create fake objects and define their behavior, helping isolate the code under test.
⚖️

Quick Comparison

This table summarizes the main differences between JUnit and Mockito.

AspectJUnitMockito
PurposeFramework for writing and running testsFramework for creating mock objects in tests
FocusTest lifecycle, assertions, and test organizationMocking dependencies and verifying interactions
UsageDefines test methods and assertionsCreates fake objects and stubs methods
Typical RoleTest runner and assertion providerMock object creation and behavior control
IntegrationCan be used alone or with mocking frameworksUsed inside test frameworks like JUnit
ExampleTesting a method's outputMocking a database call inside a test
⚖️

Key Differences

JUnit is primarily a test framework that provides annotations like @Test to mark test methods, and assertion methods such as assertEquals to check expected outcomes. It controls how tests are run and reported but does not provide tools to create fake objects.

Mockito, on the other hand, is a mocking library used inside tests to create mock objects that simulate the behavior of real dependencies. This helps isolate the code under test by replacing complex or external components with controllable mocks.

While JUnit manages the test execution and verification of results, Mockito focuses on setting up the environment inside tests by mocking and verifying interactions with dependencies. They often work together: JUnit runs the test, and Mockito helps prepare and verify the test conditions.

⚖️

Code Comparison

Here is a simple example using JUnit to test a method that adds two numbers.

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

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

class Calculator {
    int add(int a, int b) {
        return a + b;
    }
}
Output
Test passed
↔️

Mockito Equivalent

This example uses Mockito to mock a dependency inside a test, simulating a service call.

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

class UserServiceTest {
    @Test
    void testGetUserName() {
        UserRepository mockRepo = mock(UserRepository.class);
        when(mockRepo.getUserName(1)).thenReturn("Alice");

        UserService service = new UserService(mockRepo);
        String name = service.getUserName(1);

        assertEquals("Alice", name);
        verify(mockRepo).getUserName(1);
    }
}

interface UserRepository {
    String getUserName(int id);
}

class UserService {
    private final UserRepository repo;
    UserService(UserRepository repo) {
        this.repo = repo;
    }
    String getUserName(int id) {
        return repo.getUserName(id);
    }
}
Output
Test passed
🎯

When to Use Which

Choose JUnit when you need to write and run tests that check your code's correctness with assertions and test lifecycle management. It is the foundation for Java testing.

Choose Mockito when your tests require isolating the code under test by mocking dependencies, especially when those dependencies are complex, slow, or have side effects. Use it inside JUnit tests to create controlled test environments.

In practice, use JUnit for structuring and running tests, and add Mockito when you need to simulate or verify interactions with other objects.

Key Takeaways

JUnit is for writing and running tests with assertions.
Mockito is for creating mock objects to isolate code during tests.
They complement each other: JUnit runs tests, Mockito mocks dependencies.
Use Mockito when your code depends on external or complex components.
Use JUnit as the base framework for all Java testing.