You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 15:42:18