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

家住魔仙堡 提交于 2019-12-13 02:41:19

问题


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)))
    )));

回答1:


You could switch the hasProperty and the allOf matchers.

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)))
    )));



回答2:


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/



来源:https://stackoverflow.com/questions/19482372/how-do-i-simplify-mockito-hamcrest-argument-matchers-in-test-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!