JUnit 测试意外行为



我运行了几个 JUnit 测试来测试消息解析系统。

使用 3s 超时单独运行测试是可以的 - 它们都通过。

一次运行所有测试会导致问题,我经常看到以下错误消息:

java.lang.AssertionError: Expected <3> but collection size <0>

我可以通过将超时增加到 30 秒左右来解决此问题,但在这种情况下,我发现 Test1 出于某种原因重新运行。这是我在运行 Test6 时在日志中看到的,例如将 runforMilliseconds(3000, () -> messageProcessor.start()); 的超时增加到 runforMilliseconds(30000, () -> messageProcessor.start()); ...结果,这导致了很多断言错误:

[ForkJoinPool.commonPool-worker-1] Started parsing Test1
[ForkJoinPool.commonPool-worker-6] Started parsing Test6
[ForkJoinPool.commonPool-worker-2] Started parsing Test2
[ForkJoinPool.commonPool-worker-5] Started parsing Test5
[ForkJoinPool.commonPool-worker-3] Started parsing Test3

下面是单元测试的示例:

测试1.java

@Before
public void setUp() throws Exception {
    test1Mapper.deleteAll();
    messageTestMapper.deleteAll();
    setupMessages();
}
@Test
public void Test1() throws Exception {
    messageTestMapper.insertOne(new TestMessage(message1)):
    messageTestMapper.insertOne(new TestMessage(message2)):
    messageTestMapper.insertOne(new TestMessage(message3)):
    runforMilliseconds(3000, () -> messageProcessor.start());
    List<TestMessageDetails) actualTestMessageDetails = test1Mapper.select();
    assertThat(actualTestMessageDetails, hasSize(3));
}
@SneakyThrows
private void runforMilliseconds(int n, Runnable runnable) throws Exception {
    try {
        CompleteableFuture.runAsync(runnable).get(n, TimeUnit.MILLISECONDS);
    }
    catch (TimeoutException e) {
        log.info("End running");
    }
}

我该如何解决此问题?

是否所有单元测试都使用相同的test1MappermessageTestMapper变量?如果是这样,请考虑为每个测试提供其自己的单独映射器变量,以便可以并行运行它们,而不会让一个测试影响其他测试的结果。

最新更新