Is it possible to Mock a single method of a Java class?
For example:
class A { long method1(); String method2(); int method3(); } // in some other class class B { void someMethod(A a) { // how would I mock A.method1(...) such that a.method1() returns a value of my // choosing; // whilst leaving a.method2() and a.method3() untouched. } }
We can mock runInGround(String location) method inside the PersonTest class as shown below. Instead of using mock(class) here we need to use Mockito. spy() to mock the same class we are testing. Then we can mock the method we want as follows.
mock() method with Class: It is used to create mock objects of a concrete class or an interface. It takes a class or an interface name as a parameter. mock() method with Answer: It is used to create mock objects of a class or interface with a specific procedure.
For Mockito, there is no direct support to mock private and static methods. In order to test private methods, you will need to refactor the code to change the access to protected (or package) and you will have to avoid static/final methods.
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
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);
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