![](/img/trans.png)
[英]JUnit ~ Assert that list contains objects with the same values in any order
[英]How to use assertThat Contains any order method for list comparison in Junit (java)
我想使用assertThat & Contains
任何訂單來測試ShipmentEntityBO
方法。 由於 list 已返回對象,因此下面的測試函數不起作用。 請建議我。
public class ShipmentEntityBO {
public void addShipmentEntityToList(List<ShipmentEntity> shipmentEntityList,String shipmentDetails) {
String splited[] = shipmentDetails.split(",");
shipmentEntityList.add(new ShipmentEntity(new Integer(splited[0]), splited[1],
splited[2], new Long(splited[3]), splited[4]));
}
}
Junit代碼
import java.util.ArrayList;
import java.util.Arrays;
import org.junit.Before;
import org.junit.Test;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.collection.IsCollectionWithSize.hasSize;
import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder;
import static org.hamcrest.collection.IsIterableContainingInOrder.contains;
public class Junit {
ShipmentEntityBO shipmentEntityBO;
@Before
public void createObjectForShipmentEntity() {
shipmentEntityBO = new ShipmentEntityBO();
}
@Test
public void testListofShipmentEntity() {
ArrayList<ShipmentEntity> list = new ArrayList<ShipmentEntity>();
String details = "101,pavi,12345,8500,Toronto";
shipmentEntityBO.addShipmentEntityToList(list, details);
assertThat(list,containsInAnyOrder("Toronto","pavi",101,"12345",8500));
}
}
下面的代碼...
String details = "101,pavi,12345,8500,Toronto";
addShipmentEntityToList(list, details);
... 用1 個條目填充給定list
,該條目屬於ShippingEntry
類型並已從給定的details
填充
但是,您的斷言試圖驗證該list
包含5個條目,其中沒有一個屬於ShipmentEntity
類型,即"Toronto","pavi",101,"12345",8500
因此斷言失敗。
以下斷言可能會通過:
assertThat(list,containsInAnyOrder(new ShipmentEntity(101, "pavi", "12345", 8500L, "Toronto")));
但是,如果沒有看到ShipmentEntity
的構造函數和equals()
方法,我無法確定這一點。 而且,不知道你正在嘗試做的,很難知道正確的解決方法是什么。
如果以上方法對您不起作用,請:
ShipmentEntity
的構造函數和equals()
方法
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.