Close

Spring Boot - Using @TestConfiguration to define beans for tests

[Last Updated: Aug 11, 2020]

In Spring Boot, @TestConfiguration annotation can be used to define/override beans for unit tests.

@TestConfiguration vs @Configuration

@TestConfiguration classes (in test folder) can only be used by selective test classes which explicitly want to import them via @import annotation.
@Configuration classes (in test folder), are available for all tests without explicitly importing them.

Example

Boot example project

pom.xml

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-test</artifactId>
</dependency>
@Component
public class MyHelloProcessor {
  @Autowired
  private HelloService helloService;

  public String sayHi(String name) {
      return helloService.getMessage(name);
  }
}
public interface HelloService {
  String getMessage(String name);
}
@Service
public class HelloServiceImpl implements HelloService {
  public String getMessage(String name) {
      return String.format("Hi there, %s.", name);
  }
}
@SpringBootApplication
public class AppMain {
  public static void main(String[] args) {
      ConfigurableApplicationContext context =
              SpringApplication.run(AppMain.class, args);
      MyHelloProcessor bean = context.getBean(MyHelloProcessor.class);
      String msg = bean.sayHi("Joe");
      System.out.println(msg);
  }
}

. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.2.5.RELEASE)

2020-04-18 00:45:28.035 INFO 10196 --- [ main] com.logicbig.example.AppMain : Starting AppMain on DESKTOP-VCSEKL5 with PID 10196 (D:\example-projects\spring-boot\unit-testing\spring-boot-test-configuration\target\classes started by Joe in d:\example-projects\spring-boot\unit-testing\spring-boot-test-configuration)
2020-04-18 00:45:28.038 INFO 10196 --- [ main] com.logicbig.example.AppMain : No active profile set, falling back to default profiles: default
2020-04-18 00:45:28.654 INFO 10196 --- [ main] com.logicbig.example.AppMain : Started AppMain in 1.219 seconds (JVM running for 1.939)
Hi there, Joe.

Using @TestConfiguration

spring-boot-test-configuration/src/test/java/com/logicbig/example/MyTestConfig.java

package com.logicbig.example;

import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.context.annotation.Bean;

@TestConfiguration
public class MyTestConfig {
  @Bean
  public HelloService helloService(){
      return new HelloService() {
          @Override
          public String getMessage(String name) {
              return "Test hello: "+name;
          }
      };
  }
}

Importing @TestConfiguration in a test class

package com.logicbig.example;

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Import;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
@Import(MyTestConfig.class)
public class MyHelloProcessorTest {
  @Autowired
  private MyHelloProcessor myHelloProcessor;

