Fix Issue with Spring Web Scopes in Tests

January 6, 2012

Fix Issue with Spring Web Scopes in Tests

Today I’m hit with the issue that Spring whines about the exception, “No Scope registered for scope ‘request’,” when I try to run tests with request scoped bean. Fortunately the fix is fairly easy.

Update Dec. 22, 2012: Spring 3.2 has made it possible to use WebApplicationContext as well as web-based scopes available in unit tests. The fix documented here is no longer necessary if you are on Spring 3.2.

Solution

Discussions here suggest that the missing request and session scopes can be faked by using SimpleThreadScope. So, the solution is simply to register the following scopes in xml config:

<bean class="org.springframework.beans.factory.config.CustomScopeConfigurer">
    <property name="scopes">
        <map>
            <entry key="request">
                <bean class="org.springframework.context.support.SimpleThreadScope" />
            </entry>
            <entry key="session">
                <bean class="org.springframework.context.support.SimpleThreadScope" />
            </entry>
        </map>
    </property>
</bean>

Note that I have a different xml config file for testing, and obviously these lines cannot be inserted into a config file that would be loaded at runtime. Otherwise, things would be messed up.

Another note is that this method works with @Autowired dependencies. The method posted on Stack Overflow does not.

Comments

comments powered by Disqus