gpt4 book ai didi

java - 如果数据源创建失败,如何测试 Spring Boot 是否“不”启动

转载 作者:太空宇宙 更新时间:2023-11-04 09:52:59 27 4
gpt4 key购买 nike

有没有办法编写单元测试来确保如果某个 bean 创建失败,Spring Boot API 不会启动。例如:无法创建数据源 bean。

最佳答案

此代码应该可以为您完成:

@RunWith(SpringRunner.class)
@SpringBootTest
public class AnyAppNameApplicationTests {

@Test
public void contextLoads() {
}

}

来自文档:

Annotation that can be specified on a test class that runs Spring Boot based tests. Provides the following features over and above the regular Spring TestContext Framework:

  • Uses SpringBootContextLoader as the default ContextLoader when no specific @ContextConfiguration(loader=...) is defined.
  • Automatically searches for a @SpringBootConfiguration when nested @Configuration is not used, and no explicit classes are specified.
  • Allows custom Environment properties to be defined using the properties attribute.
  • Provides support for different webEnvironment modes, including the ability to start a fully running web server listening on a defined or random port.
  • Registers a TestRestTemplate and/or WebTestClient bean for use in web tests that are using a fully running web server.

If you are using JUnit 4, don’t forget to also add @RunWith(SpringRunner.class) to your test, otherwise the annotations will be ignored. If you are using JUnit 5, there’s no need to add the equivalent @ExtendWith(SpringExtension) as @SpringBootTest and the other @…Test annotations are already annotated with it.

关于java - 如果数据源创建失败,如何测试 Spring Boot 是否“不”启动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54472403/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com