简体   繁体   English

JUnit5 Assert List 类似的 Object 相等

[英]JUnit5 Assert List of similar Object are equal

I need to test a layer of a method that maps a list of objects into a list of another, eg transforming from a list of objects we don't control to a list of objects we do.我需要测试将对象列表映射到另一个对象列表的方法层,例如从我们无法控制的对象列表转换为我们可以控制的对象列表。 I can't compare by using equals() since the objects are of different types, but I need to test that the list and object values are being mapped correctly.我无法使用 equals() 进行比较,因为对象属于不同类型,但我需要测试列表和 object 值是否正确映射。

My current implementation is:我目前的实现是:

    public void test {
        // GIVEN
        List<T1> l1 = api.getData();
    
        // WHEN
        List<T2> l2 = getList();
    
        // THEN
        assertEquals(l1.size(), l1.size());

        for(int i = 0; i < l1.size(); i++) {
            assertEquals(l1.get(i).getVal1(), l2.get(i).getVal1());
            assertEquals(l1.get(i).getVal2(), l2.get(i).getVal2());
            assertEquals(l1.get(i).getVal3(), l2.get(i).getVal3());
            ...
            
        }

    
    }

I'm new to unit testing.我是单元测试的新手。 Is there a better way to structure this test?有没有更好的方法来构建这个测试?

you can use assertj library like this:你可以像这样使用assertj库:

import static org.assertj.core.api.Assertions.assertThat;
...
assertThat(l2).usingElementComparatorOnFields("val1", "va2", "val3").containsExactlyElementsOf(l1);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM