Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reload Spring application context after every test

Tags:

java

junit

spring

I have a test Class which contains 2 test:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:applicationContextTest.xml" })
@Transactional
@TransactionConfiguration(defaultRollback = true)

public class MyITest extends implements BeanFactoryAware {

    private BeanFactory beanFactory;

    @Test
    public void test1() throws Exception {}

    @Test
    public void test2() throws Exception {}        
}

When I run tests individually I get no errors, but when I run all tests together there is a failure. This failure is due to some tests modifying the application context:

  b = beanFactory.getBean("logDataSource", BasicDataSource.class);
  b.set ...

Is there an option to run this test separately? I just want when test1 start it read all necessary things then run test and then close all necessary things. And then start test2.

like image 874
hudi Avatar asked Nov 08 '12 11:11

hudi


People also ask

How do I refresh application context in Spring boot?

For a Spring Boot Actuator application, some additional management endpoints are available. You can use: POST to /actuator/env to update the Environment and rebind @ConfigurationProperties and log levels. /actuator/refresh to re-load the boot strap context and refresh the @RefreshScope beans.

How application context is loaded in Spring?

ApplicationContext is a corner stone of a Spring Boot application. It represents the Spring IoC container and is responsible for instantiating, configuring, and assembling the beans. The container gets its instructions on what objects to instantiate, configure, and assemble by reading configuration metadata.

Can Spring have multiple application contexts?

We can have multiple application contexts that share a parent-child relationship. A context hierarchy allows multiple child contexts to share beans which reside in the parent context. Each child context can override configuration inherited from the parent context.

What is DirtiesContext?

@DirtiesContext is a Spring testing annotation. It indicates the associated test or class modifies the ApplicationContext. It tells the testing framework to close and recreate the context for later tests. We can annotate a test method or an entire class.


Video Answer


1 Answers

You can use the @DirtiesContext annotation on the test class that modifies the application context.

Java Doc

Spring documentation

By default, this will mark the application context as dirty after the entire test class is run. If you would like to mark the context as dirty after a single test method, then you can either annotate the test method instead or set the classMode property to AFTER_EACH_TEST_METHOD at your class level annotation.

@DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD) 
like image 196
groodt Avatar answered Oct 01 '22 12:10

groodt