简体   繁体   English

JUnit测试意外行为

[英]JUnit tests unexpected behaviour

I have several JUnit tests that I running to test a message parsing system. 我运行了几个JUnit测试,以测试消息解析系统。

Running the tests individually with the 3s timeout is ok - they all pass. 可以在3s超时的情况下单独运行测试-它们全部通过。

Running the tests all at once causes problems and I frequently see the following error message: 一次运行所有测试会导致问题,并且我经常看到以下错误消息:

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

I can get around this by increasing the timeout to something like 30s, but in this case, I find that Test1 is rerun for some reason. 我可以通过将超时增加到30秒左右来解决此问题,但是在这种情况下,我发现由于某种原因重新运行了Test1。 This is what I see in the logs when running Test6 for example and increasing the timeout on runforMilliseconds(3000, () -> messageProcessor.start()); 例如,这是在运行Test6并在runforMilliseconds(3000, () -> messageProcessor.start());上增加超时时在日志中看到的内容runforMilliseconds(3000, () -> messageProcessor.start()); to runforMilliseconds(30000, () -> messageProcessor.start()); 运行runforMilliseconds(30000, () -> messageProcessor.start()); ... as a result this a lot of assertion errors: ...因此导致许多断言错误:

[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

This is an example of a unit test: 这是单元测试的示例:

Test1.java 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");
    }
}

How do I resolve this? 我该如何解决?

Are all of your unit tests using the same test1Mapper and messageTestMapper variables? 您的所有单元测试都使用相同的test1MappermessageTestMapper变量吗? If so, consider giving each test its own individual mapper variables so that you can run them in parallel without one test affecting the outcome of the others. 如果是这样,请考虑为每个测试提供自己的独立映射器变量,以便您可以并行运行它们,而一个测试不会影响其他变量的结果。

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

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