![](/img/trans.png)
[英]Using the parent module scope as a test dependency in the maven sub module
[英]How to add a maven module with @SpringBootApplication to another maven module as a dependency in test scope
我有一个多模块项目,其中只有根模块具有带有@SpringBootApplication 的 class。 其他模块作为依赖项添加到根模块的 POM 文件中。 为了测试其他模块,我创建了一个带有 @SpringBootApplication 注释的模块(我们称之为测试模块) class 和其他测试类,以在模块测试中运行 spring 上下文。 我添加了 test-module 作为对其他模块的依赖项,但是当我使用 maven 运行测试时,spring 上下文没有运行。 如何正确添加?
项目结构:
---> root (this module starts spring context)
|
|--- moduleA
|
|--- moduleB
我想测试 moduleA 和 moduleB,所以我创建了一个带有所需依赖项的测试模块和带有 @SpringBootApplication 注释的 class
|--- test-module (module with @SpringBootApplication)
|
|---> moduleA (test-module as dependency in test scope)
|
|---> moduleB (test-module as dependency in test scope)
如果您的模块没有@SpringBootApplication,您应该在junit 测试代码中使用@ContextConfiguration 而不是@SpringBootTest。
首先,您在 /src/test 下定义一个 class,可能称为“TestConfig”,使用 @Configuration 和 @ComponentScan 导入要测试的 bean。
其次,您在 junit 测试的 header 中使用 @ContextConfiguration(classes = {TestConfig.class})。
以下是示例代码:
TestConfig.java
@Configuration
@ComponentScan(basePackages = {"com.xxx"}) // base package of module or what package you want to import. you can write more ones if there are more than one package.
public class TestConfig {
}
Junit 测试
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = {TestConfig.class})
public class TestServiceA {
@Autowired
public ServiceA serviceA;
//...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.