source

Junit의 2개의 리스트와 같은 아사트

goodcode 2022. 7. 31. 22:58
반응형

Junit의 2개의 리스트와 같은 아사트

JUnit 테스트 케이스에서 목록 간에 동일한 주장을 하려면 어떻게 해야 합니까?목록의 내용 사이에 동등성이 있어야 합니다.

예를 들어:

List<String> numbers = Arrays.asList("one", "two", "three");
List<String> numbers2 = Arrays.asList("one", "two", "three");
List<String> numbers3 = Arrays.asList("one", "two", "four"); 

// numbers should be equal to numbers2
//numbers should not be equal to numbers3

Junit4를 위해서!이 질문은 junit5에 새로운 답을 쓸만합니다.

이 답변은 질문 후 몇 년 후에 작성된 것으로 알고 있습니다.아마 이 기능은 그 무렵에는 없었던 것 같습니다.하지만 지금은 이렇게 하는 것이 쉽습니다.

@Test
public void test_array_pass()
{
  List<String> actual = Arrays.asList("fee", "fi", "foe");
  List<String> expected = Arrays.asList("fee", "fi", "foe");

  assertThat(actual, is(expected));
  assertThat(actual, is(not(expected)));
}

Junit의 최신 버전이 hamcrest와 함께 설치되어 있는 경우 다음 Import만 추가합니다.

import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;

http://junit.org/junit4/javadoc/latest/org/junit/Assert.html#assertThat(T, org.hamcrest.매처)

http://junit.org/junit4/javadoc/latest/org/hamcrest/CoreMatchers.html

http://junit.org/junit4/javadoc/latest/org/hamcrest/core/Is.html

문자열로 변환하지 말고 비교하세요.이것은 퍼포먼스에 좋지 않다.> > = >>> = incher in in in in in in in = hasItems

List<Integer> yourList = Arrays.asList(1,2,3,4)    
assertThat(yourList, CoreMatchers.hasItems(1,2,3,4,5));

이것이 리스트의 요소를 체크하는 가장 좋은 방법입니다.

assertEquals(Object, Object) JUnit4/JUnit5에서assertThat(actual, is(expected));의 경우 두 가지 모두로 합니다.equals() ★★★★★★★★★★★★★★★★★」toString()비교 대상 객체의 클래스에 대해(및 깊이) 재정의됩니다.

는 어설션의 평등성 평가에 합니다.equals()는 ""에 합니다.toString()비교 대상입니다.
음음 such such such such such such such such such such such 등 String,Integer덮어쓰기 문제 .equals() ★★★★★★★★★★★★★★★★★」toString() '아주 정확하다'고 주장하는 타당합니다List<String> ★★★★★★★★★★★★★★★★★」List<Integer>assertEquals(Object,Object).
이: 이 문제에 : 이 문제를 덮어쓸 : 이 문제에 대해서: 이 문제를 덮어쓸 필요가 있습니다.equals()JUnit을 사용한 테스트에서 주장을 더 쉽게 하는 것뿐만 아니라 객체 평등 측면에서 말이 되기 때문에 클래스 내에서.
주장을 쉽게 하기 위해서는 다른 방법이 있다.
좋은 관행으로 어설션/매처 라이브러리를 선호합니다.

다음은 AssertJ의 솔루션입니다.

org.assertj.core.api.ListAssert.containsExactly() 필요한 것은 이것입니다.실제 그룹에 지정된 값이 정확하게 포함되어 있는지 확인하고 javadoc에 기재된 순서대로 다른 값이 포함되어 있지 않은지 확인합니다.

를 들면,Foo요소를 추가할 수 있는 클래스 및 해당 요소를 얻을 수 있는 클래스입니다.
【 】의 Foo는, 가 같은 합니다. : 、 2 、 2 개 、 2 개 that that that that that that that that that that that that that that that that that that that that that that that

import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;

@Test
void add() throws Exception { 
   Foo foo = new Foo();
   foo.add("One", "Two", "Three");
   Assertions.assertThat(foo.getElements())
             .containsExactly("One", "Two", "Three");
}

은 AssertJ를 입니다.List을 더 하게 하고 를 더 읽을 수 있게 : 상상로로로로예예예예예예예예예예예 as 。이것에 의해, 어설션이 보다 명확해지고, 코드의 판독성이 향상됩니다.

Assertions.assertThat(foo.getElements())
         .containsExactly("One", "Two", "Three");

어설션/매처이러한 라이브러리는 정말 더 나아가기 때문입니다.
" " " " 라고 가정해 보겠습니다.Foo doesn doesn doesn doesn doesn doesnString, ""Bar을 사용하다
그것은 매우 일반적인 요구이다.AssertJ는 AssertJ를 사용합니다.되지 않더라도 할 수 .equals()/hashCode()에는 : ,, JUnit 방식에는: ,, JUnit 방식에는 JUnit이 합니다.

