這將是一個容易的,但我無法找到它們之間的區別和使用哪一個,如果我的類路徑中都包含lib的話?Mockito's Matcher vs Hamcrest Matcher?
回答
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
匹配。它將Hamcrest匹配器轉換爲Mockito匹配器。所以,假設你想以某種精度匹配一個double值(但不是很多)。在這種情況下,你可以這樣做:
when(mockFoo.getBarByDouble(argThat(is(closeTo(1.0, 0.001))))).
thenReturn(mockBar);
剛提的是,在2的Mockito的' arg與Hamcrest'Matcher's一起工作的超載被移動了'MockitoHamcrest'。 [Mockito 2中的新增功能](https://github.com/mockito/mockito/wiki/What%27s-new-in-Mockito-2#incompatible)在其「與1.10不兼容的更改」一節中討論了此問題。 –
- 1. Hamcrest Matchers.contains matcher not working(?)
- 2. Hamcrest Matcher with junit style diff
- 3. Hamcrest matcher比較來自JSON的double值
- 4. java.util.Optional是否有任何Hamcrest Matcher?
- 5. 我如何獲得Hamcrest的Matcher類?
- 6. hamcrest-library Matcher與hamcrest-core CoreMatchers之間的區別
- 7. Select2 Custom Matcher
- 8. Hamcrest Matcher在字符串列表中沒有重複項?
- 9. 在nUnit中,與Hamcrest的Matchers.containsInAnyOrder(Matcher ... matchers)等效的是什麼?
- 10. 在自定義Hamcrest Matcher中緩存變量
- 11. Espresso Intent Custom Intent Matcher
- 12. RSpec Array instance_of Argument Matcher
- 13. 瞭解Pattern和Matcher
- 14. Clang AST Matcher的「AND」和「OR」
- 15. 規範不Mockito Matchers.any [FooException] matcher
- 16. Pattern和Matcher是Android的
- 17. shoulda-matcher錯誤驗證length_of
- 18. Pattern,Matcher的用法替換
- 19. 比較者的Junit Matcher?
- 20. 使用hamcrest matcher進行jUnit測試 - 如何測試集合的大小。
- 21. 是否有一個用於執行XML文檔匹配的python hamcrest matcher庫?
- 22. Scalatest在使用Matcher時顯示錯誤
- 23. cucumber,rspec,webrat if else else on matcher
- 24. 使用緩衝對象()Matcher類
- 25. Pattern類和Matcher類之間的區別
- 26. 使用@variable()@ matcher時出現Json錯誤
- 27. 用matcher解析協議段落?
- 28. Matcher在匹配後拋出IllegalStateException
- 29. Groovy中Matcher類中的Count屬性
- 30. Java - Matcher在訪問組後拋出IllegalStateException
相關:[?如何匹配器的Mockito工作(http://stackoverflow.com/a/22822514/1426891) –