hamcrest matcher和argThat方法的问题

时间:2016-08-19 07:41:36

标签: java junit mockito hamcrest

我在我的测试类中得到了这段代码:

then(collector()).should().emit(eq(myStream), eq(myTuple),
        argThat(allOf(hasItem(anyString()), hasItem("test1"), hasItem("test2"))));

问题在于我不知道第一个Item的价值。我只知道值为String类型。

如果我执行测试,我收到了消息:

  

参数匹配器的使用无效! 3匹配预期,5记录

此外:

  

如果匹配器与原始值组合,则可能会发生此异常:       //不正确:       someMethod(anyObject()," raw String");使用匹配器时,所有参数都必须由匹配器提供。例如:       //正确:       someMethod(anyObject(),eq(" matcher by matcher"));

我看不出问题是对的。

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

问题是嵌套匹配器时不能使用Mockito Matchers。您必须使用Hamcrest或其他自定义匹配器。根本的问题是argThat被视为模拟匹配器以及anyString(),并且这些匹配器被应用于导致错误的单个参数(我不知道为什么模拟不支持此功能)。切换到anyString的Hamcrest匹配器可以解决此问题。请尝试以下操作:

then(collector()).should().emit(eq(myStream), eq(myTuple),
    argThat(allOf(hasItem(isA(String.class)), hasItem("test1"), hasItem("test2"))));