import org.assertj.core.api.Assertions;
import static org.assertj.core.groups.Tuple.tuple;
import org.junit.jupiter.api.Test;

@Test
void add() throws Exception {
    Foo foo = new Foo();
    foo.add(new Bar(1, "One"), new Bar(2, "Two"), new Bar(3, "Three"));
    Assertions.assertThat(foo.getElements())
              .extracting(Bar::getId, Bar::getName)
              .containsExactly(tuple(1, "One"),
                               tuple(2, "Two"),
                               tuple(3, "Three"));
}

JUnit 4.3 이하에 적합한 레거시 답변입니다.JUnit의 최신 버전은 Assert에 판독 가능한 오류 메시지가 포함되어 있습니다.그 방법.가능하면 이 질문에 대한 다른 답변을 선호합니다.

List<E> a = resultFromTest();
List<E> expected = Arrays.asList(new E(), new E(), ...);
assertTrue("Expected 'a' and 'expected' to be equal."+
            "\n  'a'        = "+a+
            "\n  'expected' = "+expected, 
            expected.equals(a));

이 이2개의 @Paul이 .List는 같다s는 같다.

이기도 한 사이즈가 , 모두 「2개의 요소」는 「」 「」 「」 「」 「」 「」 「」 「」 「」).e1 ★★★★★★★★★★★★★★★★★」e2같음(e1==null ? e2==null : e1.equals(e2))가 같은하고 있는 는, 2개의 리스트가 되어 있습니다.에 의해 은 다른 합니다.List인터페이스입니다.

인터페이스의 JavaDocs 를 참조해 주세요.

JUnit 5의 경우

다음을 사용할 수 있습니다.

List<String> numbers = Arrays.asList("one", "two", "three");
List<String> numbers2 = Arrays.asList("one", "two", "three");

Assertions.assertIterableEquals(numbers, numbers2);

또는 목록을 어레이로 변환합니다.

List<String> numbers = Arrays.asList("one", "two", "three");
List<String> numbers2 = Arrays.asList("one", "two", "three");
Assertions.assertArrayEquals(numbers.toArray(), numbers2.toArray());

안 할 만합니다.ListAssert.assertEquals트트애애애애애애

링크: http://junit-addons.sourceforge.net/

Maven 사용자의 경우:

    <dependency>
        <groupId>junit-addons</groupId>
        <artifactId>junit-addons</artifactId>
        <version>1.4</version>
        <scope>test</scope>
    </dependency>

junit에 assertEquals를 사용할 수 있습니다.

import org.junit.Assert;   
import org.junit.Test;

    @Test
    public void test_array_pass()
    {
        List<String> actual = Arrays.asList("fee", "fi", "foe");
        List<String> expected = Arrays.asList("fee", "fi", "foe");
        Assert.assertEquals(actual,expected);
    }

요소의 순서가 다르면 오류가 반환됩니다.

모델 객체 리스트를 아사트하는 경우 특정 모델에서 동등한 방법을 재정의해야 합니다.

    @Override
    public boolean equals(Object obj) {
        if (obj == this) {
            return true;
        }
        if (obj != null && obj instanceof ModelName) {
            ModelName other = (ModelName) obj;
            return this.getItem().equals(other.getItem()) ;
        }
        return false;
    }

어레이 리스트를 작성하지 않는 경우는, 이것 또한 시험할 수 있습니다.

@Test
public void test_array_pass()
{
  List<String> list = Arrays.asList("fee", "fi", "foe");
  Strint listToString = list.toString();
  Assert.assertTrue(listToString.contains("[fee, fi, foe]"));   // passes  
}
List<Integer> figureTypes = new ArrayList<Integer>(
                           Arrays.asList(
                                 1,
                                 2
                            ));

List<Integer> figureTypes2 = new ArrayList<Integer>(
                           Arrays.asList(
                                 1,
                                 2));

assertTrue(figureTypes .equals(figureTypes2 ));

이 문제를 해결할 수 있는 옵션이 이미 많이 있다는 것을 알지만, 어떤 경우에도 두 가지 목록을 강조하기 위해 다음 작업을 수행하고자 합니다.

assertTrue(result.containsAll(expected) && expected.containsAll(result))

목록 내용의 동일성에 관심이 있다고 말씀하셨습니다(순서는 언급하지 않았습니다). ★★★★★★★★★★★★★★★★★.containsExactlyInAnyOrder단언하다되어 있습니다.spring-boot-starter-test

