[英]jUnit and Guava, comparing list equality after transform()
在 jUnit 測試中,我想根據name
列從數據庫中獲取一些行。 然后我想測試我得到的行是否具有我期望的名稱。 我有以下內容:
Set<MyClass> typesToGet = MyClassFactory.createInstances("furniture",
"audio equipment");
Collection<String> namesToGet = Collections2.transform(typesToGet,
new NameFunction<MyClass, String>());
List<MyClass> typesGotten = _svc.getAllByName(typesToGet);
assertThat(typesGotten.size(), is(typesToGet.size()));
Collection<String> namesGotten = Collections2.transform(typesGotten,
new NameFunction<ItemType, String>());
assertEquals(namesToGet, namesGotten); // fails here
我目前遇到此故障:
java.lang.AssertionError:預期:com.google.common.collect.Collections2$TransformedCollection<[音頻設備,家具]>但為:com.google.common.collect.Collections2$TransformedCollection<[音頻設備,家具]>
那么,什么是最干凈、最簡潔的方法來測試我從數據庫返回的行的name
列是否與我說的我想要的名稱相匹配? 我可以有一個for
循環遍歷並檢查一個列表中的每個名稱是否存在於另一個列表中,但我希望更簡潔。 類似於以下偽代碼的東西會很好:
List<MyClass> typesGotten = ...;
["furniture", "audio equipment"].equals(typesGotten.map(type => type.getName()))
您可以使用containsAll()
兩次來檢查您沒有任何缺失值或任何意外值。
assertTrue(namesToGet.containsAll(namesGotten));
assertTrue(namesGotten.containsAll(namesToGet));
但是,如果您決定使用List
或Set
而不是Collection
,則接口契約指定一個List
等於另一個List
( 對於Set
也是如此), 前提是兩者包含相同的值。
比較指定的 object 與此列表是否相等。 當且僅當指定的 object 也是一個列表時返回
true
,兩個列表具有相同的大小,並且兩個列表中所有對應的元素對都相等。 (如果(e1==null? e2==null: e1.equals(e2))
,則兩個元素 e1 和 e2 相等。)換句話說,如果兩個列表包含相同順序的相同元素,則它們被定義為相等. 此定義可確保 equals 方法在List
接口的不同實現中正常工作。
資源:
如果您希望它們包含相同的元素,但不一定以相同的順序,那么只需對它們進行ImmutableSet
復制並檢查這些集合是否相等。 如果您希望它們具有相同的順序,則執行ImmutableList
副本並檢查它們是否相等。
Collection
根本沒有任何平等的概念。
編寫此類斷言的最簡潔、最具表現力的方式是使用 Hamcrest 匹配器:
assertThat(namesGotten, containsInAnyOrder(namesToGet))
番石榴有一種方法,我發現它可以很好地傳達您試圖獲得的概念: symmetricDifference 。 如果 symmetricDifference 為空,則集合相等。
assetTrue(Sets.symmetricDifference(namesToGet, namesGotten).isEmpty());
然而,它可能不是“最便宜的”,因為它執行聯合、交集和差異運算。 您還可以檢查這些集合是否具有相同的大小——如果它們不相同,則它們不包含相同的元素,而如果它們是,您可以驗證(非對稱) 差異是否為空。
assertEquals(namesToGet.size(), namesGotten.size());
assertTrue(Sets.difference(namesToGet, namesGotten));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.