测试 Spring Boot 库模块

我有一个多模块项目,其中并非每个模块实际上都是应用程序,但其中很多都是库。这些库正在完成主要工作,我想在它们的实现位置测试它们。库的当前依赖项:


implementation 'org.springframework.boot:spring-boot-starter'

testImplementation 'org.springframework.boot:spring-boot-starter-test'

在主要源代码中是一个带有@Configuration单个 bean 的类:


@Bean public String testString() { return "A Test String"; }

我有2个测试班:


@RunWith(SpringRunner.class)

@SpringBootTest

@ActiveProfiles({"default", "test"}) 

public class Test1 {  


    @Test

    public void conextLoaded() {

    }

}

-


@RunWith(SpringRunner.class)

@SpringBootTest

@ActiveProfiles({"default", "test"}) 

public class Test2 {  

    @Autowired

    private String testString; 


    @Test

    public void conextLoaded() {

    }

}

第一次测试有效。第二个没有。该项目中没有@SpringBootApplication任何地方,因此在与测试相同的包中我添加了测试配置:


@SpringBootConfiguration

@EnableAutoConfiguration

@ComponentScan("com.to.config") 

public class LibTestConfiguration {

}

但它不起作用。对于 的类也是如此@Service。它们不在上下文中。我怎样才能让它像一个普通的 Spring boot 应用程序一样运行,而不需要它真正成为一个应用程序并从我需要的配置文件中加载配置和上下文?默认配置文件和测试配置文件共享它们的大部分属性(目前),我希望它们像启动 tomcat 一样加载。


慕码人8056858
浏览 52回答 2
2回答

回首忆惘然

我切换到 JUnit 5 并使它有点工作......所以如果你想测试数据库的东西:@DataMongoTest@ExtendWith(SpringExtension.class)@ActiveProfiles({"default", "test"})class BasicMongoTest { ... }允许您自动装配所有存储库和 mongo 模板使用 aplicaton.yml 配置进行初始化不初始化或配置拦截器如果您的类路径中有一个类,则完整的应用程序上下文测试@SpringBootApplication(可以是测试上下文中的空测试 main)@SpringBootTest@ExtendWith(SpringExtension.class)@ActiveProfiles({"default", "test"})public class FullContextTest { ... }使用所有配置和 bean 初始化完整上下文如果没有必要,就不应该这样做,因为它会加载所有应用程序上下文,并且有点违背了单元测试仅激活所需内容的目的。仅测试特定组件和配置:@SpringBootTest(classes = {Config1.class, Component1.class})@EnableConfigurationProperties@ExtendWith(SpringExtension.class)@ActiveProfiles({"default", "test"})public class SpecificComponentsTest { ... }仅使用 Config1 和 Component1 类初始化上下文。Component1 和 Config1 中的所有 bean 都可以自动装配。

波斯汪

我已经解决了在根测试包路径中添加一个SpringAppConfiguration类的问题@SpringBootConfiguration@ComponentScan@EnableAutoConfigurationpublic class SpringAppConfiguration {    public static void main(String[] args) {        SpringApplication.run(SpringAppConfiguration.class, args);    }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java