How to mock a single method in java

java, mocking

Solution

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

Problem

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. } } ```

Original source

Related problems