基于StrutsTestCase的单元测试(Action测试方法)

采用Struts中的Mock方式模拟action和actionForm进行测试

基础类:STCRequestProcessor

作用:Ioc将模拟的Action,ActionForm注入到struts-config.xml中的相应的action位置

package test.sample.service.util;
import java.io.IOException;
import java.util.HashMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.RequestProcessor;
import org.apache.struts.util.RequestUtils;

/** *//**
 * @author administrator
 *
 * To change this generated comment edit the template variable "typecomment":
 * Window>Preferences>Java>Templates.
 * To enable and disable the creation of type comments go to
 * Window>Preferences>Java>Code Generation.
 */
public class STCRequestProcessor extends RequestProcessor {

    private static HashMap mockActionFormMap = new HashMap();
    private static HashMap mockActionMap = new HashMap();

    public static void addMockAction(String actionStr, String className) 
    {
        mockActionMap.put(actionStr, className);
    }
    public static void addMockActionForm(String actionFormStr,String className)
    {    
        mockActionFormMap.put(actionFormStr, className);
    }
    /** *//**
     * We will insert Mock ActionForm for testing through this method
     */
    protected ActionForm processActionForm(
        HttpServletRequest request,
        HttpServletResponse response,
        ActionMapping mapping) {

        
        // Create (if necessary a form bean to use
        String formBeanName = mapping.getName();
        String mockBeanClassName = (String) mockActionFormMap.get(formBeanName);
        if (mockBeanClassName == null)
            return super.processActionForm(request, response, mapping);

        ActionForm instance = null;
        try {
            Class formClass = Class.forName(mockBeanClassName );
            instance = (ActionForm) formClass.newInstance();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

        instance.setServlet(servlet);
        if (instance == null) {
            return (null);
        }

        if (log.isDebugEnabled()) {
            log.debug(
                " Storing ActionForm bean instance in scope '"
                    + mapping.getScope()
                    + "' under attribute key '"
                    + mapping.getAttribute()
                    + "'");
        }
        if ("request".equals(mapping.getScope())) {
            request.setAttribute(mapping.getAttribute(), instance);
        } else {
            HttpSession session = request.getSession();
            session.setAttribute(mapping.getAttribute(), instance);
        }
        return (instance);

    }

    /** *//**
     * We will insert Mock Action Class through this method
     */
    protected Action processActionCreate(
        HttpServletRequest request,
        HttpServletResponse response,
        ActionMapping mapping)
        throws IOException {
        String orignalClassName = mapping.getType();
        String mockClassName = (String)mockActionMap.get(orignalClassName);
        if( mockClassName == null )
            return super.processActionCreate(request,response,mapping);
        String className = mockClassName;        
        if (log.isDebugEnabled()) {
            log.debug(" Looking for Action instance for class " + className);
        }

        Action instance = null;
        synchronized (actions) {

            // Return any existing Action instance of this class
            instance = (Action) actions.get(className);
            if (instance != null) {
                if (log.isTraceEnabled()) {
                    log.trace("  Returning existing Action instance");
                }
                return (instance);
            }

            // Create and return a new Action instance
            if (log.isTraceEnabled()) {
                log.trace("  Creating new Action instance");
            }

            try {
                instance = (Action) RequestUtils.applicationInstance(className);
            } catch (Exception e) {
                log.error(
                    getInternal().getMessage("actionCreate", mapping.getPath()),
                    e);

                response.sendError(
                    HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                    getInternal().getMessage(
                        "actionCreate",
                        mapping.getPath()));

                return (null);
            }

            instance.setServlet(this.servlet);
            actions.put(className, instance);
        }

        return (instance);
    }

}

Test类:

setUp()方法:

super.setUp();//调用mockStrutsTestCase中的setUp方法

Fileweb=newFile("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名称

package test.sample.service.action;


import java.io.File;

import servletunit.struts.MockStrutsTestCase;
import test.sample.service.util.STCRequestProcessor;
/** *//**
 * 
-  setContextDirectory,设置web应用的根 
-  setRequestPathInfo,设置request的请求 
-  addRequestParameter,将参数和对应的值加入request中 
-  actionPerform,执行这个请求 
-  verifyForward,验证forward的名字是否正确 
-  verifyForwardPath,验证forward的path是否正确 
-  verifyNoActionErrors,验证在action执行过程中没有ActionError产生 
-  verifyActionErrors,验证在action执行过程中产生的ActionError集合的内容 
 * @author donganlei
 *
 */
public class MockWordActionTest extends MockStrutsTestCase {
    
    public void testInvalidPageflag1()throws Exception{
          addRequestParameter("reqCode","getWordList");
          addRequestParameter("pageflag","userquery");
          actionPerform();
          verifyNoActionErrors();
          verifyForward("querylist");
    }
    
    public void testInvalidPageflag2()throws Exception{
          addRequestParameter("reqCode","getWordList");
          addRequestParameter("pageflag","seatquery");
          actionPerform();
          verifyNoActionErrors();
          verifyForward("querylist");
    }
    
    public void testInvalidInitUpdate()throws Exception{
          addRequestParameter("reqCode","initUpdate");
          actionPerform();
          verifyNoActionErrors();
          verifyForward("update");
    }
    public void testinitUpdate()throws Exception{
          addRequestParameter("reqCode","initUpdate");
          addRequestParameter("wordid","3");
          addRequestParameter("roomid","3");
          actionPerform();
          verifyNoActionErrors();
          verifyForward("update");
    }
    protected void setUp() throws Exception {
        super.setUp();
        File web = new File("E:/project/portal/WebContent");
        this.setContextDirectory(web);
        setConfigFile("/WEB-INF/web.xml");
        setConfigFile("/WEB-INF/struts-config.xml");
        STCRequestProcessor.addMockActionForm("ser_wordForm", "test.sample.service.form.MockWordForm");
        STCRequestProcessor.addMockAction("com.huawei.service.action.WordAction","test.sample.service.action.MockWordAction");
        setRequestPathInfo("/service/word");
    }
    public static void main(String args[]){
        junit.textui.TestRunner.run(MockWordActionTest.class);
    }  
}

Struts-congfig.xml中的processorClass

<controller>

<set-propertyproperty="processorClass"value="test.sample.service.util.STCRequestProcessor"/>

</controller>

相关推荐