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
Spies allow us to partially mock. This means that we can mock a part of the object but allow for real method calls for the rest of the object. Here, we are creating a wrapper method that calls the static method. Now, in our regularMethod, we can call this wrapper class instead of calling the static class directly.
Mockito allows us to create mock objects. Since static method belongs to the class, there is no way in Mockito to mock static methods. However, we can use PowerMock along with Mockito framework to mock static methods.
To define mock behavior and to verify static method invocations, use the MockedStatic reference returned from the Mockito. mockStatic() method. It is necessary to call ScopedMock. close() method to release the static mock once it has been used and is no longer needed.
The powerful capabilities of the feature-rich JustMock framework allow you to mock static classes and calls to static members like methods and properties, set expectations and verify results. This feature is a part of the fastest, most flexible and complete mocking tool for crafting unit tests.
Mockito does not support mocking static code. Here are some ways to handle it:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With