简体   繁体   中英

How to test that Spring Boot does *not* start if datasource creation failed

Is there a way to write unit tests to make sure spring boot API doesn't get started if a certain bean is failed to create. eg: failing to create datasource bean.

This code should do it for you:

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

    @Test
    public void contextLoads() {
    }

}

From the docs:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM