如何在AssertJ中使用satisfiesExactlyInAnyOrder验证动态预期值?附示例
AssertJ
satisfiesExactlyInAnyOrder 断言使用示例 我们可以用satisfiesExactlyInAnyOrder实现验证实际列表中的字符串是否以预期列表中的字符串为后缀,且顺序不限的需求。
有效测试示例
- 预期列表:
expected = {"abc","def","ghi"} - 实际列表:
actual = {"1=def","ghi","234=abc"}
实现代码
package test; import org.assertj.core.api.Assertions; import java.util.List; import java.util.function.Consumer; import java.util.stream.Collectors; public class Test1 { private static void testSuffixes(List<String> expected, List<String> actual) { // 将预期字符串转换为断言消费者 Consumer<String>[] suffixTests = expected .stream() .map(expectedStr -> { Consumer<String> suffixTest = value -> Assertions.assertThat(value).endsWith(expectedStr); return suffixTest; }) .collect(Collectors.toList()) .toArray(new Consumer[0]); Assertions.assertThat(actual).satisfiesExactlyInAnyOrder(suffixTests); } public static void main(String[] args) { List<String> expected = List.of("ABC", "DEF", "GHI"); List<String> actual = List.of("0=ABC", "3=GHI", "DEF"); testSuffixes(expected, actual); } }
执行结果
- 当实际列表中的元素均以预期列表对应字符串为后缀时,程序正常结束(状态码0)。
- 当实际值不符合要求时,会抛出
AssertionError,示例错误信息如下:
Exception in thread "main" java.lang.AssertionError: Expecting
actual: ["0=ABC", "DEF1", "3=GHI"] to satisfy all the consumers in
any order.
内容的提问来源于stack exchange,提问作者Asaf Artsi
相关产品推荐
相关产品推荐

