JavaHamcrest icon indicating copy to clipboard operation
JavaHamcrest copied to clipboard

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

Open graemeg opened this issue 2 years ago • 2 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

graemeg avatar Jan 23 '22 11:01 graemeg

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. :shrug:

graemeg avatar Jan 23 '22 12:01 graemeg

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

dmfs avatar Feb 01 '22 19:02 dmfs