1

テスト駆動開発 (TDD) を使用して、古いStruts 1アプリケーションをSpring 3と統合しています。そのため、私の統合テストは非常に重要です。「Struts Test Case」でアクションの統合テストを実装しようとしています。アクション(HomeAction) はシングルトンサービスセッション Bean (Basket)で自動配線されます。しかし、テストを実行すると、次のエラーが発生します。

「scopedTarget.basket」という名前の Bean の作成中にエラーが発生しました: スコープ「セッション」は現在のスレッドに対してアクティブではありません。シングルトンから参照する場合は、この Bean のスコープ付きプロキシを定義することを検討してください。ネストされた例外は java.lang.IllegalStateException: No thread-bound request found: 実際の Web 要求の外部で要求属性を参照していますか、または元の受信スレッドの外部で要求を処理していますか? 実際に Web リクエスト内で操作していてもこのメッセージが表示される場合、コードは DispatcherServlet/DispatcherPortlet の外部で実行されている可能性があります。この場合、RequestContextListener または RequestContextFilter を使用して現在のリクエストを公開します。

サービスは注入されますが、セッション Bean は注入されません。アプリケーションを実行しようとすると、正常に動作します。

誰かがそれを解決する方法を知っていますか? Maven の構成の問題かどうかはわかりませんが、テストでは、アプリケーションを実行したときのように Web コンテキストが読み込まれていないようです。前もって感謝します。

これはコードです:

Web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

    <listener>
        <listener-class>
            org.springframework.web.context.request.RequestContextListener
        </listener-class>
    </listener>

    <!-- Processes application requests -->
    <servlet>
        <servlet-name>action</servlet-name>
        <servlet-class>
            org.apache.struts.action.ActionServlet
        </servlet-class>
        <init-param>
            <param-name>config</param-name>
            <param-value>
             /WEB-INF/struts-config.xml
            </param-value>
        </init-param>
        <init-param>
            <param-name>autowire</param-name>
            <param-value>byName</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
           <servlet-name>action</servlet-name>
           <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>

struts-config.xml

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE struts-config PUBLIC
          "-//Apache Software Foundation//DTD Struts Configuration 1.3//EN"
          "http://struts.apache.org/dtds/struts-config_1_3.dtd">


<struts-config>

    <!-- ========== Definiciones de Form Bean =================== -->
    <form-beans>
        <form-bean name="homeForm" type="org.examples.appname.web.action.HomeForm" />
    </form-beans>


    <!-- ==========Forward's Globales ============================== -->
    <global-forwards>
        <forward name="error" path="/WEB-INF/views//error.jsp" />
    </global-forwards>


    <!-- ========== Mapeo de Acciones ============================== -->
    <action-mappings>
        <action path="/" type="org.apache.struts.actions.ForwardAction" parameter="/home"/>
        <action path="/home" type="org.examples.appname.web.action.HomeAction" name="homeForm" scope="request">
            <forward name="success" path="/WEB-INF/views/home.jsp" />
        </action>
    </action-mappings>


    <!-- ========== Controller Configuration ======================== -->
    <controller> 
        <!-- Autowaring injection of actions: You don't need to declare them on action-servlet.xml -->
        <set-property property="processorClass" value="org.springframework.web.struts.AutowiringRequestProcessor" />
    </controller>


    <!-- ========== Message Resources Definitions ==================== -->
    <message-resources parameter="org.example.appname.ApplicationResources" />


    <!-- ========== Plugins configuration ==================== -->
    <plug-in className="org.springframework.web.struts.ContextLoaderPlugIn">
        <set-property property="contextConfigLocation" value="/WEB-INF/action-servlet.xml, /WEB-INF/root-context.xml"/>
    </plug-in>

</struts-config>

アクションは自動配線されるため、action-servlet.xml は空です。

<!-- Action Context: defines all web actions -->
<beans></beans>

春のコンテキスト: root-context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/beans/spring-beans.xsd
         http://www.springframework.org/schema/context
         http://www.springframework.org/schema/context/spring-context.xsd
         http://www.springframework.org/schema/aop 
         http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">

    <context:annotation-config/>
    <context:component-scan base-package="org.examples.appname" scoped-proxy="targetClass"/>


    <bean name="MenuService" class="org.examples.appname.core.service.MenuServiceImpl" scope="singleton"/>

</beans>

HomeAction.java

@Component
public class HomeAction extends LookupDispatchAction {

    @Autowired
    private Basket basket;

    private MenuService menuService;

    public void setMenuService(MenuService menuService) {
        this.menuService = menuService;
        System.out.println(this.toString() + " - " + this.menuService.toString());
    }



    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        ActionErrors errors = new ActionErrors();

        HttpSession session = request.getSession();

        System.out.println("request " + request.hashCode());
        System.out.println("Session " + session.getId() + " - " + new Date(session.getCreationTime()));
        System.out.println("Basket " + basket.getState());

        //store an object on the request
        request.setAttribute("MenuItems", menuService.getMenuItems());

        // Forward control to the specified success URI
        return mapping.findForward("success");

    }


    @Override
    protected Map getKeyMethodMap() {
        // TODO Auto-generated method stub
        return null;
    }
}

バスケット.java

@Component
@Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class Basket{

    private final String state;

    public Basket() {

        this.state = UUID.randomUUID().toString();

    }

    public String getState() {
        return state;
    }
}

HomeIntegrationTest.java

public class HomeIntegrationTest extends MockStrutsTestCase{

    private static final String FORWARDED_URL = "/home";
    private static final String VIEW = "/WEB-INF/views/home.jsp";


    @Before
    public void setUp() throws Exception {
        super.setUp();
    }


    @Test
    public void testIndexUrlforwardsCorrectly() throws Exception {
        setRequestPathInfo("/");
        actionPerform();
        verifyForwardPath(FORWARDED_URL);
        verifyNoActionErrors();
    }

    @Test
    public void testHomeUrlforwardsCorrectly() throws Exception {
        setRequestPathInfo("/home");
        actionPerform();
        verifyForwardPath(VIEW);
        assertEquals("Menu items", getRequest().getAttribute("MenuItems"));
        verifyNoActionErrors();
    }

}

Maven pom.xml

<testResources>
  <testResource>
    <directory>src/test/java</directory>
    <includes>
      <include>*.*</include>
    </includes>
  </testResource>
  <testResource>
    <directory>src/main/webapp/WEB-INF</directory>
    <targetPath>/WEB-INF</targetPath> -->
    <includes>
      <include>*.xml</include>
    </includes>
  </testResource>
</testResources>
4

2 に答える 2

0

上で述べたように、このリンクをたどって解決し、Spring コンテキスト xml (root-context.xml) にこの Bean を追加しました。

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

しかし、実行環境に次の警告が表示されました。

'SimpleThreadScope は破棄コールバックをサポートしていません。Web 環境で RequestScope を使用することを検討してください。

このメッセージをテスト用にのみ許可するために、maven pom.xml を使用して別のスプリング コンテキスト xml (root-context.xml) をテスト環境に設定します。

<build>
        <testResources>
            <testResource>
                <directory>src/main/webapp/WEB-INF</directory>
                <targetPath>/WEB-INF</targetPath>
                <includes>
                    <include>*.xml</include>
                </includes>
                <excludes>
                    <exclude>root-context.xml</exclude>
                </excludes>
            </testResource>
            <testResource>
                <directory>src/test/webapp/WEB-INF</directory>
                <targetPath>/WEB-INF</targetPath>
                <includes>
                    <include>*.xml</include>
                </includes>
            </testResource>
        </testResources>
    </build>
于 2013-11-17T19:56:13.880 に答える