简体   繁体   中英

How to run all test classes but only start embedded Tomcat once when using Spring Boot?

My project has a lot of Test classes like this:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class RefererCheckerTest {
...

Each time I want to run all test classes, everyone of them will show the log like this:

2018-08-15 14:59:31.104 [main] INFO osbcetTomcatEmbeddedServletContainer [TomcatEmbeddedServletContainer.java:201] -Tomcat started on port(s): 63003 (http)

2018-08-15 14:59:31.112 [main] INFO cbsmfilter.OAuthLoginTest [StartupInfoLogger.java:57] -Started OAuthLoginTest in 27.571 seconds (JVM running for 33.229)

It seems that initializing a Spring Boot project and its embedded Tomcat costs a lot time. If I have 100 Test classes, it will cost me 27.571 seconds *100 to run all test classes.

Could I have a way to init Spring Boot and Embedded Tomcat only once when run through all my 100 test classes? Time will be saved if so.

There are many scenarios that could cause the spring-context to reload and start w new server, for example:

  • @DirtContext:
  • @TestPropertySource
  • Different @ContextConfgiurations
  • Combination of @WebMvcTest / @SpringBootTest / @SpringBootConfiguration
  • Different @ActiveProfiles

So, let me say what we normally use here to avoid this problems:

First, we create an abstract class that will contain all the params and configurations for the tests:

@RunWith(SpringRunner.class)
@ActiveProfiles("test") 
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ContextConfiguration(classes = [<your application class OR context class>])
public abstract class AbstractSpringBootTest {
}

And then, in all the tests I extend this test class:

public class RefererCheckerTest extends AbstractSpringBootTest {
   ....
}

This makes the SpringBoot start only once during the tests if all of them contain the same configuration.

We current use Spring-Boot 2.0.4.RELEASE and it works perfectly.

NOTE: We use SpringRunner instead of SpringJUnit4ClassRunner as well, it is available since spring-test:4.3+ and requires JUnit 4.12+.

Also, even if the spring-boot restarts, it is supposed to reload only part of the context, and not everything again and take the same time. Also, check how are you running the tests.

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