developer tip

JUnit과 Hamcrest를 함께 사용하는 방법은 무엇입니까?

copycodes 2020. 9. 14. 21:18
반응형

JUnit과 Hamcrest를 함께 사용하는 방법은 무엇입니까?


JUnit 4.8이 Hamcrest 매처와 어떻게 작동하는지 이해할 수 없습니다. 내부 junit-4.8.jar정의 된 매 처가 있습니다 org.hamcrest.CoreMatchers. 동시에 일부가 다른 의 정합 기 hamcrest-all-1.1.jar의는 org.hamcrest.Matchers. 그래서 어디로 가야할까요? 프로젝트에 hamcrest JAR을 명시 적으로 포함하고 JUnit에서 제공하는 매처를 무시해야합니까?

특히 empty()매처에 관심이 있는데이 병에서 찾을 수 없습니다. 다른 게 필요해? :)

그리고 철학적 질문 : JUnit이 org.hamcrest원래 hamcrest 라이브러리를 사용하도록 권장하는 대신 자체 배포판에 패키지를 포함 시킨 이유는 무엇입니까?


junit은 Matchers를 사용하고 더 읽기 쉬운 테스트 코드와 더 나은 실패 메시지를 제공해야하는 assertThat ()이라는 새로운 check assert 메서드를 제공합니다.

이를 사용하기 위해 junit에 포함 된 몇 가지 핵심 매 처가 있습니다. 기본 테스트를 위해 이것으로 시작할 수 있습니다.

더 많은 매처를 사용하려면 직접 작성하거나 hamcrest lib를 사용할 수 있습니다.

다음 예제는 ArrayList에서 빈 매처를 사용하는 방법을 보여줍니다.

package com.test;

import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;

import java.util.ArrayList;
import java.util.List;

import org.junit.Test;

public class EmptyTest {
    @Test
    public void testIsEmpty() {
        List myList = new ArrayList();
        assertThat(myList, is(empty()));

    }
}

(내 빌드 경로에 hamcrest-all.jar을 포함했습니다)


1.2보다 크거나 같은 버전의 Hamcrest를 사용하는 경우 junit-dep.jar. 이 jar에는 Hamcrest 클래스가 없으므로 클래스 로딩 문제를 피할 수 있습니다.

JUnit 4.11 이후 junit.jar자체에는 Hamcrest 클래스가 없습니다. junit-dep.jar더 이상 필요가 없습니다.


귀하의 질문에 정확히 대답하는 것은 아니지만 FEST-Assert 유창한 주장 API를 반드시 시도해야 합니다. Hamcrest와 경쟁하고 있지만 정적 가져 오기가 하나만 필요한 훨씬 더 쉬운 API가 있습니다. 다음은 FEST를 사용하여 cpater에서 제공하는 코드입니다 .

package com.test;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import static org.fest.assertions.Assertions.assertThat;

public class EmptyTest {
    @Test
    public void testIsEmpty() {
        List myList = new ArrayList();
        assertThat(myList).isEmpty();
    }  
}

편집 : Maven 좌표 :

<dependency>
  <groupId>org.easytesting</groupId>
  <artifactId>fest-assert</artifactId>
  <version>1.4</version>
  <scope>test</scope>
</dependency>

또한 JUnit 4.1.1 + Hamcrest 1.3 + Mockito 1.9.5를 사용하는 경우 mockito-all이 사용되지 않는지 확인하십시오. 그것은 Hamcrest 핵심 클래스를 포함합니다. 대신 mockito-core를 사용하십시오. 아래 구성이 작동합니다.

<dependency>
    <groupId>org.hamcrest</groupId>
    <artifactId>hamcrest-all</artifactId>
    <version>1.3</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-core</artifactId>
    <version>1.9.5</version>
    <scope>test</scope>
    <exclusions>
        <exclusion>
            <artifactId>hamcrest-core</artifactId>
            <groupId>org.hamcrest</groupId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.1.1</version>
    <scope>test</scope>
    <exclusions>
        <exclusion>
            <artifactId>hamcrest-core</artifactId>
            <groupId>org.hamcrest</groupId>
        </exclusion>
    </exclusions>
</dependency>

버전이 항상 변경되기 때문에 2014 년 12 월 2 일 현재 http://www.javacodegeeks.com/2014/03/how-to-test-dependencies-in에 있는 지침을 사람들에게 알리기 위해 게시하고 있습니다 . -a-maven-project-junit-mockito-hamcrest-assertj.html 이 저에게 효과적 이었습니다. 하지만 AssertJ를 사용하지 않았습니다.

<dependency>
  <groupId>junit</groupId>
  <artifactId>junit</artifactId>
  <version>4.11</version>
  <scope>test</scope>
</dependency>
<dependency>
  <groupId>org.mockito</groupId>
  <artifactId>mockito-core</artifactId>
  <version>1.9.5</version>
  <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.hamcrest</groupId>
    <artifactId>hamcrest-core</artifactId>
    <version>1.3</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.hamcrest</groupId>
    <artifactId>hamcrest-library</artifactId>
    <version>1.3</version>
    <scope>test</scope>
</dependency>   
<dependency>
    <groupId>org.objenesis</groupId>
    <artifactId>objenesis</artifactId>
    <version>1.3</version>
    <scope>test</scope>
</dependency>

why JUnit included org.hamcrest package into its own distribution instead of encouraging us to use original hamcrest library?

I would guess that's because they wanted the assertThat to be part of JUnit. So that means the Assert class has to import the org.hamcrest.Matcher interface and it can't do that unless JUnit either depends on Hamcrest, or includes (at least part of) Hamcrest. And I guess including part of it was easier, so that JUnit would be usable without any dependencies.


Both JUnit-4.12 and JUnit-Dep-4.10 has Hamcrest dependencies according to the respective .xml files.

Further investigation shows that although the dependency was made in the .xml files, the source and classes in the jars. The seems to be a way of excluding the dependency in build.gradle ... testing it out to keep everything clean.

Just an f.y.i.


In 2018 using most modern libraries:

configurations {
    all {
        testCompile.exclude group: "org.hamcrest", module: "hamcrest-core"
        testCompile.exclude group: "org.hamcrest", module: "hamcrest-library"
    }
}
dependencies {
    testCompile("junit:junit:4.12")
    // testCompile("org.hamcrest:hamcrest-library:1.3")
    // testCompile("org.hamcrest:java-hamcrest:2.0.0.0")
    testCompile("org.hamcrest:hamcrest-junit:2.0.0.0")
}

참고URL : https://stackoverflow.com/questions/5569394/how-to-use-junit-and-hamcrest-together

반응형