【问题标题】:How do I simplify mockito/hamcrest argument matchers in test method?如何在测试方法中简化 mockito/hamcrest 参数匹配器?
【发布时间】:2013-10-20 20:18:23
【问题描述】:

下面的测试方法出现在spring-guide tutorial中。 编写此测试是否有不那么复杂的语法,或者如何将其分成更小的块?

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

【问题讨论】:

    标签: java spring unit-testing mockito hamcrest


    【解决方案1】:

    您可以切换 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)))
        )));
    

    【讨论】:

      【解决方案2】:

      另一种方法是使用参数捕获器来记录您尝试验证的参数值。

      然后您可以对值执行您认为合适的断言。这是一种比使用匹配器更清楚地验证参数信息是否符合预期的方法。

      这篇精彩的博客文章对此进行了更全面的解释:

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

      【讨论】:

      • 是的,当您发布此内容时,我已经写了一半的答案。但是这个解决方案比我要写的要好得多。 +1。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多