![](/img/trans.png)
[英]get substring between a stringA and next stringB after stringA
[英]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.