1

我正在通过测试驱动开发 (TDD)将旧的Struts 1应用程序与Spring 3集成。出于这个原因,我的集成测试非常重要。我正在尝试使用"Struts Test Case"实现动作的集成测试。动作(HomeAction)使用单例服务会话 bean (Basket)自动装配。但是当我运行测试时,我收到以下错误:

创建名为“scopedTarget.basket”的 bean 时出错:范围“会话”对于当前线程不活动;如果您打算从单例中引用它,请考虑为该 bean 定义一个作用域代理;嵌套异常是 java.lang.IllegalStateException:未找到线程绑定请求:您是指实际 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>

Spring 上下文: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

正如我上面所说,我按照这个链接解决了它并将这个bean添加到spring上下文xml(root-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>

但我在执行环境中收到以下警告:

'SimpleThreadScope 不支持销毁回调。考虑在 Web 环境中使用 RequestScope。

为了只允许这个消息用于测试,我通过 maven pom.xml 为测试环境设置了一个不同的 spring 上下文 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 回答
0

很久以前,我写了一篇关于使用 Maven 对 struts 应用程序进行单元测试的博客。我不想在这里复制整个故事,而是参考带有模拟对象和 Maven 的 JUnit 测试 Struts 应用程序。我希望它有所帮助。

于 2013-10-26T18:41:21.067 回答