Use Session and Request Scope Beans in Tests with Spring

Sometimes it is useful haven the Web Scopes in Unit Tests. Usually Spring just show this very useful error in the Unit Test:

Caused by: java.lang.IllegalStateException: No Scope registered for scope 'session'
	at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:334)
	at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1120)
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1044)
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:942)
	at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:533)
	... 28 common frames omitted

You can easily have all needed web scopes in your unit test by adding the following annotation to your Tests: @WebAppConfiguration.

Now Web Scopes like:

@Bean(name = "foo") @Scope("session")
public String getString()

will work.

 

Paul Sterl has written 21 articles

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>