【问题标题】:How to use assertThat Contains any order method for list comparison in Junit (java)如何使用assertThat包含Junit(java)中列表比较的任何顺序方法
【发布时间】:2019-04-08 05:39:25
【问题描述】:

我想使用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)); 
    }
}

【问题讨论】:

  • containsInAnyOrder方法的代码在哪里?
  • 你能告诉我们ShipmentEntity的构造函数吗?

标签: java junit assertion


【解决方案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")));

但是,如果没有看到 ShipmentEntity 的构造函数和 equals() 方法,我无法确定这一点。而且,在不知道自己尝试做什么的情况下,很难知道正确的解决方法是什么。

如果上述方法不适合您,请:

  1. 准确描述您想要做什么,即描述您的测试目的。
  2. 更新您的问题以包括构造函数和ShipmentEntityequals() 方法

【讨论】:

    猜你喜欢
    • 2017-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-11
    • 1970-01-01
    相关资源
    最近更新 更多