your programing

jUnit의 CollectionAssert?

lovepro 2020. 10. 5. 20:32
반응형

jUnit의 CollectionAssert?


NUnit과 병렬로 jUnit이 CollectionAssert있습니까?


JUnit 4.4를 사용 assertThat()하면 Hamcrest 코드 와 함께 사용할 수 있습니다 (걱정하지 마십시오. JUnit과 함께 제공되며 추가 필요 없음 .jar). 컬렉션에서 작동하는 것을 포함하여 복잡한 자체 설명 어설 션을 생성 할 수 있습니다.

import static org.junit.Assert.assertThat;
import static org.junit.matchers.JUnitMatchers.*;
import static org.hamcrest.CoreMatchers.*;

List<String> l = Arrays.asList("foo", "bar");
assertThat(l, hasItems("foo", "bar"));
assertThat(l, not(hasItem((String) null)));
assertThat(l, not(hasItems("bar", "quux")));
// check if two objects are equal with assertThat()

// the following three lines of code check the same thing.
// the first one is the "traditional" approach,
// the second one is the succinct version and the third one the verbose one 
assertEquals(l, Arrays.asList("foo", "bar")));
assertThat(l, is(Arrays.asList("foo", "bar")));
assertThat(l, is(equalTo(Arrays.asList("foo", "bar"))));

이 접근 방식을 사용하면 어설 션이 실패 할 때 자동으로 좋은 설명을 얻을 수 있습니다.


직접적으로는 아닙니다. jUnit (및 기타 테스트 프레임 워크)과 잘 통합되는 풍부한 일치 규칙 세트를 제공하는 Hamcrest 사용을 제안합니다.


FEST Fluent Assertions를 살펴보십시오. IMHO 그들은 Hamcrest (그리고 마찬가지로 강력하고 확장 가능한 등)보다 사용하기 더 편리하며 유창한 인터페이스 덕분에 더 나은 IDE 지원을 제공합니다. 참조 https://github.com/alexruiz/fest-assert-2.x/wiki/Using-fest-assertions를


Joachim Sauer의 솔루션은 좋지만 결과에 확인하려는 일련의 기대치를 이미 가지고있는 경우 작동하지 않습니다. 이는 결과를 비교하려는 테스트에서 이미 생성되거나 일정한 기대가 있거나 결과에 병합 될 것으로 예상되는 여러 기대가있을 때 발생할 수 있습니다. 그래서 그 대신 매처 (matcher)를 사용하는 당신은 사용할 수 있습니다 List::containsAllassertTrue예를 들어 :

@Test
public void testMerge() {
    final List<String> expected1 = ImmutableList.of("a", "b", "c");
    final List<String> expected2 = ImmutableList.of("x", "y", "z");
    final List<String> result = someMethodToTest(); 

    assertThat(result, hasItems(expected1)); // COMPILE ERROR; DOES NOT WORK
    assertThat(result, hasItems(expected2)); // COMPILE ERROR; DOES NOT WORK

    assertTrue(result.containsAll(expected1));  // works~ but has less fancy
    assertTrue(result.containsAll(expected2));  // works~ but has less fancy
}

참고 URL : https://stackoverflow.com/questions/1086691/collectionassert-in-junit

반응형