IT박스

Hamcrest에서 목록이 비어 있지 않은지 확인

itboxs 2020. 6. 21. 20:26
반응형

Hamcrest에서 목록이 비어 있지 않은지 확인


사람이 목록을 사용하여 비어있는 경우 확인하는 방법을 알고 있는지 궁금 assertThat()하고 Matchers?

JUnit을 사용하는 가장 좋은 방법은 다음과 같습니다.

assertFalse(list.isEmpty());

그러나 나는 Hamcrest에서 이것을 할 수있는 방법이 있기를 바랐습니다.


항상있다

assertThat(list.isEmpty(), is(false));

...하지만 나는 그것이 당신이 의미하는 것이 아니라고 추측합니다 :)

또는

assertThat((Collection)list, is(not(empty())));

empty()Matchers클래스 에서 정적입니다 . 캐스팅 할 필요가 참고 listCollection, Hamcrest 1.2의 불안정한 제네릭 덕분에.

hamcrest 1.3과 함께 다음 수입품을 사용할 수 있습니다

import static org.hamcrest.Matchers.empty;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsNot.*;

이것은 Hamcrest 1.3에서 수정되었습니다. 아래 코드는 컴파일하고 경고를 생성하지 않습니다.

// given
List<String> list = new ArrayList<String>();
// then
assertThat(list, is(not(empty())));

그러나 이전 버전을 사용해야하는 경우 버그 대신 empty()다음을 사용할 수 있습니다.

hasSize(greaterThan(0))
( import static org.hamcrest.number.OrderingComparison.greaterThan;또는
import static org.hamcrest.Matchers.greaterThan;)

예:

// given
List<String> list = new ArrayList<String>();
// then
assertThat(list, hasSize(greaterThan(0)));

위의 솔루션에서 가장 중요한 것은 경고를 생성하지 않는다는 것입니다. 최소 결과 크기를 추정하려는 경우 두 번째 솔루션이 훨씬 더 유용합니다.


읽을 수있는 실패 메시지가 표시되면 빈 목록과 함께 일반적인 assertEquals를 사용하여 방해 금지없이 수행 할 수 있습니다.

assertEquals(new ArrayList<>(0), yourList);

예를 들어 달리면

assertEquals(new ArrayList<>(0), Arrays.asList("foo", "bar");

당신은 얻을

java.lang.AssertionError
Expected :[]
Actual   :[foo, bar]

나만의 커스텀 IsEmpty TypeSafeMatcher를 생성하십시오 :

제네릭 문제 1.3가이 메서드 대한 큰 문제로 해결 되더라도 메서드가있는 모든 클래스에서 작동합니다 isEmpty()! 뿐만 아니라 Collections!

예를 들어 작동 String합니다!

/* Matches any class that has an <code>isEmpty()</code> method
 * that returns a <code>boolean</code> */ 
public class IsEmpty<T> extends TypeSafeMatcher<T>
{
    @Factory
    public static <T> Matcher<T> empty()
    {
        return new IsEmpty<T>();
    }

    @Override
    protected boolean matchesSafely(@Nonnull final T item)
    {
        try { return (boolean) item.getClass().getMethod("isEmpty", (Class<?>[]) null).invoke(item); }
        catch (final NoSuchMethodException e) { return false; }
        catch (final InvocationTargetException | IllegalAccessException e) { throw new RuntimeException(e); }
    }

    @Override
    public void describeTo(@Nonnull final Description description) { description.appendText("is empty"); }
}

참고 URL : https://stackoverflow.com/questions/3631110/checking-that-a-list-is-not-empty-in-hamcrest

반응형