To load an ApplicationContext
for your tests by using component classes (see
Java-based container configuration), you can annotate your test
class with @ContextConfiguration
and configure the classes
attribute with an array
that contains references to component classes. The following example shows how to do so:
- Java
-
@ExtendWith(SpringExtension.class) // ApplicationContext will be loaded from AppConfig and TestConfig @ContextConfiguration(classes = {AppConfig.class, TestConfig.class}) // (1) class MyTest { // class body... }
-
Specifying component classes.
-
- Kotlin
-
@ExtendWith(SpringExtension::class) // ApplicationContext will be loaded from AppConfig and TestConfig @ContextConfiguration(classes = [AppConfig::class, TestConfig::class]) // (1) class MyTest { // class body... }
-
Specifying component classes.
-
Tip
|
Component Classes
The term “component class” can refer to any of the following:
See the javadoc of
{spring-framework-api}/context/annotation/Configuration.html[ |
If you omit the classes
attribute from the @ContextConfiguration
annotation, the
TestContext framework tries to detect the presence of default configuration classes.
Specifically, AnnotationConfigContextLoader
and AnnotationConfigWebContextLoader
detect all static
nested classes of the test class that meet the requirements for
configuration class implementations, as specified in the
{spring-framework-api}/context/annotation/Configuration.html[@Configuration
] javadoc.
Note that the name of the configuration class is arbitrary. In addition, a test class can
contain more than one static
nested configuration class if desired. In the following
example, the OrderServiceTest
class declares a static
nested configuration class
named Config
that is automatically used to load the ApplicationContext
for the test
class:
- Java
-
@SpringJUnitConfig (1) // ApplicationContext will be loaded from the static nested Config class class OrderServiceTest { @Configuration static class Config { // this bean will be injected into the OrderServiceTest class @Bean OrderService orderService() { OrderService orderService = new OrderServiceImpl(); // set properties, etc. return orderService; } } @Autowired OrderService orderService; @Test void testOrderService() { // test the orderService } }
-
Loading configuration information from the nested
Config
class.
-
- Kotlin
-
@SpringJUnitConfig (1) // ApplicationContext will be loaded from the nested Config class class OrderServiceTest { @Autowired lateinit var orderService: OrderService @Configuration class Config { // this bean will be injected into the OrderServiceTest class @Bean fun orderService(): OrderService { // set properties, etc. return OrderServiceImpl() } } @Test fun testOrderService() { // test the orderService } }
-
Loading configuration information from the nested
Config
class.
-