首页 > 解决方案 > 从多个线程向 SoftAssertions 添加失败

问题描述

SoftAssertions当我需要确保多个条件保持或收集尽可能多的失败时,AssertJ 中的in AssertJ很有用:

        final SoftAssertions softly = new SoftAssertions();

        softly.assertThat("foo").hasToString("foo");
        softly.assertThat("bar").hasToString("bar");

        softly.assertAll();

尽管如此,当我需要收集在多个线程中产生的故障时,多线程环境看起来不再那么乐观了。例如,此代码被破坏,因为SoftAssertions从其他线程对实例所做的更改可能在线程中不可见main

        final SoftAssertions softly = new SoftAssertions();

        final ForkJoinPool forkJoinPool = ForkJoinPool.commonPool();
        forkJoinPool.execute(() -> {
            softly.assertThat("foo").hasToString("foo");
        });
        forkJoinPool.execute(() -> {
            softly.assertThat("bar").hasToString("bar");
        });

        softly.assertAll();

解决上述问题的最佳方法是什么?

在我使用它们的任何地方都使用同步块进行保护SoftAssertions似乎不是一个好的解决方案(尤其是从测试可读性的角度来看)。

标签: javamultithreadingunit-testingconcurrencyassertj

解决方案


推荐阅读