Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
354 views
in Technique[技术] by (71.8m points)

java - 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, e.g. 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.

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?

question from:https://stackoverflow.com/questions/65877682/junit5-assert-list-of-similar-object-are-equal

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

you can use assertj library like this:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...