gpt4 book ai didi

java - 在另一个项目中重用 Spring 测试上下文

转载 作者:搜寻专家 更新时间:2023-11-01 02:10:31 24 4
gpt4 key购买 nike

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

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

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

/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 元素以指向其他项目。以前有人这样做过吗?

最佳答案

在 ProjectA 的 pom 中,执行此操作以生成测试 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")

关于java - 在另一个项目中重用 Spring 测试上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19485772/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com