복붙노트

[SPRING] 실행 항아리에서 실행 스프링 테스트

SPRING

실행 항아리에서 실행 스프링 테스트

나는 응용 프로그램 컨텍스트 및 테스트 몇 가지 서비스를 회전 일부 봄 테스트가 있습니다. 나는 메이븐과 IDE를 사용하여 이러한 테스트를 실행할 수 있어요. 지금은 메이븐에 대한 액세스 권한이없는 다른 컴퓨터에서이 테스트를 실행하기위한 요구 사항을 가지고있다. 내 생각은 테스트 단지를 만들고 명령 줄을 통해 실행하는 것이 었습니다.

그래서 나는 내가 필요로하는 테스트 클래스를 호출하고이 테스트는 Spring 애플리케이션 컨텍스트를 회전하고 일부 서비스를 테스트하는 사용자 정의 러너를 만들었습니다.

다음 샘플 코드는 다음과 같습니다

내 사용자 정의 러너 :

public class Main {

    public static void main(String[] args) {
        System.out.println("Running tests!");
        JUnitCore engine = new JUnitCore();
        engine.addListener(new TextListener(System.out));
        engine.run(SpringSampleTest.class);
    }
} 

상기 러너이 시험으로 호출

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {AppConfig.class})
public class SpringSampleTest {
    @Autowired
    TestService testService;

    @Test
    public void testSimple() {
        assertTrue("Test Simple", testService.isValid());
    }
}

여기 내 설정 및 서비스입니다

@Configuration
@ComponentScan(basePackages = {"mypackage"})
public class AppConfig {

}

@Service
public class TestService {

    public boolean isValid() {
        return true;
    }
}

그래서 항아리에서 이러한 테스트를 실행하기 위해, 나는 (이 대답 덕분에 여기) 내 모든 테스트 및 종속성을 포함하는 실행 항아리를 만들 어셈블리 플러그인을 사용하고 있습니다. 나는이 실행 항아리를 실행하고 때 지금, 내 사용자 정의 러너 (Main.java는) 테스트를 트리거 할 수 있지만 스프링 컨텍스트를로드하지 않고 내 종속성 autowire가되지 않습니다 때문에 NullPointer 예외와 함께 실패합니다. 여기에 로그는 다음과 같습니다

Running tests!
Sep 05, 2018 5:15:01 PM org.springframework.test.context.support.DefaultTestContextBootstrapper getDefaultTestExecutionListenerClassNames
INFO: Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: []
Sep 05, 2018 5:15:01 PM org.springframework.test.context.support.DefaultTestContextBootstrapper getTestExecutionListeners
INFO: Using TestExecutionListeners: []
.E
Time: 0.007
There was 1 failure:
1) testSimple(com.c0deattack.cu.runners.SpringSampleTest)
java.lang.NullPointerException
    at com.c0deattack.cu.runners.SpringSampleTest.testSimple(SpringSampleTest.java:19)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
    at org.junit.runners.Suite.runChild(Suite.java:128)
    at org.junit.runners.Suite.runChild(Suite.java:27)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:115)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:105)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:94)
    at com.c0deattack.cu.runners.Main.main(Main.java:15)

FAILURES!!!
Tests run: 1,  Failures: 1

누군가 내가 뭘 잘못 지적시겠습니까?

나는 또한 내 pom.xml 파일 및 조립 기술자 파일을 추가하고있다 :

pom.hml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>mypackage</groupId>
    <artifactId>executable-tests</artifactId>
    <version>1.0</version>
    <packaging>jar</packaging>

    <name>executable-tests</name>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.3.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>4.3.2.RELEASE</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>

            <plugin>
                <artifactId>maven-assembly-plugin</artifactId>
                <configuration>
                    <descriptor>src/main/assembly/assembly.xml</descriptor>
                </configuration>
                <executions>
                    <execution>
                        <id>make-assembly</id>
                        <phase>package</phase>
                        <goals>
                            <goal>assembly</goal>
                        </goals>
                        <configuration>
                            <archive>
                                <manifest>
                                    <mainClass>mypackage.Main</mainClass>
                                </manifest>
                            </archive>
                        </configuration>
                    </execution>
                </executions>
            </plugin>            
        </plugins>
    </build>
