Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
graemeg opened this issue Jan 23, 2022 · 2 comments
Open

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

graemeg opened this issue Jan 23, 2022 · 2 comments

Comments

@graemeg
Copy link

graemeg commented Jan 23, 2022

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
Copy link
Author

graemeg commented Jan 23, 2022

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. 🤷

@dmfs
Copy link

dmfs commented Feb 1, 2022

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants