Mockito - 如何验证间接私有字段对象进行的方法调用

时间:2014-07-06 17:58:38

标签: java mockito verify

我正在尝试验证由间接私有字段对象进行的方法调用。例如

要测试的代码:

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

我想验证运行A.methodToTest()时是否调用了b.wantToVerifyThisIsCalled()方法;

我试过这样的事情,但这不起作用:

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 :(

谢谢

1 个答案:

答案 0 :(得分:3)

这种情况正在发生,因为调用B方法的wantToVerifyThisIsCalled()类对象不是您的模拟对象。您应该将模拟对象注入A

如果您的A类构造函数直接使用B实例而不是CD,并依赖它来创建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();