hamcrest / JavaHamcrest

Java (and original) version of Hamcrest

Home Page:http://hamcrest.org/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Not sure why assertThat() doesn't work in this case

graemeg opened this issue · comments

The second and third assertThat statements don't compile, but I'm not sure why. I'm using Hamcrest 2.2 with JDK 17 and JUnit5.

	@Test
	void moreListAsserts() {
		List<String> list = List.of("a", "ca", "ad", "ea", "af");

		org.hamcrest.MatcherAssert.assertThat("myValue", allOf(startsWith("my"), containsString("Val")));
		org.hamcrest.MatcherAssert.assertThat(list, allOf(containsString("a"), not(hasItem("b"))));
		org.hamcrest.MatcherAssert.assertThat(list, allOf(containsString("a"), not(containsString("b"))));
	}

This is the error I get.

Error on the second assertThat():
image

Error on the third assertThat():
image

I tried the following as well, which compiles, but still doesn't pass the test as I thought it would:

assertThat(list, allOf(contains(containsString("a")), not(contains(containsString("b")))));

In the end I used JUnit5's ParameterizedTest like as seen below, to accomplish what I wanted: Two assertions against each element in the list.

	@ParameterizedTest
	@ValueSource(strings = { "a", "ca", "ad", "ea", "af" })
	void test3(String val) {
		assertThat(val, containsString("a"));
		assertThat(val, not(containsString("b")));
	}

Not sure if there is a better way to do it with Hamcrest though. 🤷

containsString is a Matcher for Strings. You're using it to match a List.
I assume you want to verify that the list contains the String "a" but not "b" in that case you would write:

assertThat(list, allOf(hasItem("a"), not(hasItem("b"))));