2015-07-21 53 views
2

我想要一個簡單的Hamcrest匹配器,用於查找List<String>中某個對象的重複項。這就是我寫的Hamcrest Matcher在字符串列表中沒有重複項?

for (QuizEntity quiz : quizzes) 
      for (QuestionEntity question : quiz.getQuestions()) 
       Assert.assertThat("There should be no duplicate questions", 1, Matchers.equalTo(Collections.frequency(questions, question.getQuestion()))); 

不幸的是我得到這個輸出,這是不夠描述。任何

java.lang.AssertionError: There should be no duplicate questions 
Expected: <20> 
    but: was <1> 

回答

2

代替

Assert.assertThat("There should be no duplicate questions", 1, Matchers.equalTo(Collections.frequency(questions, question.getQuestion()))); 

Assert.assertThat("Question '" + question.getQuestion() + "' should not be duplicated", 1, Matchers.equalTo(Collections.frequency(questions, question.getQuestion()))); 
2

另一種選擇是使用hasDistinctElements()匹配從Cirneco library(即在端部是一個Hamcrest擴展名)。

可以使用如下:

Assert.assertThat("There should be no duplicate questions", questions, CirnecoMatchersJ7.hasDistinctElements()); 

,同時我建議做

import static CirnecoMatchersJ7.*; 

,使其更可讀

assertThat("There should be no duplicate questions", questions, hasDistinctElements()); 

購買cirneco也有一定的流暢表現,即

given(questions).withReason("There should be no duplicate questions").assertThat(hasDistinctElements()); 

如下的依賴性可以被導入:

<dependency> 
    <groupId>it.ozimov</groupId> 
    <artifactId>java7-hamcrest-matchers</artifactId> 
    <version>0.7.0</version> 
</dependency> 
相關問題