How to assert that some String contains at least one value from the List <String>?
Asked Answered
U

4

7

I'm testing some UI functionality with Java and AssertJ. So when I receive some massive string from UI, I should verify if that String contains at least one predefined value from List<String>. It is easy to do opposite thing - verify if list contains at least once some String value but this is not my case. I can't find solution in standard methods.

public static final List<String> OPTIONS = Arrays.asList("Foo", "Bar", "Baz");

String text = "Just some random text with bar";

what I need is smth like this :

Assertions.assertThat(text)
                .as("Should contain at least one value from OPTIONS ")
                .containsAnyOf(OPTIONS)
Unfleshly answered 6/4, 2019 at 14:25 Comment(0)
M
7
.matches(s -> OPTIONS.stream().anyMatch(option -> s.contains(option)));
Marindamarinduque answered 6/4, 2019 at 14:30 Comment(1)
or also .matches(s -> OPTIONS.stream().anyMatch(s::contains));Somnambulate
J
3

You can also try to use Condition and AssertJ assertions like areAtLeastOne(), areAtLeast(), for instance:

assertThat(OPTIONS)
.areAtLeastOne(new Condition<>(text::contains,
                                String.format("Error message '%s'", args);
Justificatory answered 6/8, 2019 at 14:42 Comment(0)
Y
0

Another option using AssertJ

assertThat(text.split(" ")).containsAnyElementsOf(OPTIONS);
Yt answered 4/5, 2020 at 5:42 Comment(0)
G
0

Another simplified option using AssertJ:

.matches(s-> Stream.of("Foo", "Bar", "Baz").anyMatch(s::contains));
Greig answered 14/11, 2022 at 19:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.