问题描述:

My service needs to get object from session like this:

 @Service("UsageService")

@Scope(value="session")

public class UsageServiceImpl implements UsageService

{

@Override

public void doAnalysis()

{

// get data from session

ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();

HttpSession session = attr.getRequest().getSession();

......

}

}

Test code like this

@ContextConfiguration(locations = { "test-context.xml" })

@Transactional

public class UsageServiceImplTest extends AbstractTestNGSpringContextTests

{

@Autowired

private UsageService service;

@Test

public void testAnalysis()

{

service.doAnalysis(null);

}

}

And I have followed http://tarunsapra.wordpress.com/2011/06/28/junit-spring-session-and-request-scope-beans/'s suggestion add this to test-context.xml

 <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>

When I run text I got this error:

java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.

As error messages says:I am refering request attributes outside of an actual web request due to I launch service by testng not a http request,how can I make service with session read-write testable?

网友答案:

You can use mockito in your unit test to mock the RequestAttributes object to return what you want, and then call RequestContextHolder.setRequestAttributes(RequestAttributes) with your mock/stub before you start your test.

相关阅读:
Top