如何对具有特定属性的参数的方法进行存根?例如 :doReturn(true).when(object).method( // an object that has a property prop1 equals to "myprop1" // and prop2 equals to "myprop2") 最佳答案 您将需要一个自定义的Mockito匹配器或Hamcrest匹配器来解决此问题,或者将两者混合使用。 The two work a little differently,但是您可以将它们与适配器一起使用。与Hamcrest您需要使用Matchers.argThat(Mockito 1.x)或MockitoHamcrest.argThat(Mockito 2.x)来调整Hamcrest hasProperty匹配器并将其组合。doReturn(true).when(object).method( argThat(allOf(hasProperty("prop1", eq("myProp1")), hasProperty("prop2", eq("myProp2")))))在这里,argThat使Hamcrest匹配器适应Mockito,allOf确保只匹配同时满足两个条件的对象,hasProperty检查该对象,并eq(尤其是Hamcrest的eq,而不是Mockito的)比较字符串相等性。没有Hamcrest从Mockito v2.0(现在为Beta版)开始,Mockito不再直接依赖Hamcrest,因此您可能希望以类似的样式对Mockito的ArgumentMatcher类执行相同的逻辑。doReturn(true).when(object).method( argThat(new ArgumentMatcher<YourObject>() { @Override public boolean matches(Object argument) { if (!(argument instanceof YourObject)) { return false; } YourObject yourObject = (YourObject) argument; return "myProp1".equals(yourObject.getProp1()) && "myProp2".equals(yourObject.getProp2()); } }))自然,同样的自定义匹配器类技术也可以用于Hamcrest,但是如果您确定要使用Hamcrest,则可能更喜欢上面的eq技术。重构提醒您一点:尽管欢迎您按自己的意愿保存Matcher对象(以静态辅助方法返回或保存在字段中),但要调用hasProperty has side effects,因此必须在调用过程中进行呼叫argThat。换句话说,如果需要,请保存并重用method或Matcher实例,但不要将对ArgumentMatcher的调用重构,除非您将其重构为静态方法,这样argThat仍会在右侧被调用时间。// GOOD with Hamcrest's Matcher:Matcher<YourObject> hasTwoProperties = (...)doReturn(true).when(object).method(argThat(hasTwoProperties));// GOOD with Mockito's ArgumentMatcher:ArgumentMatcher<YourObject> hasTwoProperties = (...)doReturn(true).when(object).method(argThat(hasTwoProperties));// BAD because argThat is called early:YourObject expectedObject = argThat(...);doReturn(true).when(object).method(expectedObject);// GOOD because argThat is called correctly within the method call:static YourObject expectedObject() { return argThat(...); }doReturn(true).when(object).method(expectedObject());关于java - 如何使用具有特定属性的参数对方法进行 stub ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/37345213/ 10-09 05:28