gpt4 book ai didi

java - 断言数组中的字符串之一包含子字符串

转载 作者:搜寻专家 更新时间:2023-11-01 02:02:47 25 4
gpt4 key购买 nike

List<String> expectedStrings = Arrays.asList("link1", "link2");
List<String> strings = Arrays.asList("lalala link1 lalalla", "lalalal link2 lalalla");

对于每个 expectedString,我需要断言“字符串”中的任何字符串都包含 expectedString。我如何用 Hamcrest 断言这一点?感谢您的关注。

最佳答案

更新

检查这个旧答案后,我发现您可以使用更好的内置匹配器组合,使断言和错误消息更具可读性:

expectedStrings.forEach(expectedString -> 
assertThat(strings, hasItem(containsString(expectedString))));

引用原答案

您可以使用流很容易地做到这一点:

assertThat(expectedStrings.stream().allMatch(
expectedString -> strings.stream()
.anyMatch(string -> string.contains(expectedString))),
is(true));

allMatch 将确保检查所有 expectedStrings,并且在 strings 上使用 anyMatch 你可以有效地检查是否有任何字符串包含预期的字符串。

关于java - 断言数组中的字符串之一包含子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41828198/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com