Using Mockito Spy in One Class to Call Static Method from Another Class

Trying to use Mockito's spy function for my JUnit test. I originally had a Class:

public class App1 { 
    public String method1() {
        sayHello();
    }

    public sayHello() {
        Systems.out.println("Hello");
    }
}

Everything in my test class was working correctly with mockito spy on above class:

@Test(expected = IOException.class)
public void testMethod1Failure(){   
    App1 a1 = spy(App1);
    doThrow(IOException.class).when(a1).sayHello();

    a1.method1();
}

But after that i had to switch things around and take sayHello() method into another class to be used as static method:

public class App1 { 
    public String method1() {
        App2.sayHello();
    }
}

public class App2 { 
    public static void sayHello() {
        Systems.out.println("Hello");
    }
}

After this change, my original JUnit testcase is broken and i am unsure how i can use Mockito spy to start App1 that calls the external App2 static method... does anyone know how i can do it? Thanks in advance

1 Answer

Mockito does not support mocking static code. Here are some ways to handle it:

  • Use PowerMockito or similar framework as suggested here: Mocking static methods with Mockito.
  • Refactor your code converting static method back to an instance method. As you've found static methods are not easy to Unit test.
  • If it's inexpensive to execute actual static method in question then just call it.
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

David Miller

David Miller

Executive Financial & Market Analyst

David Miller brings 15 years of experience in global economics, personal finance strategy, and market dynamics. He specializes in turning complex economic trends into actionable insights for everyday readers.

Share this article
Twitter Facebook Pinterest