Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overwrite Java based Spring Context Configuration for Tests

Is there a possibility to replace a single bean or value from a Spring configuration for one or more integration tests?

In my case, I have the configuration

@Configuration
@EnableAutoConfiguration
@ComponentScan(basePackages = {"foo.bar"})
public class MyIntegrationTestConfig {
    // everything done by component scan
}

Which is used for my integration test

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = MyIntegrationTestConfig.class, loader = SpringApplicationContextLoader.class)
public class MyIntegrationTest {
    // do the tests
}

Now I want to have a second set of integration tests where I replace one bean by a different one.

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = MyIntegrationTestConfig.class, loader = SpringApplicationContextLoader.class)
public class MySpecialIntegrationTest {
    // influence the context configuration such that a bean different from the primary is loaded

    // do the tests using the 'overwritten' bean
}

What is the most simple way to achieve this?

like image 937
spike Avatar asked Jan 20 '14 15:01

spike


People also ask

How do I override a configuration class in spring boot?

To make a configuration in Spring Boot, you need to create a class and annotate it with @Configuration . Usually, in the configuration class, you can define a beans object. But if you want to override built-in configuration, you need to create a new class that extends the built-in class.

How can you access the application context in a Spring integration test?

By default the ApplicationContext is loaded using the GenericXmlContextLoader which loads a context from XML Spring configuration files. You can then access beans from the ApplicationContext by annotating fields in your test class with @Autowired , @Resource , or @Inject .

What is Spring context configuration?

@ContextConfiguration defines class-level metadata that is used to determine how to load and configure an ApplicationContext for integration tests.


1 Answers

The Spring test framework is able to understand extension over configuration. It means that you only need to extend MySpecialIntegrationTest from MyIntegrationTest:

@ContextConfiguration(classes = MySpecialIntegrationTestConfig.class, loader = SpringApplicationContextLoader.class)
public class MySpecialIntegrationTest extends MyIntegrationTest {

  @Configuration
  public static class MySpecialIntegrationTestConfig {
    @Bean
    public MyBean theBean() {}
  }

}

and create the necessary Java Config class and provide it to @ContextConfiguration. Spring will load the base one and extend it with the one that you specialize in your extended test case.

Refer to the official documentation for further discussion.

like image 109
nobeh Avatar answered Oct 14 '22 05:10

nobeh