簡體   English   中英

如何在 Junit (java) 中使用 assertThat 包含用於列表比較的任何順序方法

[英]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()方法,我無法確定這一點。 而且,不知道你正在嘗試做的,很難知道正確的解決方法是什么。

如果以上方法對您不起作用,請:

  1. 准確描述您正在嘗試做什么,即描述您的測試目的。
  2. 更新您的問題以包含ShipmentEntity的構造函數和equals()方法

暫無
暫無

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

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