如何使用assertThat包含Junit(java)中用于列表比较的任何order方法

时间:2018-11-04 19:33:30

标签: java junit assertion

我想以任何顺序使用ShipmentEntityBO测试assertThat & Contains方法。下面的测试功能不起作用,因为列表已返回该对象。请告诉我。

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)); 
    }
}

1 个答案:

答案 0 :(得分:1)

以下代码...

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")));

但是,在没有看到构造函数和equals()的{​​{1}}方法的情况下,我无法确定这一点。而且,在不知道您正在尝试做什么的情况下,很难知道什么是正确的修补程序。

如果上述方法对您不起作用,请:

  1. 准确描述您要执行的操作,即描述测试目的。
  2. 更新您的问题以包括构造函数和ShipmentEntity的{​​{1}}方法