Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon Mockito


Mockito


Overview of Mockito

**Mockito is a popular open-source mocking framework for Java, released under the MIT License. It is widely used in unit testing to create mock objects, which are test doubles that mimic the behavior of real objects in a controlled environment. This allows developers to isolate dependencies and test specific components of their system without relying on external systems or services[2][3].

Key Features of Mockito

- Mock Object Creation: Mockito provides two primary ways to create mock objects: using the `@Mock` annotation or the `mock()` static method. These methods allow developers to create mock instances of classes or interfaces[3][4].

- Behavior Verification: Mockito offers the `verify()` method to check if a method on a mock object was called with specific parameters. This helps ensure that the system under test interacts correctly with its dependencies[3].

- Stubbing: Developers can use the `when()` method to define the behavior of mock objects. For example, specifying what value should be returned when a certain method is called[3].

- Annotations: Mockito provides annotations like `@InjectMocks` to inject mock objects into the class being tested, simplifying the setup of test environments[4].

Using Mockito with Other Frameworks

Mockito is often used in conjunction with testing frameworks such as JUnit and TestNG. For JUnit 5, the `mockito-junit-jupiter` dependency is required in addition to `mockito-core` to enable seamless integration[3].

Example Usage

Here's a simple example of using Mockito with JUnit 5:

java
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;

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

public class CalcServiceTest {

    @Test
    void testCalc() {
        AddService addService = Mockito.mock(AddService.class);
        CalcService calcService = new CalcService(addService);

        int num1 = 11;
        int num2 = 12;
        int expected = 23;

        Mockito.when(addService.add(num1, num2)).thenReturn(expected);

        int actual = calcService.calc(num1, num2);

        assertEquals(expected, actual);
    }
}

Other Mockito Implementations

While Mockito is primarily associated with Java, there are similar mocking frameworks for other languages, such as the Mockito package for Dart, which supports creating mocks and verifying behavior in Dart applications[5].

Citations:
[1] https://site.mockito.org
[2] https://en.wikipedia.org/wiki/Mockito
[3] https://www.digitalocean.com/community/tutorials/mockito-tutorial
[4] https://dev.to/whathebea/how-to-use-junit-and-mockito-for-unit-testing-in-java-4pjb
[5] https://pub.dev/packages/mockito
[6] https://github.com/mockito/mockito
[7] https://www.tutorialspoint.com/mockito/index.htm
[8] https://javadoc.io/doc/org.mockito/mockito-core/latest/org/mockito/Mockito.html