![](/img/trans.png)
[英]Junit: assert that a list contains at least one property that matches some condition
[英]How to assert that some String contains at least one value from the List <String>?
我正在使用 Java 和 AssertJ 測試一些 UI 功能。 因此,當我從 UI 收到大量字符串時,我應該驗證該字符串是否至少包含一個來自List<String>
的預定義值。 做相反的事情很容易——驗證列表是否至少包含一次字符串值,但這不是我的情況。 我找不到標准方法的解決方案。
public static final List<String> OPTIONS = Arrays.asList("Foo", "Bar", "Baz");
String text = "Just some random text with bar";
我需要的是這樣的:
Assertions.assertThat(text)
.as("Should contain at least one value from OPTIONS ")
.containsAnyOf(OPTIONS)
.matches(s -> OPTIONS.stream().anyMatch(option -> s.contains(option)));
您還可以嘗試使用條件和 AssertJ 斷言,例如 areAtLeastOne()、areAtLeast(),例如:
assertThat(OPTIONS)
.areAtLeastOne(new Condition<>(text::contains,
String.format("Error message '%s'", args);
使用AssertJ 的另一種選擇
assertThat(text.split(" ")).containsAnyElementsOf(OPTIONS);
另一個使用 AssertJ 的簡化選項:
.matches(s-> Stream.of("Foo", "Bar", "Baz").anyMatch(s::contains));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.