Mockito:如何验证某些方法调用组的组顺序?

时间:2012-09-14 08:48:40

标签: java unit-testing tdd mockito verification

我正在使用Mockito来验证使用InOrder对象的方法调用的顺序。但是我对调用的总排序不感兴趣,只是在调用其他一些方法之前,某些方法调用都发生了。例如像这样

@Test
public void testGroupOrder() {
    Foo foo1 = mock(Foo.class);
    Foo foo2 = mock(Foo.class);
    Bar underTest = new Bar();
    underTest.addFoo(foo1);
    underTest.addFoo(foo2);

    underTest.fire()

    InOrder inOrder = inOrder(foo1,foo2);

    inorder.verify(foo1).doThisFirst();
    inorder.verify(foo2).doThisFirst();

    inorder.verify(foo1).beforeDoingThis();
    inorder.verify(foo2).beforeDoingThis();
}

但是这个测试确实测试得太多了,因为它测试了Foo个实例的顺序。但我只对不同方法的顺序感兴趣。实际上,我希望underTest不区分Foo的实例,它们可能有内部顺序,因此无论调用foos的顺序都无关紧要。我想将其作为实施细节。

但是,在任何其他foo上调用doThisFirst()之前,在{em>所有 foos上调用beforeDoingThis()非常重要。有可能用Mockito表达吗?怎么样?

2 个答案:

答案 0 :(得分:7)

Mockito验证传递给inorder函数的所有模拟的顺序。因此,如果您不想验证foos的顺序,则需要创建两个单独的in-order。即。

@Test
public void testGroupOrder() {
    Foo foo1 = mock(Foo.class);
    Foo foo2 = mock(Foo.class);
    Bar underTest = new Bar();
    underTest.addFoo(foo1);
    underTest.addFoo(foo2);

    underTest.fire()

    InOrder inOrderFoo1 = inOrder(foo1);
    inOrderFoo1.verify(foo1).doThisFirst();
    inOrderFoo1.verify(foo1).beforeDoingThis();

    InOrder inOrderFoo2 = inOrder(foo2);
    inOrderFoo2.verify(foo2).doThisFirst();
    inOrderFoo2.verify(foo2).beforeDoingThis();
}

答案 1 :(得分:2)

您可以通过实施自己的验证模式访问内部(感谢this answer教我,我的代码基于它)。实施并不完整,但您会明白这一点。

不幸的是,Mockito没有记录这个界面,他们可能认为它是内部的(因此在未来的版本中它可能不会100%稳定)。

verify(foo1, new DoFirst()).doThisFirst();
verify(foo2, new DoFirst()).doThisFirst();
verify(foo1, new DoSecond()).beforeDoingThis();
verify(foo1, new DoSecond()).beforeDoingThis();

然后

// Set to true when one 
boolean secondHasHappened = false; 

// Inner classes so they can reach the boolean above.
// Gives an error of any DoSecond verification has happened already.
public class DoFirst implements VerificationMode {
   public void verify(VerificationData data) {
      List<Invocation> invocations = data.getAllInvocations()
      InvocationMatcher matcher = data.getWanted();
      Invocation invocation = invocations.get(invocations.size() - 1);
      if (wanted.matches(invocation) && secondHasHappened) throw new MockitoException("...");
   }
}

// Registers no more DoFirst are allowed to match.
public class DoSecond implements VerificationMode {
    public void verify(VerificationData data) {
       List<Invocation> invocations = data.getAllInvocations()
       InvocationMatcher matcher = data.getWanted();
       Invocation invocation = invocations.get(invocations.size() - 1);
       if (!wanted.matches(invocation)) secondHasHappened = true;
    }
}