</project>

설명 - assembly.xml

<assembly
        xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3 http://maven.apache.org/xsd/assembly-1.1.3.xsd">
    <id>fat-tests</id>
    <formats>
        <format>jar</format>
    </formats>
    <includeBaseDirectory>false</includeBaseDirectory>
    <dependencySets>
        <dependencySet>
            <outputDirectory>/</outputDirectory>
            <useProjectArtifact>true</useProjectArtifact>
            <unpack>true</unpack>
            <scope>test</scope>
        </dependencySet>
    </dependencySets>
    <fileSets>
        <fileSet>
            <directory>${project.build.directory}/test-classes</directory>
            <outputDirectory>/</outputDirectory>
            <includes>
                <include>**/*.class</include>
            </includes>
            <useDefaultExcludes>true</useDefaultExcludes>
        </fileSet>
    </fileSets>
</assembly>

당신은 GitHub의에서 샘플 프로젝트를 살펴 가질 수 있습니다 https://github.com/SaiUpadhyayula/executabletests

해결법

  1. ==============================

    1.난 그냥 저장소를 포크하고 난 오류를 발견했다. 봄 공장은 시험 받는다는에 의해 발생하는 경우에 사용되는 것과 동일해야합니다. 이 테스트 컨텍스트와 같은 동일한 방법으로 봄 IC에 위임 할 필수입니다.

    난 그냥 저장소를 포크하고 난 오류를 발견했다. 봄 공장은 시험 받는다는에 의해 발생하는 경우에 사용되는 것과 동일해야합니다. 이 테스트 컨텍스트와 같은 동일한 방법으로 봄 IC에 위임 할 필수입니다.

    자세한 내용은 끌어 오기 요청을 참조하십시오 :

    https://github.com/SaiUpadhyayula/executabletests/pull/2

  2. ==============================

    2.내가 마지막으로 테스트를 디버깅 후 문제가 발견, 알고 보니 그 봄을 찾아 것 TestContext 부트 스트랩 동안 TestExecutionListener의 스프링 테스트 항아리 내부의 META-INF는 / spring.factories 파일 내에 정의.

    내가 마지막으로 테스트를 디버깅 후 문제가 발견, 알고 보니 그 봄을 찾아 것 TestContext 부트 스트랩 동안 TestExecutionListener의 스프링 테스트 항아리 내부의 META-INF는 / spring.factories 파일 내에 정의.

    이 파일은 이상적으로 내 실행 항아리의 META-INF 폴더 안에 위치해야 spring.factories. 그러나 어셈블리 - 플러그인이하는 것은 필요한 TestExecutionListener의 포함 권리 spring.factories 파일을 추가하지 않은입니다

    SRC / 메인 / 자원 / META-INF에이 파일을 추가 / spring.factories 문제를 해결

    # Default TestExecutionListeners for the Spring TestContext Framework
    #
    org.springframework.test.context.TestExecutionListener = \
        org.springframework.test.context.web.ServletTestExecutionListener,\
        org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener,\
        org.springframework.test.context.support.DependencyInjectionTestExecutionListener,\
        org.springframework.test.context.support.DirtiesContextTestExecutionListener,\
        org.springframework.test.context.transaction.TransactionalTestExecutionListener,\
        org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener
    
    # Default ContextCustomizerFactory implementations for the Spring TestContext Framework
    #
    org.springframework.test.context.ContextCustomizerFactory = \
        org.springframework.test.context.web.socket.MockServerContainerContextCustomizerFactory
    
  3. ==============================

    3.당신은 테스트를 실행하는 다른 컴퓨터에 받는다는 설치해야합니다.

    당신은 테스트를 실행하는 다른 컴퓨터에 받는다는 설치해야합니다.

    받는다는 설치가 가능한 옵션이 아닌 경우, 테스트 클래스를 포함하는 항아리를 작성하고 테스트를 실행이 항아리를 사용합니다. http://maven.apache.org/plugins/maven-jar-plugin/examples/create-test-jar.html - 받는다는 문서를 확인

  4. from https://stackoverflow.com/questions/52188683/running-spring-tests-from-executable-jar by cc-by-sa and MIT license