簡體   English   中英

JUnit 檢查異常拋出的消息是 `stringA` 還是 `stringB`

[英]JUnit checking if the message thrown by an exception is either `stringA` or `stringB`

在我的代碼中,我有一些類似的模式(我試圖盡可能地簡化):

import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import java.util.Set;

public void funcSubSet() {
   final Set<String> setA = new HashSet<>(Arrays.asList("a", "b", "c", "d"));
   final Set<String> setB = new HashSet<>(Arrays.asList("a"));
   Preconditions.checkArgument(setB.constainsAll(setA),
                               "The strings %s are present in setA but not in setB",
                               Joiner.on(", ").join(setA.stream()
                                                   .filter(Predicate.not(setB::contains))
                                                   .iterator())
                               );
}

基本上,這會檢查setA是否完全包含在setB中。 如果不是,則拋出異常並打印 setA 中但不在setA中的setB (以逗號和空格分隔)。 當我測試它時,問題是它 output setB中未包含的字符串有時會以不同的順序排列,並且以下測試用例偶爾會失敗。

assertThrows(IllegalArgumentException.class,
             () -> funcSubSet()),
             "The strings b, c, d are present in setA but not in setB")

有時 output 就像:“字符串 d、b、c 存在於 setA 中,但不存在於 setB 中”。

你如何讓它與訂單無關? 我如何告訴hasMessage()或任何其他斷言我接受多個字符串? 我查了一下,找不到任何東西。

我用的是JUnit 5!

如果您可以在測試中提供要從外部檢查的集合(我建議這樣做以獲得良好的代碼設計和高可測試性),則可以提供java.util.LinkedHashSet<E>而不是HashSet進行測試。 這個 class 確保迭代順序是第一次插入的順序,所以你得到一個可預測的結果。

如果您不能為測試選擇實際的Set實現,我會編寫一些不同的測試:

import org.junit.jupiter.api.Assertions;

//...

// expect permutation of:
//The strings b, c, d are present in setA but not in setB

Exception thrownException = Assertions.assertThrows(Exception.class, () -> funcSubSet());

String message = thrownException.getMessage();

Assertions.assertEquals("The strings ", message.substring(0, 12), "message start");
Assertions.assertEquals(" are present in setA but not in setB", message.substring(19), "message end");
String variables = message.substring(11,19);
Assertions.assertTrue(variables.contains(" b"), "contains b");
Assertions.assertTrue(variables.contains(" c"), "contains c");
Assertions.assertTrue(variables.contains(" d"), "contains d");

使用Assertions.assertThrows ,您還可以期待一個固定的 String 並處理捕獲的異常以獲取更多詳細信息。 org.junit.jupiter.api.Assertions是 JUnit 的一部分,不需要像 AssertJ 這樣的第三方依賴項。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM