I am testing a class and want to mock a method call in it:
class B{
method A();
String method C();
}
Now, I want to test method A, and mock call to method C, as method C reads input from a URL. How can I do this using Mockito?
You have a number of options here.
Probably the simplest - you could use a mockito spy (http://docs.mockito.googlecode.com/hg/latest/org/mockito/Mockito.html#13), which is an object where you can stub some of the methods, and the others retain their existing behaviour.
Or, you could use a mock, and then stub methodA using either the static doCallRealMethod method, using when in combination with thenCallRealMethod.
But best of all in my opinion would be to refactor your class so that the part that reads from the URL is in a separate class. Then write a unit test for class B, using a mock for the separate class. Then write an integration test for the class that reads from the URL.
Please post a comment here if this approach is not clear; I'll try to elaborate.
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