Projekt von de.halbekunst.juplo nach de.juplo verschoben und aufgeräumt
[percentcodec] / testingtools / src / main / java / de / juplo / testingtools / WebContextTestExecutionListener.java
1 package de.juplo.testingtools;
2
3 import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
4 import org.springframework.beans.factory.config.Scope;
5 import org.springframework.context.support.GenericApplicationContext;
6 import org.springframework.context.support.SimpleThreadScope;
7 import org.springframework.test.context.TestContext;
8 import org.springframework.test.context.support.AbstractTestExecutionListener;
9
10 /**
11  * Diese Klasse ermöglicht es, Beans mit dem Scope REQUEST in JUnit-Testfällen
12  * zu verwenden.
13  * <p>
14  * Source: http://stackoverflow.com/questions/2411343/request-scoped-beans-in-spring-testing
15  * <p>
16  * Anwendung:
17  * <code>
18  * @RunWith(SpringJUnit4ClassRunner.class)
19  * @ContextConfiguration(locations = "classpath:spring/TestScopedBeans-context.xml")
20  * @TestExecutionListeners({
21  *      WebContextTestExecutionListener.class,
22  *      DependencyInjectionTestExecutionListener.class,
23  *      DirtiesContextTestExecutionListener.class })
24  * public class TestScopedBeans {
25  * ...
26  * </code>
27  */
28 public class WebContextTestExecutionListener extends AbstractTestExecutionListener {
29     @Override
30     public void prepareTestInstance(TestContext testContext) throws Exception {
31
32         if (testContext.getApplicationContext() instanceof GenericApplicationContext) {
33             GenericApplicationContext context = (GenericApplicationContext) testContext.getApplicationContext();
34             ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
35             Scope requestScope = new SimpleThreadScope();
36             beanFactory.registerScope("request", requestScope);
37             Scope sessionScope = new SimpleThreadScope();
38             beanFactory.registerScope("session", sessionScope);
39         }
40     }
41 }