Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can a test 'dirty' a spring application context?

The spring framework documentation states:

In the unlikely case that a test may 'dirty' the application context, requiring reloading - for example, by changing a bean definition or the state of an application object - Spring's testing support provides mechanisms to cause the test fixture to reload the configurations and rebuild the application context before executing the next test.

Can someone elaborate this? I am just not getting it. Examples would be nice.

like image 367
JavaRocky Avatar asked Feb 26 '23 15:02

JavaRocky


1 Answers

Each JUnit test method is assumed to be isolated, that is does not have any side effects that could cause another test method to behave differently. This can be achieved by modifying the state of beans that are managed by spring.

For example, say you have a bean managed by spring of class MySpringBean which has a string property with a value of "string". The following test method testBeanString will have a different result depending if it is called before or after the method testModify.

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"/base-context.xml"})
public class SpringTests {

    @Autowired
    private MySpringBean bean;

    @Test public void testModify() {
        // dirties the state of a managed bean
        bean.setString("newSring");
    }

    @Test public void testBeanString() {
        assertEquals("string", bean.getString());
    }
}

use the @DirtiesContext annotation to indicate that the test method may change the state of spring managed beans.

like image 119
krock Avatar answered Mar 15 '23 06:03

krock