东东东 陈煜东的博客

标签存档: spring

用junit对struts2 action和spring进行单元测试

对action和spring进行测试,就不用再开tomcat了,此方法就是模拟用户的http请求进行的,但是这个方法不能看页面的工作情况,但对action的测试足够了。

此测试方法参考了http://depressedprogrammer.wordpress.com/2007/06/18/unit-testing-struts-2-actions-spring-junit/ ,此方法在我的代码中不能正常工作,需要改动。

首先需要的jar文件:spring-test-3.05.RELEASE.jar、spring-core-3.1.5RELEASE.jar,文中并没有给出相关依赖jar包。

public class PersonAction extend ActionSupport {

  private int id;

  public int getId() {
    return id;
  }
  public void setId(int id) {
    this.id = id;
  }
  public String deletePerson() {
    ....
    return SUCCESS;
  }
}
import com.opensymphony.xwork2.ActionProxy;
import com.opensymphony.xwork2.ActionProxyFactory;
import junit.framework.TestCase;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.dispatcher.Dispatcher;
import org.apache.struts2.views.JspSupportServlet;
import org.springframework.context.ApplicationContext;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.mock.web.MockServletConfig;
import org.springframework.mock.web.MockServletContext;
import org.springframework.web.context.ContextLoader;

import java.util.HashMap;

/**
 * @author Zarar Siddiqi
 */
public abstract class BaseStrutsTestCase extends TestCase {
    private static final String CONFIG_LOCATIONS = "file:WebRoot/WEB-INF/applicationContext.xml";
    private static ApplicationContext applicationContext;
    private Dispatcher dispatcher;
    protected ActionProxy proxy;
    protected static MockServletContext servletContext;
    protected static MockServletConfig servletConfig;
    protected MockHttpServletRequest request;
    protected MockHttpServletResponse response;

    public BaseStrutsTestCase(String name) {
        super(name);
    }

    /**
     * Created action class based on namespace and name
     * @param clazz Class for which to create Action
     * @param namespace Namespace of action
     * @param name Action name
     * @return Action class
     * @throws Exception Catch-all exception
     */
    @SuppressWarnings("unchecked")
    protected <T> T createAction(Class<T> clazz, String namespace, String name)
            throws Exception {

        // create a proxy class which is just a wrapper around the action call.
        // The proxy is created by checking the namespace and name against the
        // struts.xml configuration
        proxy = dispatcher.getContainer().getInstance(ActionProxyFactory.class).
                createActionProxy(
                namespace, name, null, true, false);

        // by default, don't pass in any request parameters
        proxy.getInvocation().getInvocationContext().
                setParameters(new HashMap());

        // do not execute the result after executing the action
        proxy.setExecuteResult(true);

        // set the actions context to the one which the proxy is using
        ServletActionContext.setContext(
                proxy.getInvocation().getInvocationContext());
        request = new MockHttpServletRequest();
        response = new MockHttpServletResponse();
        ServletActionContext.setRequest(request);
        ServletActionContext.setResponse(response);
        ServletActionContext.setServletContext(servletContext);
        return (T) proxy.getAction();
    }

    protected void setUp() throws Exception {
        if( applicationContext == null ) {
            // this is the first time so initialize Spring context
            servletContext = new MockServletContext();
            servletContext.addInitParameter(ContextLoader.CONFIG_LOCATION_PARAM,
                    CONFIG_LOCATIONS);
            applicationContext = (new ContextLoader()).initWebApplicationContext(servletContext);

            // Struts JSP support servlet (for Freemarker)
            new JspSupportServlet().init(new MockServletConfig(servletContext));
        }
        // Dispatcher is the guy that actually handles all requests.  Pass in
        // an empty. Map as the parameters but if you want to change stuff like
        // what config files to read, you need to specify them here.  Here's how to
        // scan packages for actions (thanks to Hardy Ferentschik - Comment 66)
        // (see Dispatcher's source code)
        HashMap params = new HashMap();
        params.put("actionPackages", "com.test.action");
        dispatcher = new Dispatcher(servletContext, params);
        dispatcher.init();
        Dispatcher.setInstance(dispatcher);
    }
}

文中第20行在我的myeclipse不能工作,本来按原文的方法是抛出FileNotFound异常,采用改为file:WebRoot/WEB-INF/applicationContext.xml来解决的。其中第87行需要改成自己的包名。

public class PersonActionTest extends BaseStrutsTestCase {

