0

私のサービスは、次のようにセッションからオブジェクトを取得する必要があります。

  @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();
             ......
    }
  }

このようなテストコード

@ContextConfiguration(locations = { "test-context.xml" })
@Transactional
public class UsageServiceImplTest extends AbstractTestNGSpringContextTests
{
        @Autowired
        private UsageService service;

        @Test
        public void testAnalysis()
        {
       service.doAnalysis(null);
        }
}

そして、私はhttp://tarunsapra.wordpress.com/2011/06/28/junit-spring-session-and-request-scope-beans/の提案に従い、これを 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>

テキストを実行すると、次のエラーが発生しました。

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.

エラー メッセージが示すように: http 要求ではなく testng によってサービスを起動するため、実際の Web 要求の外部で要求属性を参照しています。

4

1 に答える 1

0

単体テストで mockito を使用して RequestAttributes オブジェクトをモックし、必要なものを返し、テストを開始する前にモック/スタブで RequestContextHolder.setRequestAttributes(RequestAttributes) を呼び出すことができます。

于 2012-12-20T06:11:01.677 に答える