我有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