Spring Boot
JUnit Testing
AutoConfiguration
Testing Strategies
Java Development

How to exclude AutoConfiguration classes in Spring Boot JUnit tests?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

To exclude AutoConfiguration classes in Spring Boot JUnit tests, use the exclude attribute on @SpringBootTest, @EnableAutoConfiguration, or test-slice annotations like @WebMvcTest. You can also exclude them via spring.autoconfigure.exclude in a test-specific properties file. This gives you a leaner application context, faster test startup, and isolation from infrastructure dependencies you do not need for a given test.

Spring Boot's autoconfiguration is powerful in production, but during testing it often loads database drivers, message brokers, caches, and security filters that have nothing to do with the unit under test. A test for a REST controller should not fail because Cassandra is unreachable. Excluding irrelevant autoconfiguration classes solves that problem directly.

Method 1: @EnableAutoConfiguration(exclude)

The most explicit approach is placing the exclude attribute on @EnableAutoConfiguration. This works with any test that loads a Spring context.

java
1import org.junit.jupiter.api.Test;
2import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
3import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
4import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
5import org.springframework.boot.test.context.SpringBootTest;
6
7@SpringBootTest
8@EnableAutoConfiguration(exclude = {
9    DataSourceAutoConfiguration.class,
10    SecurityAutoConfiguration.class
11})
12class OrderServiceTest {
13
14    @Test
15    void shouldProcessOrderWithoutDatabase() {
16        // Test logic that does not require a DataSource or Spring Security
17    }
18}

This approach is straightforward because the exclusion is visible right next to the test class declaration. Anyone reading the test immediately understands which parts of the context are intentionally omitted.

Method 2: @SpringBootTest(exclude) or @SpringBootApplication(exclude)

If your test configuration class uses @SpringBootApplication, you can place the exclusion there instead.

java
1import org.springframework.boot.autoconfigure.SpringBootApplication;
2import org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration;
3
4@SpringBootApplication(exclude = {MongoAutoConfiguration.class})
5class TestApplication {
6}

Then reference this configuration in your test:

java
1import org.junit.jupiter.api.Test;
2import org.springframework.boot.test.context.SpringBootTest;
3
4@SpringBootTest(classes = TestApplication.class)
5class UserServiceTest {
6
7    @Test
8    void shouldCreateUser() {
9        // Mongo is not loaded in this context
10    }
11}

This pattern is useful when multiple test classes share the same set of exclusions. A dedicated test configuration class avoids repeating the exclusion list on every test.

Method 3: Test-Slice Annotations

Spring Boot's test-slice annotations like @WebMvcTest, @DataJpaTest, and @WebFluxTest already load only a subset of autoconfiguration. However, even within a slice, you sometimes need further exclusions.

java
1import org.junit.jupiter.api.Test;
2import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
3import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
4import org.springframework.beans.factory.annotation.Autowired;
5import org.springframework.test.web.servlet.MockMvc;
6
7import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
8import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
9
10@WebMvcTest(
11    controllers = ProductController.class,
12    excludeAutoConfiguration = SecurityAutoConfiguration.class
13)
14class ProductControllerTest {
15
16    @Autowired
17    private MockMvc mockMvc;
18
19    @Test
20    void shouldReturnProducts() throws Exception {
21        mockMvc.perform(get("/api/products"))
22               .andExpect(status().isOk());
23    }
24}

Notice that @WebMvcTest uses excludeAutoConfiguration rather than exclude. The attribute name differs from @EnableAutoConfiguration, which is a common source of confusion.

Method 4: Properties-Based Exclusion

You can exclude autoconfiguration classes in application-test.properties or application-test.yml without touching annotations at all.

properties
1# src/test/resources/application-test.properties
2spring.autoconfigure.exclude=\
3  org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration,\
4  org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration

Activate this profile in your test:

java
1import org.junit.jupiter.api.Test;
2import org.springframework.boot.test.context.SpringBootTest;
3import org.springframework.test.context.ActiveProfiles;
4
5@SpringBootTest
6@ActiveProfiles("test")
7class PaymentServiceTest {
8
9    @Test
10    void shouldCalculatePayment() {
11        // DataSource and Security are excluded via properties
12    }
13}

This method keeps test classes clean and centralizes exclusion decisions. It is especially useful when an entire test suite needs the same exclusions.

