如何将带有@SpringBootApplication的maven模块添加到另一个maven模块作为测试范围中的依赖项

How to add a maven module with @SpringBootApplication to another maven module as a dependency in test scope

我有一个多模块项目,其中只有根模块有一个 class 和 @SpringBootApplication。其他模块作为依赖项添加到根模块的 POM 文件中。为了测试其他模块,我创建了一个模块(我们称之为测试模块),@SpringBootApplication 注释为 class 和其他测试 classes 到 运行 模块测试中的 spring 上下文.我添加了测试模块作为对其他模块的依赖,但是当我 运行 使用 maven 测试时 spring 上下文没有 运行。如何正确添加?

项目结构:

---> root (this module starts spring context)
|
|--- moduleA
|
|--- moduleB

我想测试 moduleA 和 moduleB,所以我创建了一个具有所需依赖项的测试模块,并且 class 带有 @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下定义一个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 {
}

联合测试

@RunWith(SpringRunner.class)
@ContextConfiguration(classes = {TestConfig.class})
public class TestServiceA {

    @Autowired
    public ServiceA serviceA;

//...
}