program tip

명령 줄을 사용하여 JUnit 클래스에서 단일 테스트 실행

radiobox 2020. 9. 8. 07:51
반응형

명령 줄을 사용하여 JUnit 클래스에서 단일 테스트 실행


명령 줄과 자바 만 사용하여 JUnit 클래스에서 단일 테스트를 실행할 수있는 접근 방식을 찾으려고합니다.

다음을 사용하여 클래스에서 전체 테스트 세트를 실행할 수 있습니다.

java -cp .... org.junit.runner.JUnitCore org.package.classname

제가 정말로하고 싶은 것은 다음과 같습니다.

java -cp .... org.junit.runner.JUnitCore org.package.classname.method

또는:

java -cp .... org.junit.runner.JUnitCore org.package.classname#method

JUnit 주석을 사용하여이 작업을 수행하는 방법이있을 수 있지만 테스트 클래스의 소스를 수동으로 수정하지 않는 것이 좋습니다 (이 작업을 자동화하려고 시도 함). 나는 또한 Maven이 이것을 할 수있는 방법을 가지고 있다는 것을 알았지 만, 가능하다면 Maven에 의존하는 것을 피하고 싶습니다.

그래서 이것을 할 방법이 있는지 궁금합니다.


내가 찾고있는 요점 :

  • JUnit 테스트 클래스에서 단일 테스트를 실행하는 기능
  • 명령 줄 (JUnit 사용)
  • 테스트 소스 수정 방지
  • 추가 도구 사용 방지

사용자 정의 베어 본 JUnit 러너를 상당히 쉽게 만들 수 있습니다. 다음은 다음과 같은 형식으로 단일 테스트 메서드를 실행하는 것입니다 com.package.TestClass#methodName.

import org.junit.runner.JUnitCore;
import org.junit.runner.Request;
import org.junit.runner.Result;

public class SingleJUnitTestRunner {
    public static void main(String... args) throws ClassNotFoundException {
        String[] classAndMethod = args[0].split("#");
        Request request = Request.method(Class.forName(classAndMethod[0]),
                classAndMethod[1]);

        Result result = new JUnitCore().run(request);
        System.exit(result.wasSuccessful() ? 0 : 1);
    }
}

다음과 같이 호출 할 수 있습니다.

> java -cp path/to/testclasses:path/to/junit-4.8.2.jar SingleJUnitTestRunner 
    com.mycompany.product.MyTest#testB

JUnit 소스를 간략히 살펴본 후 JUnit이 기본적으로이를 지원하지 않는다는 결론에 도달했습니다. IDE에는 모두 다른 작업 중에서 커서 아래에서 테스트 메서드를 실행할 수있는 사용자 지정 JUnit 통합이 있기 때문에 이것은 나에게 문제가되지 않았습니다. 명령 줄에서 직접 JUnit 테스트를 실행 한 적이 없습니다. 나는 항상 IDE 또는 빌드 도구 (Ant, Maven)가 처리하도록했습니다. 특히 기본 CLI 진입 점 (JUnitCore)은 테스트 실패시 0이 아닌 종료 코드 이외의 결과 출력을 생성하지 않기 때문입니다.

참고 : JUnit 버전> = 4.9의 경우 클래스 경로에 hamcrest 라이브러리가 필요합니다.


I use Maven to build my project, and use SureFire maven plugin to run junit tests. Provided you have this setup, then you could do:

mvn -Dtest=GreatTestClass#testMethod test

In this example, we just run a test method named "testMethod" within Class "GreatTestClass".

For more details, check out http://maven.apache.org/surefire/maven-surefire-plugin/examples/single-test.html


We used IntelliJ, and spent quite a bit of time trying to figure it out too.

Basically, it involves 2 steps:

Step 1: Compile the Test Class

% javac -cp .:"/Applications/IntelliJ IDEA 13 CE.app/Contents/lib/*" SetTest.java

Step 2: Run the Test

% java -cp .:"/Applications/IntelliJ IDEA 13 CE.app/Contents/lib/*" org.junit.runner.JUnitCore SetTest

참고URL : https://stackoverflow.com/questions/9288107/run-single-test-from-a-junit-class-using-command-line

반응형