I am using Mockito to write a JUnit Test Case and I am trying to bypass a static method invocation inside my test method. I am getting a NullPointerException while running the Test Case.
Is there any way of bypassing the above mentioned invocation without using PowerMockito or what fixes are needed in the below mentioned approach?
Below are the code snippets which will help you understand the problem:
=> This is my Code for which I want to write a JUnit Test Case using Mockito.
class MyClassToTest{
public void methodToTest(){
JsonObject obj = MyUtilClass.staticMethod(arg1);
}
}
=> Below is the definition of the MyUtilClass:
class MyUtilClass{
public static JsonObject staticMethod(JsonObject arg1){
//use arg1 to populate return object
return jsonobject;
}
}
=> Below is the snippet of how my current Test Class and Test Method looks for MyClassToTest.methodToTest
class MyTestClass{
public void test_methodToTest(){
JsonObject dummy_jsonObject = new JsonObject().put("foo","foo");
doReturn(dummy_jsonObject).when(MyUtilClass.staticMethod(any()));
}
}
If you want to mock your staticMethod from MyUtilClass with Mockito (version 3.4.0 or greater required), the stubbing looks like the following (I assume you use a Java version > 9):
@Test
void shouldMockStatic() {
JsonObject dummy_jsonObject = new JsonObject().put("foo","foo");
try (MockedStatic<MyUtilsClass> mockedStatic = Mockito.mockStatic(MyUtilsClass.class)) {
mockedStatic.when(() -> MyUtilsClass.staticMethod(anyString()).thenReturn(dummy_jsonObject);
// now invoke your class under test
}
}
You can find further information and examples of this feature of Mockito here.