Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

222
Views
Bypass static method in Mockito

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()));
    }
 }
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!