【问题标题】:Struts 2 JUnit plugin and multiple struts configuration filesStruts 2 JUnit 插件和多个 struts 配置文件
【发布时间】:2011-03-08 13:36:35
【问题描述】:

在网上冲浪了几个小时寻找这个问题的答案,最后我决定在这里发布这个问题。

我正在使用 struts 2 junit 插件来测试 struts 2 应用程序的一些操作。主要的 struts 配置文件(struts.xml)是这样的:

<struts>
    <package name="default" extends="struts-default">

    </package>

    <include file="/com/jmc/textil/productcard/action/productcard.xml"/>
    <!--More includes...-->

</struts>

productcard.xml 文件:

<struts>
        <!--Some other packages...-->

        <package name="productClasification" namespace="/productClasification" extends="default">
        <!--More actions...-->
            <action name="edit" method="edit" class="com.jmc.textil.productcard.action.ProductClasificationAction">
                <result>/main/jsp/json_struts2.jsp</result>
            </action>
        </package>

    </struts>

我有一个扩展 StrutsTestCase 的测试类,以及一个用于“/productClasification/edit”操作的测试方法。当进行以下调用时:

 ActionProxy proxy = getActionProxy("/productClasification/edit.action");
 ProductClasificationAction clasificationAction = 
                        (ProductClasificationAction) proxy.getAction();

由于无法定位操作而引发异常。默认情况下,StrutsTestCase 使用 struts.xml,但其他 struts 配置 xml 文件呢?

提前致谢。

【问题讨论】:

  • 我可能会稍后再回来重温,但让我为未来的访问者提供一个大纲。 web.xml 中 FilterDispatcher 的配置 init 参数告诉 web 应用程序要查找哪些 .xml 文件。假设使用 spring-mock api,您将创建一个 MockFilterConfig 选项。您为此 FilterConfig 对象设置初始化参数(config 是带有您的 xml 文件名称的参数),然后使用此 FilterConfig 初始化一个 FilterDispatcher。可能更进一步,但这听起来很接近。

标签: java junit struts2


【解决方案1】:

所以我花了过去 5 个小时来研究这个问题,我终于找到了解决方案。基本上,您需要覆盖 StrutsTestCase setUp 方法,并为您要添加的每个配置文件添加一个新的 StrutsXmlConfigurationProvider。请注意,配置提供程序足够智能,可以遍历包含语句,因此如果您的配置“树”只有一个根,您只需添加根即可。

示例实现:

@Override
public void setUp() throws Exception {
    super.setUp();
    List<ContainerProvider> providers = super.configurationManager.getContainerProviders();
    //make one of these for each config file you want to add
    StrutsXmlConfigurationProvider newConfig = new StrutsXmlConfigurationProvider("src/main/webapp/WEB-INF/classes/struts.xml", true, super.servletContext);
    providers.add(newConfig);
    super.configurationManager.reload();
}

如果您的项目中有很多动作,那么可能值得您花时间创建一个扩展 StrutsTestCase 的基础测试类,并让您的所有动作测试都扩展它。

【讨论】:

  • 非常感谢您跟进此事!很有帮助。
猜你喜欢
  • 2011-03-24
  • 1970-01-01
  • 1970-01-01
  • 2013-09-30
  • 2012-06-22
  • 1970-01-01
  • 1970-01-01
  • 2014-10-17
  • 1970-01-01
相关资源
最近更新 更多