简体   繁体   English

如何在测试方法中简化Mockito / hamcrest参数匹配器?

[英]How do I simplify mockito/hamcrest argument matchers in test method?

The test method below appear in a spring-guide tutorial . 以下测试方法出现在弹簧指南中 Is there a less convoluted syntax to write this test or how can I break it apart into smaller chunks? 是否有较不复杂的语法来编写此测试,或者如何将其拆分为较小的块?

verify(orderService).createOrder(
      org.mockito.Matchers.<CreateOrderEvent>argThat(
        allOf( org.hamcrest.Matchers.<CreateOrderEvent>
            hasProperty("details",
                hasProperty("dateTimeOfSubmission", notNullValue())),

        org.hamcrest.Matchers.<CreateOrderEvent>hasProperty("details",
                hasProperty("name", equalTo(CUSTOMER_NAME))),

        org.hamcrest.Matchers.<CreateOrderEvent>hasProperty("details",
                hasProperty("address1", equalTo(ADDRESS1))),
        org.hamcrest.Matchers.<CreateOrderEvent>hasProperty("details",
                hasProperty("postcode", equalTo(POST_CODE)))
    )));

You could switch the hasProperty and the allOf matchers. 您可以切换hasProperty和allOf匹配器。

verify(orderService).createOrder(
      org.mockito.Matchers.<CreateOrderEvent>argThat(
        org.hamcrest.Matchers.<CreateOrderEvent>hasProperty("details",
          allOf(
            hasProperty("dateTimeOfSubmission", notNullValue()),
            hasProperty("name", equalTo(CUSTOMER_NAME)),
            hasProperty("address1", equalTo(ADDRESS1)),
            hasProperty("postcode", equalTo(POST_CODE)))
    )));

Another way is to use an argument captor to record the argument value you're trying to verify. 另一种方法是使用参数捕获器来记录您要验证的参数值。

Then you can perform assertions on the value as you see fit. 然后,您可以根据需要对值执行断言。 This is a much clearer way of verifying the argument information is what is expected than using matchers. 与使用匹配器相比,这是一种更清晰的方法来验证参数信息是否正确。

This is explained more fully in the this great blog entry: 在这个很棒的博客文章中对此进行了更全面的说明:

http://www.planetgeek.ch/2011/11/25/mockito-argumentmatcher-vs-argumentcaptor/ http://www.planetgeek.ch/2011/11/25/mockito-argumentmatcher-vs-argumentcaptor/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM