如何在Java中模拟单个方法


问题内容

是否可以模拟Java类的单个方法?

例如:

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

问题答案:

使用Mockito's间谍机制:

A a = new A();
A aSpy = Mockito.spy(a);
Mockito.when(aSpy.method1()).thenReturn(5l);

间谍的使用将为未存根的任何方法调用包装对象的默认行为。

Mockito.spy() /
@间谍