繁体   English   中英

JUnit测试意外行为

[英]JUnit tests unexpected behaviour

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

可以在3s超时的情况下单独运行测试-它们全部通过。

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

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

我可以通过将超时增加到30秒左右来解决此问题,但是在这种情况下,我发现由于某种原因重新运行了Test1。 例如,这是在运行Test6并在runforMilliseconds(3000, () -> messageProcessor.start());上增加超时时在日志中看到的内容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

这是单元测试的示例:

Test1.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变量吗? 如果是这样,请考虑为每个测试提供自己的独立映射器变量,以便您可以并行运行它们,而一个测试不会影响其他变量的结果。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM