JUnit Spring session and request scope beans.

While writing units test using SpringJUnit4ClassRunner, the issue that comes up very often is what to do for beans that are request and session scope. These beans are generally injected as dependency using Autowired annotation within another bean. Lets see the example

 class Order{

The above Order bean is session scope and suppose it’s injected within Person bean below

public class Person {
Order order;

Now in the above code, you are bound to get
java.lang.IllegalStateException: No Scope registered for scope ‘session’

Though there are multiple solutions for this available on the Internet, some suggest mocking while other suggest to use single scoped Order bean in the test configuration file(bad practice!).

The thing which worked for me was the below XML snippet in my Test configuration file

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

Since Junits are executed in a single thread thus a simple thread-bound session scope is available which maintains it’s states between the tests.


About Tarun Sapra
Agile Java developer @ Xebia India

5 Responses to JUnit Spring session and request scope beans.

  1. Mike Hancock says:

    Thanks! I was having this problem, but only on certain JUnit tests (not all). Had spent a lot of time comparing “good” tests to “bad” and googling the error message (a whole of reading, too) Copied your snippet into my test configuration file and the problem was cured.

  2. Pingback: JavaPins

  3. Anonymous says:

    Great!!!!! Many thanks to you for this wonderful post. Worked for me.

  4. Thanks! I had this problem when testing with cucumber. Cucumber does not allow (or I could not figure out) other means of accessing beans in a sessin/request scope, but your solution worked fine.

  5. Pingback: Making a Spring bean session scoped – Thomas Uhrig

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: