문제

Nunit과 평행 한 주니가 있습니까? CollectionAssert?

도움이 되었습니까?

해결책

Junit 4.4를 사용하여 사용할 수 있습니다 assertThat() 함께 Hamcrest 코드 (걱정하지 마십시오. 주니트와 함께 배송됩니다. .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"))));

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

다른 팁

직접적이지 않습니다. 나는 사용을 제안한다 Hamcrest, Junit (및 기타 테스트 프레임 워크)와 잘 통합되는 풍부한 일치하는 규칙 세트를 제공합니다.

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

Joachim Sauer의 솔루션은 좋지만 이미 확인하려는 기대가 이미있는 경우에는 효과가 없습니다. 결과를 비교하려는 테스트에서 이미 생성되거나 지속적인 기대가있을 때 발생하거나 결과에 병합 될 것으로 예상되는 여러 기대치가있을 때 발생할 수 있습니다. 따라서 매칭자를 사용하는 대신 만 사용할 수 있습니다. List::containsAll 그리고 assertTrue 예를 들어:

@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
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top