Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

224
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda