有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

我有一个多模块项目,其中只有根模块有一个带有@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)

共 (1) 个答案

  1. # 1 楼答案

    如果您的模块没有@SpringBootApplication,您应该在junit测试代码中使用@ContextConfiguration而不是@SpringBootTest

    首先,在/src/test下定义一个类,可能称为“TestConfig”,使用@Configuration和@ComponentScan导入要测试的bean

    其次,在junit测试的头中使用@ContextConfiguration(classes={TestConfig.class})

    下面是示例代码:

    TestConfig。爪哇

    @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;
    
    //...
    }