Cri*_*cho 2 java junit struts2
经过几个小时的网上冲浪寻找这个问题的答案,最后我决定在这里发布这个问题。
我正在使用 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>
Run Code Online (Sandbox Code Playgroud)
产品卡.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>
Run Code Online (Sandbox Code Playgroud)
我有一个扩展 StrutsTestCase 的测试类,以及“/productClasification/edit”操作的测试方法。当进行以下调用时:
ActionProxy proxy = getActionProxy("/productClasification/edit.action");
ProductClasificationAction clasificationAction =
(ProductClasificationAction) proxy.getAction();
Run Code Online (Sandbox Code Playgroud)
由于无法找到该操作,因此引发异常。默认情况下,StrutsTestCase 使用 struts.xml,但是其他 struts 配置 xml 文件呢?
提前致谢。
小智 5
所以我花了过去 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();
}
Run Code Online (Sandbox Code Playgroud)
如果您的项目中有很多操作,那么可能值得您花时间创建一个扩展 StrutsTestCase 的基本测试类,并且让所有操作测试都扩展它。