unruly / java-8-matchers

Hamcrest Matchers for Java 8 features
MIT License
23 stars 5 forks source link

using combinable matchers with streams #24

Open adrian-herscu opened 4 years ago

adrian-herscu commented 4 years ago

This one works:

        assertThat(Stream.of(7, 3, 1, 4, 1), anyMatch(greaterThan(5)));

but now... there is another requirement!!! The stream must not contain any zeros. So I tried:

        assertThat(Stream.of(7, 3, 1, 4, 1),
            both(allMatch(is(not(0))))
              .and(anyMatch(greaterThan(5))));

which fails with IllegalStateException: stream has already been operated upon or closed

Seems that the both matcher causes the stream to be operated twice. Other issue? Anyway to overcome this?

CliveEvans commented 4 years ago

This is because the both matcher, from core, is causing both matchers to be checked, one after the other, and therefore the stream is being reused after it has been read.

Ideally we'd have some clever way of combining stream matchers, but currently we don't. You can try to twist your assertion logic in order to create something that can be checked in one pass, but it's trivially simple to come up with examples where this can't be done (such as yours).

Sounds like a nice feature, I don't suppose you'd like to propose a solution and raise a PR, would you? ;)