Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

227
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda