How to assert that Set has item with exact property with hamcrest
Asked Answered
P

3

6

i've been trying assert that my Set has collection with given property with hamcrest, using this solution, but i have :

java.lang.NoSuchMethodError: org.hamcrest.Matcher.describeMismatch(Ljava/lang/Object;Lorg/hamcrest/Description;)V at org.hamcrest.Condition$Matched.matching(Condition.java:52)

imports:

import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasProperty;
import static org.junit.Assert.assertThat;

code:

assertThat(mySet, contains(hasProperty("id", equalTo("expectedId"))));

have You any ideas how to assert it well ?

Pothook answered 12/2, 2016 at 12:12 Comment(0)
M
3

Well, you should try to let assertThat do the work for you.

Set<WhateverPropertyTypeYouAreUsing> expectedSet = Collections.singleton( ... create a property object with that id/value);

assertThat(mySet, is(expectedSet))

The restriction here: that assumes that your set contains only that one property value.

Otherwise, you can go for:

assertThat(mySet.contains(someProperty), is(true))

(probably with an additional message to better describe a failing assert).

Prereq: your property class should be implementing equals() in a reasonable manner.

Mahratta answered 12/2, 2016 at 12:25 Comment(1)
i tought it won't work if I just initiate te same object in test and assert it's in my returned collection, because I tought it would compare if its the same object, if You know what I mean , but well, it works assertThat(mySet.contains(expectedValue), equalTo(true)); thank You :)Pothook
S
1

Another approach will be:

assertTrue(mySet.contains(someProperty);

Symbiosis answered 2/12, 2021 at 12:29 Comment(0)
P
0

Your original code is fine. Your problem is probably due to some version conflict. By the way, you should be using Hamcrest's assertThat (import static org.hamcrest.MatcherAssert.assertThat), instead of JUnit's.

Primero answered 17/1, 2022 at 15:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.