我有一个多模块项目,其中只有根模块有一个带有@SpringBootApplication 的类。其他模块作为依赖项添加到根模块的 POM 文件中。为了测试其他模块,我创建了一个带有@SpringBootApplication 注释类和其他测试类的模块(我们称之为测试模块),以在模块测试中运行 spring 上下文。我添加了测试模块作为对其他模块的依赖,但是当我使用 maven 运行测试时,spring 上下文没有运行。如何正确添加?
项目结构:
---> root (this module starts spring context)
|
|--- moduleA
|
|--- moduleB
我想测试 moduleA 和 moduleB,所以我创建了一个具有所需依赖项的测试模块和带有 @SpringBootApplication 注释的类
|--- 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 下定义一个类,可能称为“TestConfig”,使用@Configuration 和@ComponentScan 导入您要测试的bean。
其次,您在 junit 测试的 header 中使用 @ContextConfiguration(classes = {TestConfig.class})。
下面是示例代码:
测试配置.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 {
}
联合测试
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = {TestConfig.class})
public class TestServiceA {
@Autowired
public ServiceA serviceA;
//...
}
关于java - 如何将带有@SpringBootApplication的maven模块添加到另一个maven模块作为测试范围中的依赖项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65431959/