Search code examples
javaunit-testingjunithamcrest

Hamcrest Matcher for no duplicates in a List of Strings?


I would like a simple hamcrest matcher for finding duplicates of an object in a List<String>. This is what I wrote

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())));

Unfortunately I got this output, which isn't descriptive enough. Any

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

Solution

  • Replaced

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

    with

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