gpt4 book ai didi

java - Mockito's Matcher vs Hamcrest Matcher?

转载 作者:IT老高 更新时间:2023-10-28 20:54:42 24 4
gpt4 key购买 nike

这将是一个简单的问题,但如果我的类路径中包含两个库,我找不到它们之间的区别以及使用哪一个?

最佳答案

Hamcrest 匹配器方法返回 Matcher<T>和 Mockito 匹配器返回 T。因此,例如:org.hamcrest.Matchers.any(Integer.class)返回 org.hamcrest.Matcher<Integer> 的实例, 和 org.mockito.Matchers.any(Integer.class)返回 Integer 的实例.

这意味着您只能在 Matcher<?> 时使用 Hamcrest 匹配器。签名中需要对象 - 通常在 assertThat 中来电。在调用模拟对象的方法的地方设置期望或验证时,您可以使用 Mockito 匹配器。

例如(为了清楚起见,使用完全限定的名称):

@Test
public void testGetDelegatedBarByIndex() {
Foo mockFoo = mock(Foo.class);
// inject our mock
objectUnderTest.setFoo(mockFoo);
Bar mockBar = mock(Bar.class);
when(mockFoo.getBarByIndex(org.mockito.Matchers.any(Integer.class))).
thenReturn(mockBar);

Bar actualBar = objectUnderTest.getDelegatedBarByIndex(1);

assertThat(actualBar, org.hamcrest.Matchers.any(Bar.class));
verify(mockFoo).getBarByIndex(org.mockito.Matchers.any(Integer.class));
}

如果您想在需要 Mockito 匹配器的上下文中使用 Hamcrest 匹配器,您可以使用 org.mockito.Matchers.argThat (或 org.mockito.hamcrest.MockitoHamcrest.argThat 中的 Mockito 2 )。它将 Hamcrest 匹配器转换为 Mockito 匹配器。因此,假设您想以某种精度(但不多)匹配 double 值。在这种情况下,您可以这样做:

when(mockFoo.getBarByDouble(argThat(is(closeTo(1.0, 0.001))))).
thenReturn(mockBar);

关于java - Mockito's Matcher vs Hamcrest Matcher?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8348046/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com