Performance Impact of Exclusions

Excluding unnecessary autoconfiguration classes has a measurable impact on test execution time. Each autoconfiguration class that loads in a test context triggers bean creation, dependency injection, and potentially external resource initialization (database connections, message broker clients, cache pools). In a large Spring Boot application with many starters, the full autoconfiguration scan can add 10-30 seconds to context initialization.

Spring Boot caches application contexts between tests that share the same configuration. By keeping exclusion sets consistent across related test classes, you maximize context reuse and minimize cold-start overhead. If two test classes exclude different sets of autoconfiguration, Spring creates two separate contexts, which doubles the initialization cost.

java
1// These two tests share a context because their exclusion sets match
2@SpringBootTest
3@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class})
4class OrderServiceTest { }
5
6@SpringBootTest
7@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class})
8class InventoryServiceTest { }

When testing a specific layer (controllers, repositories, or services), prefer the built-in test slices (@WebMvcTest, @DataJpaTest, @WebFluxTest) over @SpringBootTest with exclusions. Test slices load only the autoconfiguration relevant to that layer, so you often need fewer manual exclusions.

Commonly Excluded AutoConfiguration Classes

AutoConfiguration ClassWhat It LoadsTypical Reason to Exclude
DataSourceAutoConfigurationJDBC DataSource and connection poolTests that do not touch a database
SecurityAutoConfigurationSpring Security filter chainController tests where auth is irrelevant
CassandraAutoConfigurationCassandra session and templateNon-Cassandra tests in a multi-module project
RedisAutoConfigurationRedis connection factoryTests that do not use caching or sessions
MongoAutoConfigurationMongoDB client and templateServices that do not depend on Mongo
KafkaAutoConfigurationKafka producer/consumer setupTests for components unrelated to messaging
FlywayAutoConfigurationFlyway database migration runnerUnit tests where schema migration is unnecessary

Verifying What Gets Loaded

If you are unsure which autoconfiguration classes are active, enable the autoconfiguration report.

properties
# application-test.properties
debug=true

Spring Boot will print a conditions evaluation report at startup, listing every autoconfiguration class and whether it was matched (loaded) or excluded. This is the fastest way to confirm your exclusions are working.

You can also check programmatically:

java
1import org.junit.jupiter.api.Test;
2import org.springframework.beans.factory.annotation.Autowired;
3import org.springframework.boot.test.context.SpringBootTest;
4import org.springframework.context.ApplicationContext;
5
6import static org.assertj.core.api.Assertions.assertThat;
7
8@SpringBootTest
9class AutoConfigExclusionVerificationTest {
10
11    @Autowired
12    private ApplicationContext context;
13
14    @Test
15    void dataSourceShouldNotBeLoaded() {
16        assertThat(context.containsBean("dataSource")).isFalse();
17    }
18}

Common Pitfalls

Using the wrong attribute name on test-slice annotations. @WebMvcTest uses excludeAutoConfiguration, not exclude. Using the wrong attribute will compile but silently fail to exclude anything.

Excluding too many classes at once. Aggressive exclusion can cause the context to fail in unexpected ways when beans that do exist depend on excluded infrastructure. Exclude only what you actually need to remove, and let Spring Boot handle the rest.

Forgetting that @SpringBootTest without classes scans for the main @SpringBootApplication class. If your main class has its own exclusions, those apply in tests too. If it does not, you may need to specify a test-specific configuration class.

Not using @ActiveProfiles when relying on properties-based exclusion. The exclusions in application-test.properties only take effect when the "test" profile is active.

Confusing excludeName with exclude. Both exist on @EnableAutoConfiguration. The exclude attribute takes class references, while excludeName takes fully qualified class name strings. Use excludeName only when the class is not on your test classpath.

Summary

Spring Boot offers four ways to exclude autoconfiguration in tests: the exclude attribute on @EnableAutoConfiguration, the same attribute on @SpringBootApplication, the excludeAutoConfiguration attribute on test-slice annotations, and the spring.autoconfigure.exclude property in test configuration files. Use the annotation approach for targeted, per-test exclusions and the properties approach for suite-wide exclusions. Always verify your exclusions are working by enabling debug=true or asserting on the application context. The goal is a test context that loads only what the test actually needs, resulting in faster execution and fewer false failures from missing infrastructure.


Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.