How to mock static object inside an Interface by using JUnit5 in Java?

 Mocking static objects inside an interface using JUnit5 requires the use of a mocking framework. One popular mocking framework in Java is Mockito. Here are the steps to mock a static object inside an interface using JUnit5 and Mockito:

Add the Mockito library to your project. You can do this by adding the following dependency to your build file:

<dependency>

    <groupId>org.mockito</groupId

    <artifactId>mockito-core</artifactId>

    <version>3.12.4</version>

    <scope>test</scope>

</dependency>

Import the necessary classes from the Mockito library:

import static org.mockito.Mockito.mockStatic;

import static org.mockito.ArgumentMatchers.anyString;

Use the mockStatic() method to mock the static object inside the interface:

@Test

void testStaticObjectInsideInterface() {

    try (MockedStatic<MyInterface> mocked = mockStatic(MyInterface.class)) {

        mocked.when(() -> MyInterface.myMethod(anyString())).thenReturn("Mocked response");


        // call the method that uses the static object inside the interface

        String result = MyInterface.myMethod("input");


        // assert that the result is the mocked response

        assertEquals("Mocked response", result);

    }

}

In this example, we are using the MockedStatic class provided by Mockito to mock the static object inside the MyInterface interface. We use the when() method to specify the behavior of the mocked method, and then we call the method that uses the static object inside the interface. Finally, we assert that the result is equal to the mocked response.


Note that we are using a try-with-resources statement to automatically close the MockedStatic instance after the test is run. This is important to ensure that the static object is properly reset after the test, and to avoid interfering with other tests that may use the same static object.

No comments:

Post a Comment