vicusbass
vicusbass

Reputation: 1804

Can Spring Boot test classes reuse application context for faster test run?

@ContextConfiguration location attribute does not make sense for Spring Boot integration testing. Is there any other way for reusing application context across multiple test classes annotated with @SpringBootTest ?

Upvotes: 43

Views: 52331

Answers (5)

Adisesha
Adisesha

Reputation: 5258

For us, issue caused by @ConfigurationPropertiesScan present in one test but not the others. RoshanKumar's answer provided a clue.

Upvotes: 0

Bram
Bram

Reputation: 1196

If you land here from Google and have an issue with multiple application contexts being started, also take note of this:

Make sure that when you use @SpringBootTests multiple times that you use the same properties. E.g. if you have one test using simply @SpringBootTest and another one using @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) each will spin up its own context!

Easiest would be to have a BaseIntegrationTest class which you extend in every integration test and put the @SpringBootTest annotation on that base class, e.g.:

package com.example.demo;

import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
public abstract class BaseIntegrationTest{
}

Upvotes: 21

rcomblen
rcomblen

Reputation: 4649

For those like me landing from Google:

If you have <reuseFork>false</reuseFork> in your Maven surefire plugin, there is no chance your context can be reused, as you're effectively spawning a new JVM for each test class.

This is well documented in Spring Documentation: https://docs.spring.io/spring/docs/current/spring-framework-reference/testing.html#testcontext-ctx-management-caching

Upvotes: 13

luboskrnac
luboskrnac

Reputation: 24561

Yes. Actually it is default behavior. The link point to Spring Framework docs, which is used by Spring Boot under the hood.

BTW, context is reused by default also when @ContextConfiguration is used as well.

Upvotes: 31

RoshanKumar Mutha
RoshanKumar Mutha

Reputation: 2445

@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)

The above annotation says the complete context is loaded and same is used across the tests. It means it's loaded once only.

Spring Boot provides a @SpringBootTest annotation which can be used as an alternative to the standard spring-test @ContextConfiguration annotation when you need Spring Boot features. The annotation works by creating the ApplicationContext used in your tests via SpringApplication

Upvotes: 8

Related Questions