2016-07-22 42 views
2

我有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是否有某種緩存?

+0

備註:您可能想聽http://www.se-radio.net/2016/05/se-radio-episode-256-jay-fields-on-working-effectively-with-unit-測試/ ......那個傢伙爭辯說,在你的單元測試中有像Kristin和其他人一樣的「測試角色」這個想法,現在幾乎是一個**反模式**。 – GhostCat

+0

嘗試PowerMockito –

+1

@IndraUprade感謝您的建議,但我不知道我明白了。 PowerMockito如何解決這個問題? – felipecao

回答

0

我想出問題是Spring安全測試配置的緩存設置。

+2

沒有必要道歉,但如果您想幫助未來的讀者充分利用他們的時間,請在您的問題和答案中添加有關您的設置的詳細信息,以及您需要檢查/調整哪些配置設置以便進行測試更好地工作。 –