是否可以模拟 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 的
spy 机制:
A a = new A();
A aSpy = Mockito.spy(a);
Mockito.when(aSpy.method1()).thenReturn(5l);
对于任何未 stub 的方法,使用 spy 调用包装对象的默认行为。
关于java - 如何在java中模拟单个方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10895605/