我正在尝试编写一个单元测试(使用 JMockit)来验证方法是根据部分顺序调用的。具体用例是确保在事务中调用某些操作,但更一般地说,我想验证这样的事情:
- 方法
beginTransaction
被调用。 operation1
通过 to的方法以operationN
任意顺序调用。- 方法
endTransaction
被调用。 someOtherOperation
在事务之前、期间或之后的某个时间调用方法。
期望和验证 API 似乎无法处理此要求。
如果我有,@Mocked BusinessObject bo
我可以验证是否调用了正确的方法(以任何顺序):
new Verifications() {{
bo.beginTransaction();
bo.endTransaction();
bo.operation1();
bo.operation2();
bo.someOtherOperation();
}};
可以选择FullVerifications
检查是否没有其他副作用。
要检查排序约束,我可以执行以下操作:
new VerificationsInOrder() {{
bo.beginTransaction();
unverifiedInvocations();
bo.endTransaction();
}};
但这不处理这种someOtherOperation
情况。我无法替换为unverifiedInvocations
,bo.operation1(); bo.operation2()
因为这会对调用进行总排序。业务方法的正确实现可以调用bo.operation2(); bo.operation1()
.
如果我做到了:
new VerificationsInOrder() {{
unverifiedInvocations();
bo.beginTransaction();
unverifiedInvocations();
bo.endTransaction();
unverifiedInvocations();
}};
someOtherOperation
然后在事务之前调用时出现“没有未验证的调用”失败。尝试bo.someOtherOperation(); minTimes = 0
也无济于事。
那么:有没有一种简洁的方法来使用 JMockIt 中的 Expectations/Verifications API 来指定方法调用的部分排序要求?或者我是否必须使用 aMockClass
并手动跟踪调用,a la:
@MockClass(realClass = BusinessObject.class)
public class MockBO {
private boolean op1Called = false;
private boolean op2Called = false;
private boolean beginCalled = false;
@Mock(invocations = 1)
public void operation1() {
op1Called = true;
}
@Mock(invocations = 1)
public void operation2() {
op2Called = true;
}
@Mock(invocations = 1)
public void someOtherOperation() {}
@Mock(invocations = 1)
public void beginTransaction() {
assertFalse(op1Called);
assertFalse(op2Called);
beginCalled = true;
}
@Mock(invocations = 1)
public void endTransaction() {
assertTrue(beginCalled);
assertTrue(op1Called);
assertTrue(op2Called);
}
}