java - 如何使用assertThat 包含Junit中列表比较的任意顺序方法(java)

标签 java junit assertion

我想使用 assertThat & Contains 任何订单来测试 ShipmentEntityBO 方法。由于列表已返回对象,因此以下测试函数无法正常工作。请给我建议。

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条目填充给定的列表,该条目的类型为ShippingEntry并且已从给定的详细信息填充

但是,您的断言尝试验证列表是否包含5个条目,其中没有一个条目属于ShipmentEntity类型,即“Toronto” ,"pavi",101,"12345",8500 以便断言失败。

以下断言可能会通过:

assertThat(list,containsInAnyOrder(new ShipmentEntity(101, "pavi", "12345", 8500L, "Toronto")));

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

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

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

关于java - 如何使用assertThat 包含Junit中列表比较的任意顺序方法(java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53144619/

相关文章:

没有参数的springboot WireMock mock

python - nose.tools.eq_ 与 assertEqual

c - 当数组在 c 中达到长度 0 时断言中止

java - java中夏令时的时区问题

java - 单独测试单一方法?

java - 统一安卓 : Didn't find class "com.unity3d.player.ReflectionHelper"

java - 如何在不破坏 Android 的情况下将 Eclipse 工作区组织到文件夹中

java - Junit 测试用例

maven - 使用 Maven 运行时的 log4j 设置与从 Eclipse 运行时不同

java - 在if语句中比较AssertNull