Using Mockito spy in one class to Call static method from another class
33,462
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.
Author by
R.C
Updated on April 04, 2020Comments
-
R.C about 4 years
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