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()...
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.