[JAVA] Mock static methods in Mockito 3.4

Overview

From version 3.4 of Mockito, static methods can be mocked. This eliminates the need to install PowerMock if you just want to mock static methods.

environment

In addition to the above jar, you will need new mockito-inline and byte-buddy-agent.

You can download them from Mockito Official Site and ByteBuddy Official Site, respectively.

version
java 8
JUnit 5

Sample code

Class to be mocked

Contains static methods.

public class MockedClass {

    public static String methodA() {
        return "val1";
    }

    public static String methodB() {
        return "val2";
    }

    public static String methodC(String str) {
        return str;
    }
}

Test class

public class MockedClassTest {

    @Test
    public void test() throws Exception {

        //Expected value
        String expected_methodA = "test";
        String expected_methodB = "val2";

        //Mocking the target class
        MockedStatic<MockedClass> mocked = Mockito.mockStatic(MockedClass.class);
        //Set a return value and stub
        mocked.when(MockedClass::methodA).thenReturn(expected_methodA);
        //If not stubbed
        mocked.when(MockedClass::methodB).thenCallRealMethod();

        //Run
        String actual_methodA = MockedClass.methodA();
        String actual_methodB = MockedClass.methodB();

        //Check the result
        assertEquals(expected_methodA, actual_methodA);
        assertEquals(expected_methodB, actual_methodB);
    }
}

To mock Mockito.mockStatic () ThenReturn () to set the return value If you want to call the real thing without setting the return value, thenCallRealMethod () You can use.

How to specify static method

In the sample code, it is specified by the method reference like MockedClass :: methodA, but the description method when there is an argument is as follows.

mocked.when(() -> { MockedClass.methodC(Mockito.anyString()); })
      .thenReturn("stub");

You can specify any () from Mockito in the argument list. Of course, writing with a lambda expression is valid even when there are no arguments. {} Can be omitted according to the lambda expression description rule.

mocked.when(() -> MockedClass.methodA())
      .thenReturn("stub");

Recommended Posts

Mock static methods in Mockito 3.4
Mock static methods with PowerMock
Changes in Mockito 2
Org.mockito.exceptions.misusing.InvalidUseOfMatchersException in Mockito
Check static and public behavior in Java methods
Mock test de Mockito
Dynamically call methods in JSF
About validation methods in JUnit
Mock and stub in RSpec
Helper methods available in devise
Test private methods in JUnit
Test private methods in JUnit
Disable static initializer in PowerMock
About Java static and non-static methods
Differences in split methods of StringUtils
Frequently used methods in Active Record
Mock only some methods with Spock
Ruby methods often used in Rails