簡體   English   中英

如何使用匹配器與Hamcrest進行收藏?

[英]How use matchers for collection with Hamcrest?

輸入:

  1. 不帶 equals方法的MyElement集合。
  2. org.hamcrest.TypeSafeMatcher實現,該實現通過某些字段匹配元素。

目的是使以下語句可編譯:

Collection<MyElement> elements = ...
Collection<TypeSafeMatchert> matchers = ...
assertThat(elements, Matchers.contains(matchers); //<error here

在這里必須使用什么? 想要我去Matcher<? super java.util.List<MyElement>> Matcher<? super java.util.List<MyElement>>並告訴我我確實通過了Matcher<java.lang.Iterable<? super java.util.List<MyElement>>> Matcher<java.lang.Iterable<? super java.util.List<MyElement>>> 那么如何在這里通過Matcher Collection?

關於將集合與hamcrest進行比較存在一個問題 ,但是沒有傳遞Matchers集合而不是元素的示例。

使用列表代替匹配器的集合,或將其轉換為數組。

Hamcrest具有以下contains方法:

public static <E> org.hamcrest.Matcher<java.lang.Iterable<? extends E>> contains(org.hamcrest.Matcher<? super E>... itemMatchers)

public static <E> org.hamcrest.Matcher<java.lang.Iterable<? extends E>> contains(E... items)

public static <E> org.hamcrest.Matcher<java.lang.Iterable<? extends E>> contains(org.hamcrest.Matcher<? super E> itemMatcher)

public static <E> org.hamcrest.Matcher<java.lang.Iterable<? extends E>> contains(java.util.List<org.hamcrest.Matcher<? super E>> itemMatchers)

如您所見,它僅在List或varags的情況下才處理Matchers(但是,如果僅傳遞一個元素,則需要將其轉換為數組)。

除了定義TypeSafeMatchersCollection TypeSafeMatchers ,您還需要定義以下內容:

    List<Matcher<? super MyElement>> matchers = ...;

這樣, Hamcrest就會知道您想要什么。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM