1

Is the below piece of code fine where two threads may end up modifying the TestReporter instance at the same time?

    @Test
    public void someTest(TestReporter testReporter) {
        // do some stuff
        CompletableFuture.allOf(
                CompletableFuture.runAsync(() -> {
                    // do task A
                    testReporter.publishEntry("taskA", "valueA");
                }),
                CompletableFuture.runAsync(() -> {
                    // do task B
                    testReporter.publishEntry("taskB", "valueB");
                })
        ).join();
    }
6harat
  • 542
  • 6
  • 18

1 Answers1

4

TLDR: Yes

The correct answer is of course: It depends.

JUnit 5 has been designed to allow parallel test execution. The whole mechanism of reporting test results (and also publishing report entries) is done through event propagation and does neither share mutable state nor synchronise on events or instances of then underlying ReportEntry. Given there are no tricky bugs testReporter.publishEntry(..) should therefore be thread-safe.

Here's the "BUT": The JUnit 5 platform allows that 3rd parties hook into event listening, e.g. to generate their own reports or do other things when tests start, when tests end or when a test publishes some additional data. Those 3rd party TestExecutionListener implementations can do what they want and they may not be thread-safe.

johanneslink
  • 4,877
  • 1
  • 20
  • 37