  @Test
  public void testSayHi() {
      String message = myHelloProcessor.sayHi("Joe");
      System.out.println(message);
      Assert.assertEquals(message, "Test hello: Joe");
  }
}
D:\spring-boot-test-configuration>mvn test -Dtest=MyHelloProcessorTest.java
[INFO] Scanning for projects...
[INFO]
[INFO] --------< com.logicbig.example:spring-boot-test-configuration >---------
[INFO] Building spring-boot-test-configuration 1.0-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- maven-resources-plugin:3.1.0:resources (default-resources) @ spring-boot-test-configuration ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO]
[INFO] --- maven-compiler-plugin:3.8.1:compile (default-compile) @ spring-boot-test-configuration ---
[INFO] Changes detected - recompiling the module!
[INFO]
[INFO] --- maven-resources-plugin:3.1.0:testResources (default-testResources) @ spring-boot-test-configuration ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO]
[INFO] --- maven-compiler-plugin:3.8.1:testCompile (default-testCompile) @ spring-boot-test-configuration ---
[INFO] Changes detected - recompiling the module!
[INFO]
[INFO] --- maven-surefire-plugin:2.22.2:test (default-test) @ spring-boot-test-configuration ---
[INFO]
[INFO] -------------------------------------------------------
[INFO] T E S T S
[INFO] -------------------------------------------------------
00:52:27.616 [main] DEBUG org.springframework.test.context.junit4.SpringJUnit4ClassRunner - SpringJUnit4ClassRunner constructor called with [class com.logicbig.example.MyHelloProcessorTest]
00:52:27.624 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating CacheAwareContextLoaderDelegate from class [org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate]
00:52:27.656 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating BootstrapContext using constructor [public org.springframework.test.context.support.DefaultBootstrapContext(java.lang.Class,org.springframework.test.context.CacheAwareContextLoaderDelegate)]
00:52:27.741 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating TestContextBootstrapper for test class [com.logicbig.example.MyHelloProcessorTest] from class [org.springframework.boot.test.context.SpringBootTestContextBootstrapper]
00:52:27.769 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Neither @ContextConfiguration nor @ContextHierarchy found for test class [com.logicbig.example.MyHelloProcessorTest], using SpringBootContextLoader
00:52:27.775 [main] DEBUG org.springframework.test.context.support.AbstractContextLoader - Did not detect default resource location for test class [com.logicbig.example.MyHelloProcessorTest]: class path resource [com/logicbig/example/MyHelloProcessorTest-context.xml] does not exist
00:52:27.778 [main] DEBUG org.springframework.test.context.support.AbstractContextLoader - Did not detect default resource location for test class [com.logicbig.example.MyHelloProcessorTest]: class path resource [com/logicbig/example/MyHelloProcessorTestContext.groovy] does not exist
00:52:27.779 [main] INFO org.springframework.test.context.support.AbstractContextLoader - Could not detect default resource locations for test class [com.logicbig.example.MyHelloProcessorTest]: no resource found for suffixes {-context.xml, Context.groovy}.
00:52:27.780 [main] INFO org.springframework.test.context.support.AnnotationConfigContextLoaderUtils - Could not detect default configuration classes for test class [com.logicbig.example.MyHelloProcessorTest]: MyHelloProcessorTest does not declare any static, non-private, non-final, nested classes annotated with @Configuration.
00:52:27.847 [main] DEBUG org.springframework.test.context.support.ActiveProfilesUtils - Could not find an 'annotation declaring class' for annotation type [org.springframework.test.context.ActiveProfiles] and class [com.logicbig.example.MyHelloProcessorTest]
00:52:27.954 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Found @SpringBootConfiguration com.logicbig.example.AppMain for test class com.logicbig.example.MyHelloProcessorTest
00:52:28.111 [main] DEBUG org.springframework.boot.test.context.SpringBootTestContextBootstrapper - @TestExecutionListeners is not present for class [com.logicbig.example.MyHelloProcessorTest]: using defaults.
00:52:28.113 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener, org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener, org.springframework.test.context.event.EventPublishingTestExecutionListener]
00:52:28.178 [main] DEBUG org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Skipping candidate TestExecutionListener [org.springframework.test.context.web.ServletTestExecutionListener] due to a missing dependency. Specify custom listener classes or make the default listener classes and their required dependencies available. Offending class: [javax/servlet/ServletContext]
00:52:28.184 [main] DEBUG org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Skipping candidate TestExecutionListener [org.springframework.test.context.transaction.TransactionalTestExecutionListener] due to a missing dependency. Specify custom listener classes or make the default listener classes and their required dependencies available. Offending class: [org/springframework/transaction/interceptor/TransactionAttributeSource]
00:52:28.188 [main] DEBUG org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Skipping candidate TestExecutionListener [org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener] due to a missing dependency. Specify custom listener classes or make the default listener classes and their required dependencies available. Offending class: [org/springframework/transaction/interceptor/TransactionAttribute]
00:52:28.188 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Using TestExecutionListeners: [org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener@7d9f158f, org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener@45efd90f, org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener@4b8729ff, org.springframework.test.context.support.DirtiesContextTestExecutionListener@61710c6, org.springframework.test.context.event.EventPublishingTestExecutionListener@3214ee6, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener@383dc82c, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener@4a07d605, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener@74287ea3, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener@7d7758be, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener@2bdd8394]
00:52:28.201 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved @ProfileValueSourceConfiguration [null] for test class [com.logicbig.example.MyHelloProcessorTest]
00:52:28.203 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [com.logicbig.example.MyHelloProcessorTest]
00:52:28.251 [main] DEBUG org.springframework.test.context.junit4.SpringJUnit4ClassRunner - SpringJUnit4ClassRunner constructor called with [class com.logicbig.example.MyHelloProcessorTest]
00:52:28.251 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating CacheAwareContextLoaderDelegate from class [org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate]
00:52:28.251 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating BootstrapContext using constructor [public org.springframework.test.context.support.DefaultBootstrapContext(java.lang.Class,org.springframework.test.context.CacheAwareContextLoaderDelegate)]
00:52:28.252 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating TestContextBootstrapper for test class [com.logicbig.example.MyHelloProcessorTest] from class [org.springframework.boot.test.context.SpringBootTestContextBootstrapper]
00:52:28.253 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Neither @ContextConfiguration nor @ContextHierarchy found for test class [com.logicbig.example.MyHelloProcessorTest], using SpringBootContextLoader
00:52:28.254 [main] DEBUG org.springframework.test.context.support.AbstractContextLoader - Did not detect default resource location for test class [com.logicbig.example.MyHelloProcessorTest]: class path resource [com/logicbig/example/MyHelloProcessorTest-context.xml] does not exist
00:52:28.255 [main] DEBUG org.springframework.test.context.support.AbstractContextLoader - Did not detect default resource location for test class [com.logicbig.example.MyHelloProcessorTest]: class path resource [com/logicbig/example/MyHelloProcessorTestContext.groovy] does not exist
00:52:28.255 [main] INFO org.springframework.test.context.support.AbstractContextLoader - Could not detect default resource locations for test class [com.logicbig.example.MyHelloProcessorTest]: no resource found for suffixes {-context.xml, Context.groovy}.
00:52:28.255 [main] INFO org.springframework.test.context.support.AnnotationConfigContextLoaderUtils - Could not detect default configuration classes for test class [com.logicbig.example.MyHelloProcessorTest]: MyHelloProcessorTest does not declare any static, non-private, non-final, nested classes annotated with @Configuration.
00:52:28.258 [main] DEBUG org.springframework.test.context.support.ActiveProfilesUtils - Could not find an 'annotation declaring class' for annotation type [org.springframework.test.context.ActiveProfiles] and class [com.logicbig.example.MyHelloProcessorTest]
00:52:28.259 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Found @SpringBootConfiguration com.logicbig.example.AppMain for test class com.logicbig.example.MyHelloProcessorTest
00:52:28.263 [main] DEBUG org.springframework.boot.test.context.SpringBootTestContextBootstrapper - @TestExecutionListeners is not present for class [com.logicbig.example.MyHelloProcessorTest]: using defaults.
00:52:28.263 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener, org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener, org.springframework.test.context.event.EventPublishingTestExecutionListener]
00:52:28.264 [main] DEBUG org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Skipping candidate TestExecutionListener [org.springframework.test.context.web.ServletTestExecutionListener] due to a missing dependency. Specify custom listener classes or make the default listener classes and their required dependencies available. Offending class: [javax/servlet/ServletContext]
00:52:28.265 [main] DEBUG org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Skipping candidate TestExecutionListener [org.springframework.test.context.transaction.TransactionalTestExecutionListener] due to a missing dependency. Specify custom listener classes or make the default listener classes and their required dependencies available. Offending class: [org/springframework/transaction/interceptor/TransactionAttributeSource]
00:52:28.266 [main] DEBUG org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Skipping candidate TestExecutionListener [org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener] due to a missing dependency. Specify custom listener classes or make the default listener classes and their required dependencies available. Offending class: [org/springframework/transaction/interceptor/TransactionAttribute]
00:52:28.266 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Using TestExecutionListeners: [org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener@723e88f9, org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener@5f0fd5a0, org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener@64e7619d, org.springframework.test.context.support.DirtiesContextTestExecutionListener@495ee280, org.springframework.test.context.event.EventPublishingTestExecutionListener@4fa1c212, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener@6ea2bc93, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener@3116c353, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener@f627d13, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener@4e928fbf, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener@352ff4da]
00:52:28.266 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved @ProfileValueSourceConfiguration [null] for test class [com.logicbig.example.MyHelloProcessorTest]
00:52:28.267 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [com.logicbig.example.MyHelloProcessorTest]
00:52:28.354 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved @ProfileValueSourceConfiguration [null] for test class [com.logicbig.example.MyHelloProcessorTest]
00:52:28.354 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [com.logicbig.example.MyHelloProcessorTest]
[INFO] Running com.logicbig.example.MyHelloProcessorTest
00:52:28.362 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved @ProfileValueSourceConfiguration [null] for test class [com.logicbig.example.MyHelloProcessorTest]
00:52:28.362 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [com.logicbig.example.MyHelloProcessorTest]
00:52:28.363 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved @ProfileValueSourceConfiguration [null] for test class [com.logicbig.example.MyHelloProcessorTest]
00:52:28.363 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [com.logicbig.example.MyHelloProcessorTest]
00:52:28.370 [main] DEBUG org.springframework.test.context.support.AbstractDirtiesContextTestExecutionListener - Before test class: context [DefaultTestContext@d771cc9 testClass = MyHelloProcessorTest, testInstance = [null], testMethod = [null], testException = [null], mergedContextConfiguration = [MergedContextConfiguration@36b4091c testClass = MyHelloProcessorTest, locations = '{}', classes = '{class com.logicbig.example.AppMain}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[[ImportsContextCustomizer@4671115f key = [com.logicbig.example.MyTestConfig]], org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@217ed35e, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@31190526, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.web.client.TestRestTemplateContextCustomizer@4e08711f, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@5e5d171f], contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]], attributes = map[[empty]]], class annotated with @DirtiesContext [false] with mode [null].
00:52:28.373 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved @ProfileValueSourceConfiguration [null] for test class [com.logicbig.example.MyHelloProcessorTest]
00:52:28.373 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [com.logicbig.example.MyHelloProcessorTest]
00:52:28.380 [main] DEBUG org.springframework.test.context.support.DependencyInjectionTestExecutionListener - Performing dependency injection for test context [[DefaultTestContext@d771cc9 testClass = MyHelloProcessorTest, testInstance = com.logicbig.example.MyHelloProcessorTest@3f91b517, testMethod = [null], testException = [null], mergedContextConfiguration = [MergedContextConfiguration@36b4091c testClass = MyHelloProcessorTest, locations = '{}', classes = '{class com.logicbig.example.AppMain}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[[ImportsContextCustomizer@4671115f key = [com.logicbig.example.MyTestConfig]], org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@217ed35e, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@31190526, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.web.client.TestRestTemplateContextCustomizer@4e08711f, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@5e5d171f], contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]], attributes = map[[empty]]]].
00:52:28.409 [main] DEBUG org.springframework.test.context.support.TestPropertySourceUtils - Adding inlined properties to environment: {spring.jmx.enabled=false, org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true, server.port=-1}

. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.2.5.RELEASE)

2020-04-18 00:52:28.728 INFO 17412 --- [ main] c.logicbig.example.MyHelloProcessorTest : No active profile set, falling back to default profiles: default
2020-04-18 00:52:29.457 INFO 17412 --- [ main] c.logicbig.example.MyHelloProcessorTest : Started MyHelloProcessorTest in 1.044 seconds (JVM running for 2.756)
Test hello: Joe
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.642 s - in com.logicbig.example.MyHelloProcessorTest
[INFO]
[INFO] Results:
[INFO]
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 9.951 s
[INFO] Finished at: 2020-04-18T00:52:30-05:00
[INFO] ------------------------------------------------------------------------

As seen above the bean implementation of HelloService is overridden by the one defined in MyTestConfig class.

Another test class without importing @TestConfiguration

package com.logicbig.example;

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class MyHelloProcessorTest2 {
  @Autowired
  private MyHelloProcessor myHelloProcessor;

  @Test
  public void testSayHi() {
      String message = myHelloProcessor.sayHi("Joe");
      System.out.println(message);
      Assert.assertEquals(message, "Hi there, Joe.");
  }
}
D:\spring-boot-test-configuration>mvn test -Dtest=MyHelloProcessorTest2.java
[INFO] Scanning for projects...
[INFO]
[INFO] --------< com.logicbig.example:spring-boot-test-configuration >---------
[INFO] Building spring-boot-test-configuration 1.0-SNAPSHOT
[INFO] --------------------------------[ jar ]---------------------------------
[INFO]
[INFO] --- maven-resources-plugin:3.1.0:resources (default-resources) @ spring-boot-test-configuration ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO]
[INFO] --- maven-compiler-plugin:3.8.1:compile (default-compile) @ spring-boot-test-configuration ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-resources-plugin:3.1.0:testResources (default-testResources) @ spring-boot-test-configuration ---
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO]
[INFO] --- maven-compiler-plugin:3.8.1:testCompile (default-testCompile) @ spring-boot-test-configuration ---
[INFO] Nothing to compile - all classes are up to date
[INFO]
[INFO] --- maven-surefire-plugin:2.22.2:test (default-test) @ spring-boot-test-configuration ---
[INFO]
[INFO] -------------------------------------------------------
[INFO] T E S T S
[INFO] -------------------------------------------------------
02:16:02.815 [main] DEBUG org.springframework.test.context.junit4.SpringJUnit4ClassRunner - SpringJUnit4ClassRunner constructor called with [class com.logicbig.example.MyHelloProcessorTest2]
02:16:02.820 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating CacheAwareContextLoaderDelegate from class [org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate]
02:16:02.833 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating BootstrapContext using constructor [public org.springframework.test.context.support.DefaultBootstrapContext(java.lang.Class,org.springframework.test.context.CacheAwareContextLoaderDelegate)]
02:16:02.889 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating TestContextBootstrapper for test class [com.logicbig.example.MyHelloProcessorTest2] from class [org.springframework.boot.test.context.SpringBootTestContextBootstrapper]
02:16:02.914 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Neither @ContextConfiguration nor @ContextHierarchy found for test class [com.logicbig.example.MyHelloProcessorTest2], using SpringBootContextLoader
02:16:02.918 [main] DEBUG org.springframework.test.context.support.AbstractContextLoader - Did not detect default resource location for test class [com.logicbig.example.MyHelloProcessorTest2]: class path resource [com/logicbig/example/MyHelloProcessorTest2-context.xml] does not exist
02:16:02.920 [main] DEBUG org.springframework.test.context.support.AbstractContextLoader - Did not detect default resource location for test class [com.logicbig.example.MyHelloProcessorTest2]: class path resource [com/logicbig/example/MyHelloProcessorTest2Context.groovy] does not exist
02:16:02.921 [main] INFO org.springframework.test.context.support.AbstractContextLoader - Could not detect default resource locations for test class [com.logicbig.example.MyHelloProcessorTest2]: no resource found for suffixes {-context.xml, Context.groovy}.
02:16:02.922 [main] INFO org.springframework.test.context.support.AnnotationConfigContextLoaderUtils - Could not detect default configuration classes for test class [com.logicbig.example.MyHelloProcessorTest2]: MyHelloProcessorTest2 does not declare any static, non-private, non-final, nested classes annotated with @Configuration.
02:16:02.967 [main] DEBUG org.springframework.test.context.support.ActiveProfilesUtils - Could not find an 'annotation declaring class' for annotation type [org.springframework.test.context.ActiveProfiles] and class [com.logicbig.example.MyHelloProcessorTest2]
02:16:03.064 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Found @SpringBootConfiguration com.logicbig.example.AppMain for test class com.logicbig.example.MyHelloProcessorTest2
02:16:03.193 [main] DEBUG org.springframework.boot.test.context.SpringBootTestContextBootstrapper - @TestExecutionListeners is not present for class [com.logicbig.example.MyHelloProcessorTest2]: using defaults.
02:16:03.193 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener, org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener, org.springframework.test.context.event.EventPublishingTestExecutionListener]
02:16:03.219 [main] DEBUG org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Skipping candidate TestExecutionListener [org.springframework.test.context.web.ServletTestExecutionListener] due to a missing dependency. Specify custom listener classes or make the default listener classes and their required dependencies available. Offending class: [javax/servlet/ServletContext]
02:16:03.223 [main] DEBUG org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Skipping candidate TestExecutionListener [org.springframework.test.context.transaction.TransactionalTestExecutionListener] due to a missing dependency. Specify custom listener classes or make the default listener classes and their required dependencies available. Offending class: [org/springframework/transaction/interceptor/TransactionAttributeSource]
02:16:03.226 [main] DEBUG org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Skipping candidate TestExecutionListener [org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener] due to a missing dependency. Specify custom listener classes or make the default listener classes and their required dependencies available. Offending class: [org/springframework/transaction/interceptor/TransactionAttribute]
02:16:03.229 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Using TestExecutionListeners: [org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener@36804139, org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener@20bd8be5, org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener@730d2164, org.springframework.test.context.support.DirtiesContextTestExecutionListener@24959ca4, org.springframework.test.context.event.EventPublishingTestExecutionListener@10289886, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener@5c86dbc5, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener@461ad730, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener@4ee203eb, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener@1a5a4e19, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener@7068e664]
02:16:03.242 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved @ProfileValueSourceConfiguration [null] for test class [com.logicbig.example.MyHelloProcessorTest2]
02:16:03.245 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [com.logicbig.example.MyHelloProcessorTest2]
02:16:03.297 [main] DEBUG org.springframework.test.context.junit4.SpringJUnit4ClassRunner - SpringJUnit4ClassRunner constructor called with [class com.logicbig.example.MyHelloProcessorTest2]
02:16:03.297 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating CacheAwareContextLoaderDelegate from class [org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate]
02:16:03.298 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating BootstrapContext using constructor [public org.springframework.test.context.support.DefaultBootstrapContext(java.lang.Class,org.springframework.test.context.CacheAwareContextLoaderDelegate)]
02:16:03.300 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating TestContextBootstrapper for test class [com.logicbig.example.MyHelloProcessorTest2] from class [org.springframework.boot.test.context.SpringBootTestContextBootstrapper]
02:16:03.308 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Neither @ContextConfiguration nor @ContextHierarchy found for test class [com.logicbig.example.MyHelloProcessorTest2], using SpringBootContextLoader
02:16:03.310 [main] DEBUG org.springframework.test.context.support.AbstractContextLoader - Did not detect default resource location for test class [com.logicbig.example.MyHelloProcessorTest2]: class path resource [com/logicbig/example/MyHelloProcessorTest2-context.xml] does not exist
02:16:03.322 [main] DEBUG org.springframework.test.context.support.AbstractContextLoader - Did not detect default resource location for test class [com.logicbig.example.MyHelloProcessorTest2]: class path resource [com/logicbig/example/MyHelloProcessorTest2Context.groovy] does not exist
02:16:03.323 [main] INFO org.springframework.test.context.support.AbstractContextLoader - Could not detect default resource locations for test class [com.logicbig.example.MyHelloProcessorTest2]: no resource found for suffixes {-context.xml, Context.groovy}.
02:16:03.326 [main] INFO org.springframework.test.context.support.AnnotationConfigContextLoaderUtils - Could not detect default configuration classes for test class [com.logicbig.example.MyHelloProcessorTest2]: MyHelloProcessorTest2 does not declare any static, non-private, non-final, nested classes annotated with @Configuration.
02:16:03.330 [main] DEBUG org.springframework.test.context.support.ActiveProfilesUtils - Could not find an 'annotation declaring class' for annotation type [org.springframework.test.context.ActiveProfiles] and class [com.logicbig.example.MyHelloProcessorTest2]
02:16:03.332 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Found @SpringBootConfiguration com.logicbig.example.AppMain for test class com.logicbig.example.MyHelloProcessorTest2
02:16:03.337 [main] DEBUG org.springframework.boot.test.context.SpringBootTestContextBootstrapper - @TestExecutionListeners is not present for class [com.logicbig.example.MyHelloProcessorTest2]: using defaults.
02:16:03.339 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener, org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener, org.springframework.test.context.event.EventPublishingTestExecutionListener]
02:16:03.345 [main] DEBUG org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Skipping candidate TestExecutionListener [org.springframework.test.context.web.ServletTestExecutionListener] due to a missing dependency. Specify custom listener classes or make the default listener classes and their required dependencies available. Offending class: [javax/servlet/ServletContext]
02:16:03.346 [main] DEBUG org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Skipping candidate TestExecutionListener [org.springframework.test.context.transaction.TransactionalTestExecutionListener] due to a missing dependency. Specify custom listener classes or make the default listener classes and their required dependencies available. Offending class: [org/springframework/transaction/interceptor/TransactionAttributeSource]
02:16:03.348 [main] DEBUG org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Skipping candidate TestExecutionListener [org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener] due to a missing dependency. Specify custom listener classes or make the default listener classes and their required dependencies available. Offending class: [org/springframework/transaction/interceptor/TransactionAttribute]
02:16:03.349 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Using TestExecutionListeners: [org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener@2663e964, org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener@48b67364, org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener@189cbd7c, org.springframework.test.context.support.DirtiesContextTestExecutionListener@7bf3a5d8, org.springframework.test.context.event.EventPublishingTestExecutionListener@42e25b0b, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener@39b43d60, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener@44be0077, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener@2205a05d, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener@72ef8d15, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener@6aa8e115]
02:16:03.349 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved @ProfileValueSourceConfiguration [null] for test class [com.logicbig.example.MyHelloProcessorTest2]
02:16:03.349 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [com.logicbig.example.MyHelloProcessorTest2]
02:16:03.424 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved @ProfileValueSourceConfiguration [null] for test class [com.logicbig.example.MyHelloProcessorTest2]
02:16:03.425 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [com.logicbig.example.MyHelloProcessorTest2]
[INFO] Running com.logicbig.example.MyHelloProcessorTest2
02:16:03.430 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved @ProfileValueSourceConfiguration [null] for test class [com.logicbig.example.MyHelloProcessorTest2]
02:16:03.430 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [com.logicbig.example.MyHelloProcessorTest2]
02:16:03.431 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved @ProfileValueSourceConfiguration [null] for test class [com.logicbig.example.MyHelloProcessorTest2]
02:16:03.431 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [com.logicbig.example.MyHelloProcessorTest2]
02:16:03.436 [main] DEBUG org.springframework.test.context.support.AbstractDirtiesContextTestExecutionListener - Before test class: context [DefaultTestContext@38604b81 testClass = MyHelloProcessorTest2, testInstance = [null], testMethod = [null], testException = [null], mergedContextConfiguration = [MergedContextConfiguration@1e44b638 testClass = MyHelloProcessorTest2, locations = '{}', classes = '{class com.logicbig.example.AppMain}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@3754a4bf, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@175c2241, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.web.client.TestRestTemplateContextCustomizer@815b41f, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@3857f613], contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]], attributes = map[[empty]]], class annotated with @DirtiesContext [false] with mode [null].
02:16:03.441 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved @ProfileValueSourceConfiguration [null] for test class [com.logicbig.example.MyHelloProcessorTest2]
02:16:03.442 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [com.logicbig.example.MyHelloProcessorTest2]
02:16:03.451 [main] DEBUG org.springframework.test.context.support.DependencyInjectionTestExecutionListener - Performing dependency injection for test context [[DefaultTestContext@38604b81 testClass = MyHelloProcessorTest2, testInstance = com.logicbig.example.MyHelloProcessorTest2@1efe439d, testMethod = [null], testException = [null], mergedContextConfiguration = [MergedContextConfiguration@1e44b638 testClass = MyHelloProcessorTest2, locations = '{}', classes = '{class com.logicbig.example.AppMain}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@3754a4bf, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@175c2241, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@0, org.springframework.boot.test.web.client.TestRestTemplateContextCustomizer@815b41f, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@0, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@3857f613], contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]], attributes = map[[empty]]]].
02:16:03.482 [main] DEBUG org.springframework.test.context.support.TestPropertySourceUtils - Adding inlined properties to environment: {spring.jmx.enabled=false, org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true, server.port=-1}

. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.2.5.RELEASE)

2020-04-18 02:16:03.771 INFO 12640 --- [ main] c.l.example.MyHelloProcessorTest2 : No active profile set, falling back to default profiles: default
2020-04-18 02:16:04.460 INFO 12640 --- [ main] c.l.example.MyHelloProcessorTest2 : Started MyHelloProcessorTest2 in 0.974 seconds (JVM running for 2.404)
Hi there, Joe.
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.549 s - in com.logicbig.example.MyHelloProcessorTest2
[INFO]
[INFO] Results:
[INFO]
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 7.254 s
[INFO] Finished at: 2020-04-18T02:16:05-05:00
[INFO] ------------------------------------------------------------------------

As seen above the bean implementation for HelloService is used from application instead of the one which is defined in MyTestConfig.

Example Project

Dependencies and Technologies Used:

  • Spring Boot 2.2.5.RELEASE
  • spring-boot-starter-test : Starter for testing Spring Boot applications with libraries including JUnit, Hamcrest and Mockito.
  • JDK 1.8
  • Maven 3.5.4

Spring Boot - @TestConfiguration Example Select All Download
  • spring-boot-test-configuration
    • src
      • main
        • java
          • com
            • logicbig
              • example
      • test
        • java
          • com
            • logicbig
              • example
                • MyTestConfig.java

    See Also