我正在尝试验证由间接私有字段对象进行的方法调用。例如
测试代码:
class A
{
final private B b;
public A(C c, D d)
{
this.b = new B(c,d);
}
public void methodToTest()
{
b.wantToVerifyThisIsCalled();
}
}
class B
{
private C c;
private D d;
public B(C c, D d)
{
this.c = c;
this.d = d;
}
...
public void wantToVerifyThisIsCalled()
{
//do stuff
return;
}
}
我想验证b.wantToVerifyThisIsCalled()方法被调用时,我运行A.methodToTest();
我试过这样做,但这不起作用:
C c = mock(C.class);
D d = mock(D.class);
A a = new A(C,D);
B b = moc(B.class);
a.methodToTest();
verify(b).wantToVerifyThisIsCalled(); \<-- This gives me error, wanted but not invoked
我该如何验证类A的b字段对象确实在进行方法调用?
没有setter方法,字段对象也被标记为final:(
谢谢
这是因为调用wantToVerifyThisIsCalled()
方法的B
类对象不是您的模拟对象。您应该将模拟对象注入A
。
如果你的A
类构造函数直接使用B
实例而不是C
和D
,并依靠它来创建B
类对象,那将会更好。
试着这样修改你的类:
class A {
private final B b;
public A(B b) { this.b = b; }
public void methodToTest() {
b.wantToVerifyThisIsCalled();
}
}
class B {
private final C c;
private final D d;
public B(C c, D d) { this.c = c; this.d = d; }
public void wantToVerifyThisIsCalled() { ... }
}
然后像这样测试:
C c = mock(C.class);
D d = mock(D.class);
B b = mock(B.class);// Find a way to set private fields (May be provide setters).
A a = new A(b);
a.methodToTest();
verify(b).wantToVerifyThisIsCalled();