【问题标题】:Reuse a Spring test context in another project在另一个项目中重用 Spring 测试上下文
【发布时间】:2013-10-29 10:17:25
【问题描述】:

我有两个 Java 项目,“A”和“B”,B 对 A 有 Maven 依赖:

<dependency>
    <!--  Back end stuff -->
    <groupId>com.myapp</groupId>
    <artifactId>ProjectA</artifactId>
    <version>1.0.0</version>
</dependency>

这两个项目在我的工作站上并排放置在一个共同的父文件夹中:

/Myproject
    /ProjectA
    /ProjectB

我也想在项目 B 中的所有单元测试中使用项目 A 的单元测试上下文“test-context.xml”。有没有办法直接引用外部上下文进行测试?这些是使用 Surefire 和 Junit 进行测试的 Maven 项目,但我担心 Surefire 和 Junit 不是我的强项。我很确定有办法做到这一点,但我不知道在哪里寻找答案 - Spring、Junit、Maven、Surefire...?

我的项目“A”单元测试类配置如下:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:test-context.xml"})

并且文件“test-context.xml”位于项目 A 的 /src/test/resources/test-context.xml 中。理想情况下,我会像这样简单地配置我的项目“B”单元测试类:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"ProjectA-reference:test-context.xml"})

但是,我不知道如何配置 ContextConfiguration 元素以指向其他项目。以前有人做过吗?

【问题讨论】:

    标签: java spring junit


    【解决方案1】:

    在 ProjectA 的 pom 中,执行此操作以生成 test-jar 依赖项:

    <build>
        <plugins>
            <plugin>
                <artifactId>maven-jar-plugin</artifactId>
                <executions>
                    <execution>
                        <goals>
                            <goal>test-jar</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
    

    然后,在 ProjectB 的 pom.xml 中,这样做:

        <dependency>
            <groupId>${project.groupId}</groupId>
            <artifactId>ProjectA</artifactId>
            <version>${project.version}</version>
            <type>test-jar</type>
            <scope>test</scope>
        </dependency>
    

    最后,在 ProjectB 的测试类中,您应该能够使用上面尝试的类路径方法从 ProjectA 中的 src/test/resources 引用任何 xml 文件。假设您的文件名为 projectA-test-context.xml 并位于 /src/test/resources/META-INF/spring。

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration("/META-INF/spring/projectA-test-context.xml")
    

    编辑编辑了我的答案,将 /src/main/resources 更正为 /src/test/resources。

    【讨论】:

    • 如果单个 XML 文件是从两个项目中引用的,那么将它移动到某个公共位置不是更有意义,例如项目 C
    • 这是另一种选择,但引用它的过程与我的回答相同。可以将通用文件代替“ProjectA”放在“ProjectTest”或一些类似名称的模块中。我的答案中唯一的调整是依赖关系,将“ProjectA”更改为“ProjectTest”。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-14
    • 2011-09-22
    • 2012-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多