 /**
  * Invoke all interceptors and specify value of the action
  * class' domain objects directly.
  * @throws Exception Exception
  */
 public void testInterceptorsBySettingDomainObjects()
         throws Exception {
  PersonAction action = createAction(PersonAction.class,
                "/site", "deletePerson");
  action.setId(123);
  String result = proxy.execute();
  assertEquals(result, "success");
 }

 /**
  * Invoke all interceptors and specify value of action class'
  * domain objects through request parameters.
  * @throws Exception Exception
  */
 public void testInterceptorsBySettingRequestParameters()
                     throws Exception {
  createAction(PersonAction.class, "/site", "deletePerson");
  request.addParameter("id", "123");
  String result = proxy.execute();
  assertEquals(result, "success");
 }

 /**
  * Skip interceptors and specify value of action class'
  * domain objects by setting them directly.
  * @throws Exception Exception
  */
 public void testActionAndSkipInterceptors() throws Exception {
  PersonAction action = createAction(PersonAction.class,
                  "/site", "deletePerson");
  action.setId(123);
  String result = action.deletePerson();
  assertEquals(result, "success");
 }
}

自己编写testcase继承该类即可。按照这个格式编写测试用例。

另外的junit方法,查看http://developer.51cto.com/art/201108/282751.htm

声明:未经允许禁止转载 东东东 陈煜东的博客 文章,谢谢。如经授权,转载请注明: 转载自东东东 陈煜东的博客

本文链接地址: 用junit对struts2 action和spring进行单元测试 – https://www.chenyudong.com/archives/unit-testing-struts-2-actions-and-spring-using-junit.html

分类: 未分类

tomcat web应用 jsp 数据库 spring hibernate使用UTF-8编码

Eclipse项目配置

在Eclipse的项目中,使用UTF-8编码。如果需要,最好把整个workspace都设置成UTF-8编码。

Tomcat配置

此处的配置主要是配置URL的配置,这样可以中文的URL了。在$Tomcat/conf/server.xml文件中添加高亮部分

<!-- Define a non-SSL HTTP/1.1 Connector on port 8080 -->
<Connector port="8080" maxHttpHeaderSize="8192"
         maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
         enableLookups="false" redirectPort="8443" acceptCount="100"
         connectionTimeout="20000" disableUploadTimeout="true"
         URIEncoding="UTF-8"
/>

数据库配置

数据库多种多样,有Oracle、DB2、MySQL、SQLServer等常用的。不一一说明具体的数据库配置。

举例MySQL数据库来说。要设置的有数据库、表、字段。字符集全部设置成utf8编码,字符集整理一般使用utf8_gerenral_ci。

spring配置

在连接数据库上使用jdbc:mysql://localhost:3306/db?useUnicode=true&characterEncoding=UTF-8来确保与数据库的交互使用UTF-8编码。

<bean id="dataSource"                   
    class="org.apache.commons.dbcp.BasicDataSource">        <!-- 配置数据源 -->
    <property name="driverClassName"
        value="com.mysql.jdbc.Driver">
    </property>
    <property name="url"
        value="jdbc:mysql://localhost:3306/db?useUnicode=true&amp;characterEncoding=UTF-8">
    </property>
    <property name="username" value="root"></property>
    <property name="password" value="root"></property>
</bean>

jsp页面配置

第一行确保服务器传送一个UTF-8编码的流给客户端,第六行确保浏览器使用一个UTF-8编码来显示给客户。

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML>
<html>
    <head>
        <title>页面</title>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    </head>
</html>

Java Web应用配置

web.xml的文件配置

<filter>  
        <filter-name>encodingFilter</filter-name>  
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>  
        <init-param>  
            <param-name>encoding</param-name>  
            <param-value>UTF-8</param-value>  
        </init-param>  
        <init-param>  
            <param-name>forceEncoding</param-name>  
            <param-value>true</param-value>  
        </init-param>  
</filter>

声明:未经允许禁止转载 东东东 陈煜东的博客 文章,谢谢。如经授权,转载请注明: 转载自东东东 陈煜东的博客

本文链接地址: tomcat web应用 jsp 数据库 spring hibernate使用UTF-8编码 – https://www.chenyudong.com/archives/tomcat-jsp-database-spring-hibernate-all-use-unicode-and-utf8.html

分类: 未分类

Copyright © 2021 东东东 陈煜东的博客 粤ICP备13059639号-1

SITEMAP回到顶部 ↑