我有3个测试方法的测试类。基本上我想要做的是对每个测试中使用不同的客户,并分配给每个客户的权限在看起来很像一个常见的方法想通了:是否Mockito缓存thenAnswer块?
protected void setupCustomerPermissions(final IntegrationTestCustomer customer)
{
System.out.println("customer = " + customer.getName());
when(permissionClient.createToken()).thenAnswer(invocation ->
{
System.out.println("customer again = " + customer.getName());
if (customer.equals(IntegrationTestCustomer.KRISTIN())) {
return createToken(IntegrationTestCustomer.KRISTIN());
} else if (customer.equals(IntegrationTestCustomer.FRED())) {
return createToken(IntegrationTestCustomer.FRED());
} else if (customer.equals(IntegrationTestCustomer.DANIELA())) {
return createToken(IntegrationTestCustomer.DANIELA());
}
throw new IllegalStateException("IntegrationTestCustomer:[" + customer.getName() + "] shouldn't have got this far");
});
}
基本上,我有3次测试:第一次使用KRISTIN作为客户,第二次使用FRED,第三次使用KRISTIN。
请注意System.out.println
调用。当第一次测试运行(使用KRISTIN作为客户),这是会打印:
customer = KRISTIN
customer again = KRISTIN
到目前为止,一切都很好。现在到了有趣的部分。第二个测试(使用FRED作为客户)打印此:
customer = FRED
customer again = KRISTIN
然后第三个测试,再次使用KRISTIN,版画:
customer = KRISTIN
customer again = FRED
我不知道我在做什么错在这里...应该都打System.out.println
打印同一个客户? Mockito是否有某种缓存?
备注:您可能想听http://www.se-radio.net/2016/05/se-radio-episode-256-jay-fields-on-working-effectively-with-unit-测试/ ......那个家伙争辩说,在你的单元测试中有像Kristin和其他人一样的“测试角色”这个想法,现在几乎是一个**反模式**。 – GhostCat
尝试PowerMockito –
@IndraUprade感谢您的建议,但我不知道我明白了。 PowerMockito如何解决这个问题? – felipecao