I came across this simpler approach, thought I might as well post here in case others need it.
<bean class="org.springframework.beans.factory.config.CustomScopeConfigurer">
<property name="scopes">
<map>
<entry key="session">
<bean class="org.springframework.context.support.SimpleThreadScope"/>
</entry>
</map>
</property>
</bean>
With this approach, you don’t have to mock any request/session objects.
Source: http://tarunsapra.wordpress.com/2011/06/28/junit-spring-session-and-request-scope-beans/
Update for spring 5.x (works in spring 5.3.22, in a JUnit5 test, annotated by @ExtendWith(SpringExtension.class) ): The same bean definitions by annotations. Place this code somewhere in a spring configuration class:
/**
* Used in CustomScopeConfigurer bean below
*
* @return
*/
@Bean
public static SimpleThreadScope simpleThreadScope()
{
return new SimpleThreadScope();
}
/**
* This bean is needed in order to mimic spring's SessionScope
*
* @param aSimpleThreadScope
* @return
*/
@Bean
public static CustomScopeConfigurer customScopeConfigurer(SimpleThreadScope aSimpleThreadScope)
{
CustomScopeConfigurer result = new CustomScopeConfigurer();
result.addScope( "session", aSimpleThreadScope );
return result;
}