簡體   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