采用Struts中的Mock方式模拟action和actionForm进行测试
基础类:STCRequestProcessor
作用:Ioc 将模拟的Action,ActionForm注入到struts-config.xml中的相应的action位置
1. package test.sample.service.util;
2. import java.io.IOException;
3. import java.util.HashMap;
4. import javax.servlet.http.HttpServletRequest;
5. import javax.servlet.http.HttpServletResponse;
6. import javax.servlet.http.HttpSession;
7.
8. import org.apache.struts.action.Action;
9. import org.apache.struts.action.ActionForm;
10. import org.apache.struts.action.ActionMapping;
11. import org.apache.struts.action.RequestProcessor;
12. import org.apache.struts.util.RequestUtils;
13.
14. /** *//**
15. * @author administrator
16. *
17. * To change this generated comment edit the template variable "typecomment":
18. * Window>Preferences>Java>Templates.
19. * To enable and disable the creation of type comments go to
20. * Window>Preferences>Java>Code Generation.
21. */
22. public class STCRequestProcessor extends RequestProcessor {
23.
24. private static HashMap mockActionFormMap = new HashMap();
25. private static HashMap mockActionMap = new HashMap();
26.
27. public static void addMockAction(String actionStr, String className)
28. {
29. mockActionMap.put(actionStr, className);
30. }
31. public static void addMockActionForm(String actionFormStr,String className)
32. {
33. mockActionFormMap.put(actionFormStr, className);
34. }
35. /** *//**
36. * We will insert Mock ActionForm for testing through this method
37. */
38. protected ActionForm processActionForm(
39. HttpServletRequest request,
40. HttpServletResponse response,
41. ActionMapping mapping) {
42.
43.
44. // Create (if necessary a form bean to use
45. String formBeanName = mapping.getName();
46. String mockBeanClassName = (String) mockActionFormMap.get(formBeanName);
47. if (mockBeanClassName == null)
48. return super.processActionForm(request, response, mapping);
49.
50. ActionForm instance = null;
51. try {
52. Class formClass = Class.forName(mockBeanClassName );
53. instance = (ActionForm) formClass.newInstance();
54. } catch (ClassNotFoundException e) {
55. e.printStackTrace();
56. } catch (InstantiationException e) {
57. e.printStackTrace();
58. } catch (IllegalAccessException e) {
59. e.printStackTrace();
60. }
61.
62. instance.setServlet(servlet);
63. if (instance == null) {
64. return (null);
65. }
66.
67. if (log.isDebugEnabled()) {
68. log.debug(
69. " Storing ActionForm bean instance in scope '"
70. + mapping.getScope()
71. + "' under attribute key '"
72. + mapping.getAttribute()
73. + "'");
74. }
75. if ("request".equals(mapping.getScope())) {
76. request.setAttribute(mapping.getAttribute(), instance);
77. } else {
78. HttpSession session = request.getSession();
79. session.setAttribute(mapping.getAttribute(), instance);
80. }
81. return (instance);
82.
83. }
84.
85. /** *//**
86. * We will insert Mock Action Class through this method
87. */
88. protected Action processActionCreate(
89. HttpServletRequest request,
90. HttpServletResponse response,
91. ActionMapping mapping)
92. throws IOException {
93. String orignalClassName = mapping.getType();
94. String mockClassName = (String)mockActionMap.get(orignalClassName);
95. if( mockClassName == null )
96. return super.processActionCreate(request,response,mapping);
97. String className = mockClassName;
98. if (log.isDebugEnabled()) {
99. log.debug(" Looking for Action instance for class " + className);
100. }
101.
102. Action instance = null;
103. synchronized (actions) {
104.
105. // Return any existing Action instance of this class
106. instance = (Action) actions.get(className);
107. if (instance != null) {
108. if (log.isTraceEnabled()) {
109. log.trace(" Returning existing Action instance");
110. }
111. return (instance);
112. }
113.
114. // Create and return a new Action instance
115. if (log.isTraceEnabled()) {
116. log.trace(" Creating new Action instance");
117. }
118.
119. try {
120. instance = (Action) RequestUtils.applicationInstance(className);
121. } catch (Exception e) {
122. log.error(
123. getInternal().getMessage("actionCreate", mapping.getPath()),
124. e);
125.
126. response.sendError(
127. HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
128. getInternal().getMessage(
129. "actionCreate",
130. mapping.getPath()));
131.
132. return (null);
133. }
134.
135. instance.setServlet(this.servlet);
136. actions.put(className, instance);
137. }
138.
139. return (instance);
140. }
141.
142. }
Test类:
setUp()方法:
super.setUp();//调用mockStrutsTestCase中的setUp方法
File web = new File("E:/project/portal/WebContent");
this.setContextDirectory(web);//定位工程包的位置
setConfigFile("/WEB-INF/web.xml");//定位工程中的web.xml位置
setConfigFile("/WEB-INF/struts-config.xml");//定位工程中struts-config.xml位置
STCRequestProcessor.addMockActionForm("ser_wordForm", "test.sample.service.form.MockWordForm");//注入模拟的form
STCRequestProcessor.addMockAction("com.huawei.service.action.WordAction","test.sample.service.action.MockWordAction");//
注入模拟的action
setRequestPathInfo("/service/word");//定义struts-config.xml中的path名称
1. package test.sample.service.action;
2.
3.
4. import java.io.File;
5.
6. import servletunit.struts.MockStrutsTestCase;
7. import test.sample.service.util.STCRequestProcessor;
8. /** *//**
9. *
10. - setContextDirectory,设置web应用的根
11. - setRequestPathInfo,设置request的请求
12. - addRequestParameter,将参数和对应的值加入request中
13. - actionPerform,执行这个请求
14. - verifyForward,验证forward的名字是否正确
15. - verifyForwardPath,验证forward的path是否正确
16. - verifyNoActionErrors,验证在action执行过程中没有ActionError产生
17. - verifyActionErrors,验证在action执行过程中产生的ActionError集合的内容
18. * @author donganlei
19. *
20. */
21. public class MockWordActionTest extends MockStrutsTestCase {
22.
23. public void testInvalidPageflag1()throws Exception{
24. addRequestParameter("reqCode","getWordList");
25. addRequestParameter("pageflag","userquery");
26. actionPerform();
27. verifyNoActionErrors();
28. verifyForward("querylist");
29. }
30.
31. public void testInvalidPageflag2()throws Exception{
32. addRequestParameter("reqCode","getWordList");
33. addRequestParameter("pageflag","seatquery");
34. actionPerform();
35. verifyNoActionErrors();
36. verifyForward("querylist");
37. }
38.
39. public void testInvalidInitUpdate()throws Exception{
40. addRequestParameter("reqCode","initUpdate");
41. actionPerform();
42. verifyNoActionErrors();
43. verifyForward("update");
44. }
45. public void testinitUpdate()throws Exception{
46. addRequestParameter("reqCode","initUpdate");
47. addRequestParameter("wordid","3");
48. addRequestParameter("roomid","3");
49. actionPerform();
50. verifyNoActionErrors();
51. verifyForward("update");
52. }
53. protected void setUp() throws Exception {
54. super.setUp();
55. File web = new File("E:/project/portal/WebContent");
56. this.setContextDirectory(web);
57. setConfigFile("/WEB-INF/web.xml");
58. setConfigFile("/WEB-INF/struts-config.xml");
59. STCRequestProcessor.addMockActionForm("ser_wordForm", "test.sample.service.form.MockWordForm");
60. STCRequestProcessor.addMockAction("com.huawei.service.action.WordAction","test.sample.service.action.MockWordAction");
61. setRequestPathInfo("/service/word");
62. }
63. public static void main(String args[]){
64. junit.textui.TestRunner.run(MockWordActionTest.class);
65. }
66. }
Struts-congfig.xml中的processorClass
<controller>
<set-property property="processorClass" value="test.sample.service.util.STCRequestProcessor"/>
</controller>