Hamcrest 비교 컬렉션
두 가지 목록을 비교하려고 합니다.
assertThat(actual.getList(), is(Matchers.containsInAnyOrder(expectedList)));
하지만 아이디어
java: no suitable method found for assertThat(java.util.List<Agent>,org.hamcrest.Matcher<java.lang.Iterable<? extends model.Agents>>)
method org.junit.Assert.<T>assertThat(T,org.hamcrest.Matcher<T>) is not applicable
(no instance(s) of type variable(s) T exist so that argument type org.hamcrest.Matcher<java.lang.Iterable<? extends model.Agents>> conforms to formal parameter type org.hamcrest.Matcher<T>)
method org.junit.Assert.<T>assertThat(java.lang.String,T,org.hamcrest.Matcher<T>) is not applicable
(cannot instantiate from arguments because actual and formal argument lists differ in length)
어떻게 써야 되지?
두 목록이 동일하다고 주장하려면 Hamcrest를 복잡하게 만들지 마십시오.
assertEquals(expectedList, actual.getList());
순서에 구애받지 않는 비교를 정말로 실행하는 경우containsInAnyOrder
vararargs 메서드 및 직접 값을 제공합니다.
assertThat(actual.getList(), containsInAnyOrder("item1", "item2"));
(목록이 다음과 같다고 가정합니다.String
,보다는Agent
(이 예에서는).
같은 메서드를 정말로 호출하고 싶은 경우,List
:
assertThat(actual.getList(), containsInAnyOrder(expectedList.toArray(new String[expectedList.size()]));
이렇게 하지 않으면 단일 인수로 메서드를 호출하고,Matcher
에 필적할 것으로 기대됩니다.Iterable
여기서 각 요소는List
. 이 명령어는 다음 명령어를 매칭할 수 없습니다.List
.
즉, 이 명령어를 조합할 수 없습니다.List<Agent>
와 함께Matcher<Iterable<List<Agent>>
그게 바로 당신의 코드가 시도하고 있는 겁니다.
List<Long> actual = Arrays.asList(1L, 2L);
List<Long> expected = Arrays.asList(2L, 1L);
assertThat(actual, containsInAnyOrder(expected.toArray()));
다중 매개 변수가 없는 @Joe 응답의 단축 버전입니다.
@Joe의 답변을 보완하려면:
Hamcrest는 목록과 일치시키는 세 가지 주요 방법을 제공합니다.
contains
순서를 카운트하는 모든 요소가 일치하는지 확인합니다. 목록에 요소가 많거나 적으면 실패합니다.
containsInAnyOrder
모든 요소가 일치하는지 확인합니다.순서는 중요하지 않습니다.목록에 요소가 많거나 적으면 실패합니다.
hasItems
지정된 개체만 확인합니다. 목록에 더 많은 개체가 있더라도 상관 없습니다.
hasItem
하나의 오브젝트만 체크합니다.목록에 더 많은 오브젝트가 있어도 상관없습니다.
모두 오브젝트 목록을 수신하여equals
비교 방법 또는 @borjab과 같은 다른 투수와 혼합할 수 있습니다.
assertThat(myList , contains(allOf(hasProperty("id", is(7L)),
hasProperty("name", is("testName1")),
hasProperty("description", is("testDesc1"))),
allOf(hasProperty("id", is(11L)),
hasProperty("name", is("testName2")),
hasProperty("description", is("testDesc2")))));
http://hamcrest.org/JavaHamcrest/javadoc/1.3/org/hamcrest/Matchers.html#contains(E...) http://hamcrest.org/JavaHamcrest/javadoc/1.3/org/hamcrest/Matchers.html#containsInAnyOrder(java.util.Collection) http://hamcrest.org/JavaHamcrest/javadoc/1.3/org/hamcrest/Matchers.html#hasItems(T...)
기존 Hamcrest 라이브러리(v.2.0.0.0 기준)에서는 contains를 사용하려면 컬렉션에서 Collection.toArray() 메서드를 사용해야 합니다.InAnyOrder Matcher.이것을 org.hamcrest에 다른 방법으로 추가하는 것이 좋습니다.수강자:
public static <T> org.hamcrest.Matcher<java.lang.Iterable<? extends T>> containsInAnyOrder(Collection<T> items) {
return org.hamcrest.collection.IsIterableContainingInAnyOrder.<T>containsInAnyOrder((T[]) items.toArray());
}
실제로 이 방법을 커스텀 테스트 라이브러리에 추가하여 테스트 케이스의 가독성을 높이기 위해 사용하고 있습니다(장황성이 낮기 때문에).
오브젝트 목록에는 다음과 같은 것이 필요할 수 있습니다.
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.beans.HasPropertyWithValue.hasProperty;
import static org.hamcrest.Matchers.is;
@Test
@SuppressWarnings("unchecked")
public void test_returnsList(){
arrange();
List<MyBean> myList = act();
assertThat(myList , contains(allOf(hasProperty("id", is(7L)),
hasProperty("name", is("testName1")),
hasProperty("description", is("testDesc1"))),
allOf(hasProperty("id", is(11L)),
hasProperty("name", is("testName2")),
hasProperty("description", is("testDesc2")))));
}
추신. 억제된 경고를 피할 수 있는 어떤 도움도 정말 감사할 것입니다.
하세요.Object
에는, 「」가 있습니다.equals()
정의되어 있습니다.그럼.
assertThat(generatedList, is(equalTo(expectedList)));
작동하다.
두 목록을 보존된 순서(엄격한 순서)와 비교하려면 를 사용합니다.
assertThat(actualList, contains("item1","item2"));
특정 순서 없이 비교하려면 다음 명령을 사용합니다.
assertThat(collection, containsInAnyOrder("item1","item2"));
언급URL : https://stackoverflow.com/questions/21624592/hamcrest-compare-collections
'programing' 카테고리의 다른 글
MySQL - 일대일 관계 (0) | 2022.12.27 |
---|---|
json_encode/json_decode - PHP의 어레이 대신 stdClass를 반환합니다. (0) | 2022.12.27 |
이름, 성, 시에서 보낸 이메일 목록을 작성하려면 어떻게 해야 합니까? (0) | 2022.12.07 |
Java에서 문자열 표시 너비 계산 (0) | 2022.12.07 |
원칙 오류: 구문 오류 또는 액세스 위반: 10649 (0) | 2022.12.07 |