AssertJ docs ListAssert#contains에서Exact In Any Order:

실제 그룹에 지정된 값이 정확하게 포함되어 있고 다른 값이 포함되어 있지 않은지 확인합니다.예:

 // an Iterable is used in the example but it would also work with an array
 Iterable<Ring> elvesRings = newArrayList(vilya, nenya, narya, vilya);

 // assertion will pass
 assertThat(elvesRings).containsExactlyInAnyOrder(vilya, vilya, nenya, narya);

 // assertion will fail as vilya is contained twice in elvesRings.
 assertThat(elvesRings).containsExactlyInAnyOrder(nenya, vilya, narya);

assertEquals(expected, result); 2개의 어떤 할 수 .이 함수는 두 개의 객체를 가져오기 때문에 무엇이든 전달할 수 있습니다.

public static void assertEquals(Object expected, Object actual) {
    AssertEquals.assertEquals(expected, actual);
}

위의 모든 답변이 두 개의 개체 목록을 비교하는 정확한 솔루션을 제공하고 있지는 않습니다.위의 접근법의 대부분은 비교의 한계 - 크기 비교 - 참조 비교에만 도움이 될 수 있습니다.

그러나 개체 수준에서 동일한 크기의 개체 목록과 서로 다른 데이터가 있는 경우 이 비교 방법은 도움이 되지 않습니다.

다음 접근법은 사용자 정의 객체에 대한 우선 등호 및 해시 코드 메서드와 완벽하게 연동될 것입니다.

Override equals와 hashcode에 Xstream lib를 사용했는데 out won 로직/비교로 equals와 hashcode를 덮어쓸 수도 있습니다.

여기 참고용 예가 있습니다.

    import com.thoughtworks.xstream.XStream;

    import java.text.ParseException;
    import java.util.ArrayList;
    import java.util.List;

    class TestClass {
      private String name;
      private String id;

      public void setName(String value) {
        this.name = value;
      }

      public String getName() {
        return this.name;
      }

      public String getId() {
        return id;
      }

      public void setId(String id) {
        this.id = id;
      }

      /**
       * @see java.lang.Object#equals(java.lang.Object)
       */
      @Override
      public boolean equals(Object o) {
        XStream xstream = new XStream();
        String oxml = xstream.toXML(o);
        String myxml = xstream.toXML(this);

        return myxml.equals(oxml);
      }

      /**
       * @see java.lang.Object#hashCode()
       */
      @Override
      public int hashCode() {
        XStream xstream = new XStream();
        String myxml = xstream.toXML(this);
        return myxml.hashCode();
      }
    }

    public class XstreamCompareTest {
      public static void main(String[] args) throws ParseException {
      checkObjectEquals();
}

      private static void checkObjectEquals() {
        List<TestClass> testList1 = new ArrayList<TestClass>();
        TestClass tObj1 = new TestClass();
        tObj1.setId("test3");
        tObj1.setName("testname3");
        testList1.add(tObj1);

        TestClass tObj2 = new TestClass();
        tObj2.setId("test2");
        tObj2.setName("testname2");
        testList1.add(tObj2);

        testList1.sort((TestClass t1, TestClass t2) -> t1.getId().compareTo(t2.getId()));

        List<TestClass> testList2 = new ArrayList<TestClass>();
        TestClass tObj3 = new TestClass();
        tObj3.setId("test3");
        tObj3.setName("testname3");
        testList2.add(tObj3);

        TestClass tObj4 = new TestClass();
        tObj4.setId("test2");
        tObj4.setName("testname2");
        testList2.add(tObj4);

        testList2.sort((TestClass t1, TestClass t2) -> t1.getId().compareTo(t2.getId()));

        if (isNotMatch(testList1, testList2)) {
          System.out.println("The list are not matched");
        } else {
          System.out.println("The list are matched");
        }

      }

      private static boolean isNotMatch(List<TestClass> clist1, List<TestClass> clist2) {
        return clist1.size() != clist2.size() || !clist1.equals(clist2);
      }
    }

가장 중요한 것은 객체의 동일한 체크에 필드를 포함하지 않으려면 주석(@XStreamOmitField)의 필드를 무시해도 된다는 것입니다.이와 같은 주석은 구성할 수 있는 것이 많으므로 이 lib의 주석에 대해 자세히 살펴보십시오.

이 답변으로 인해 2개의 오브젝트 목록을 비교하기 위한 올바른 접근방식을 식별할 수 있습니다. : ).이 건에 대해 문제가 있으면 코멘트를 주세요.

언급URL : https://stackoverflow.com/questions/3236880/assert-equals-between-2-lists-in-junit

반응형