首页 > 解决方案 > Mockito 核心匹配器-GreaterThan

问题描述

我正在尝试在我的项目中升级 mockito 版本。

当前版本:mockito-all [1.9.5]

升级到:mockito-core [2.8.8]

我的一些旧测试在这个问题上失败了

测试:

.andExpect(jsonPath("$.paymentTransaction.totalAmount").value(new GreaterThan<Double>(0.0D)))

失败消息:

java.lang.AssertionError: For JSON path $.paymentTransaction.totalAmount type of value 
Expected :class org.mockito.internal.matchers.GreaterThan
Actual   :class java.lang.Double

任何线索,如果要通过 mockito 版本升级以不同的方式处理?

标签: junitmockitomatcherspring-test-mvc

解决方案


您最终使用了错误的重载:

public ResultMatcher value(Object expectedValue) https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/test/web/servlet/result/JsonPathResultMatchers.html#value-java.lang.Object-

代替

public <T> ResultMatcher value(Matcher<T> matcher) https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/test/web/servlet/result/JsonPathResultMatchers.html#value-org.hamcrest.Matcher-

原因是你使用了 Mockito 的 matcher,而不是 Hamcrest 的。你需要使用: org.hamcrest.Matchers.greaterThan(T value)

另外,请注意,jsonPath将 Hamcrest 匹配器作为第二个参数存在过载(无需调用value


推荐阅读