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.
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 |
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;
}
}
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.
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