非确定性行为的断言

Assertions for non-deterministic behavior

AssertJ(或JUnit)是否有办法在单个(流利的)表达式中链接多个断言被测单元其中一个断言可能抛出异常。本质上,我试图断言:

If a unit under test (X) doesn't result in a particular exception, which it may, then assert that a particular property on the unit under test doesn't hold. Otherwise assert the exception is of a certain type.

例如,有没有一种方法可以表达以下错误代码可能 EITHER 导致异常或 strings.size() ! = 10000:

@Test/*(expected=ArrayIndexOutOfBoundsException.class)*/
public void raceConditions() throws Exception {


    List<String> strings = new ArrayList<>(); //not thread-safe

    Stream.iterate("+", s -> s+"+")
    .parallel()
    .limit(10000)
    //.peek(e -> System.out.println(e+" is processed by "+ Thread.currentThread().getName()))
    .forEach(e -> strings.add(e));

    System.out.println("# of elems: "+strings.size());
} 

AssertJ有一个soft assertions的概念,是那种场景用的吗?如果是这样,我将不胜感激一些代码示例。

或者有更好的框架专门针对此类场景设计?

谢谢。

我得出以下结论:

 @Test
 public void testRaceConditions() {
    List<String> strings = new ArrayList<>(); //not thread-safe

    int requestedSize = 10_000;

    Throwable thrown = catchThrowable(() -> { 
    Stream.iterate("+", s -> s+"+")
    .parallel()
    .limit(requestedSize)
    //.peek(e -> System.out.println(e+" is processed by "+ Thread.currentThread().getName()))
    .forEach(e -> strings.add(e));
    });

    SoftAssertions.assertSoftly(softly -> {
         softly.assertThat(strings.size()).isNotEqualTo(requestedSize);
         softly.assertThat(thrown).isInstanceOf(ArrayIndexOutOfBoundsException.class);
     });

 }

如果掌握更多 AssertJ 或其他一些工具的人知道更好的方法,我很乐意接受他们的解决方案。谢谢!

我不确定这是否是您真正想要的,但您可以尝试使用假设。 执行完被测代码后,对结果进行假设,以下code/assertions只有在假设正确的情况下才会执行

自 3.9.0 AssertJ 提供开箱即用的 assumptions,示例:

List<String> strings = new ArrayList<>(); // not thread-safe

int requestedSize = 10_000;

Throwable thrown = catchThrowable(() -> {
  Stream.iterate("+", s -> s + "+")
        .parallel()
        .limit(requestedSize)
        .forEach(strings::add);
});

// thrown is null if there was no exception raised
assumeThat(thrown).isNotNull();

// only executed if thrown was not null otherwise the test is skipped.
assertThat(thrown).isInstanceOf(ArrayIndexOutOfBoundsException.class);

如果您正在测试异步代码,您还应该看看 https://github.com/awaitility/awaitility