2016-07-22 44 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

没有必要道歉,但如果您想帮助未来的读者充分利用他们的时间,请在您的问题和答案中添加有关您的设置的详细信息,以及您需要检查/调整哪些配置设置以便进行测试更好地工作。 –