Is it possible to Mock a single method of a Java class?
For example:
class A {
long method1();
String method2();
int method3();
}
// in
Use the spy() method from Mockito, and mock your method like this:
import static org.mockito.Mockito.*;
...
A a = spy(new A());
when(a.method1()).thenReturn(10L);
You could simply create a subclass of A
that overrides method1()
.
Assuming you are using jmockit:
public void testCase(@Mocked("methodToBeMocked") final ClassBoBeMocked mockedInstance) {
new Expectations() {{
mockedInstance.methodToBeMocked(someParameter); returns(whateverYouLikeItToReturn);
}}
mockedInstance.callSomemethod();
}
Use Mockito's
spy mechanism:
A a = new A();
A aSpy = Mockito.spy(a);
Mockito.when(aSpy.method1()).thenReturn(5l);
The use of a spy calls the default behavior of the wrapped object for any method that is not stubbed.
Mockito.spy()/@Spy