使用struts2 - junit - plugin - *.jar对Action进行测试

1. 使用StrutsTestCase测试


Account.java:

package cn.wang.struts;

public class Account {
 private String userName;
 private String password;

 public String getUserName() {
 return userName;
 }

 public void setUserName(String userName) {
 this.userName = userName;
 }

 public String getPassword() {
 return password;
 }

 public void setPassword(String password) {
 this.password = password;
 }
}

AccountAction.java:

package cn.wang.struts;

import com.opensymphony.xwork2.ActionSupport;

public class AccountAction extends ActionSupport {
 private static final long serialVersionUID = 1L;

 private Account accountBean;

 public String execute(){

 return SUCCESS;

 }

 public void validate(){

 if ( accountBean.getUserName().length() == 0 ){

 addFieldError( "accountBean.userName", "User name is required." );

 }

 if ( accountBean.getUserName().length() < 5 ) {

 addFieldError( "accountBean.userName", "User name must be at least 5 characters long." );

 }

 if ( accountBean.getUserName().length() > 10 ) {

 addFieldError( "accountBean.userName", "User name cannot be at more than 10 characters long." );

 }


 }

 public Account getAccountBean() {
 return accountBean;
 }

 public void setAccountBean(Account accountBean) {
 this.accountBean = accountBean;
 }

}


struts.xml: 

放在src目录下
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name="struts.devMode" value="true" />
 <package name="test" namespace="/test" extends="struts-default">
 <action name="createaccount"
 class="cn.wang.struts.AccountAction">
 <result>/thankyou.jsp</result>
 <result name="input">/createaccount.jsp</result>
 </action>
 </package>
</struts>


TestAccountActionUsingStrutsTestCase.java:

package cn.wang.struts.tests;

import org.apache.struts2.StrutsTestCase;
import org.apache.struts2.dispatcher.mapper.ActionMapping;
import org.junit.Test;

import cn.wang.struts.AccountAction;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionProxy;

public class TestAccountActionUsingStrutsTestCase extends StrutsTestCase {
 @Test
 public void testActionMapping() {
 ActionMapping mapping = getActionMapping("/test/createaccount");
 assertNotNull(mapping);
 assertEquals("/test", mapping.getNamespace());
 assertEquals("createaccount", mapping.getName());
 }
 
 @Test
 public void testUserNameErrorMessage() throws Exception {

     request.setParameter("accountBean.userName", "Bruc");
     request.setParameter("accountBean.password", "test");

     ActionProxy proxy = getActionProxy("/test/createaccount");
     assertNotNull(proxy);
     
     AccountAction accountAction = (AccountAction) proxy.getAction();
     assertNotNull(accountAction);
     
        String result = proxy.execute();
        assertEquals(Action.INPUT, result);
        assertTrue("Problem There were no errors present in fieldErrors but there should have been one error present", accountAction.getFieldErrors().size() == 1);
 assertTrue("Problem field account.userName not present in fieldErrors but it should have been",
 accountAction.getFieldErrors().containsKey("accountBean.userName") );

    }

 @Test
    public void testUserNameCorrect() throws Exception {

     request.setParameter("accountBean.userName", "Bruce");
     request.setParameter("accountBean.password", "test");

     ActionProxy proxy = getActionProxy("/test/createaccount");

     AccountAction accountAction = (AccountAction) proxy.getAction();

        String result = proxy.execute();

        assertTrue("Problem There were errors present in fieldErrors but there should not have been any errors present", accountAction.getFieldErrors().size() == 0);
        assertEquals("Result returned form executing the action was not success but it should have been.", "success", result);

    }
}



另外还需在WebRoot目录下创建两个JSP文件:createaccount.jsp和thankyou.jsp.

2. 使用StrutsSpringTestCase集成Spring进行Action的测试

第1种类型的Action:

Account.java:

package cn.wang.struts;

public class Account {
 private String userName;
 private String password;

 public String getUserName() {
 return userName;
 }

 public void setUserName(String userName) {
 this.userName = userName;
 }

 public String getPassword() {
 return password;
 }

 public void setPassword(String password) {
 this.password = password;
 }
}

AccountAction.java:

package cn.wang.struts;

import com.opensymphony.xwork2.ActionSupport;

public class AccountAction extends ActionSupport {
 private static final long serialVersionUID = 1L;
// private static final Logger logger = Logger.getLogger( AccountAction.class.getName() );
 private Account accountBean;

 public String execute(){
 return SUCCESS;
 }

 public void validate(){
// logger.debug("In method validate. accountBean's state is " + accountBean );
 if ( accountBean.getUserName().length() == 0 ){
 addFieldError( "accountBean.userName", "User name is required." );
 }

 if ( accountBean.getUserName().length() < 5 ) {
 addFieldError( "accountBean.userName", "User name must be at least 5 characters long." );
 }
 if ( accountBean.getUserName().length() > 10 ) {
 addFieldError( "accountBean.userName", "User name cannot be at more than 10 characters long." );
 }
 }

 public Account getAccountBean() {
 return accountBean;
 }

 public void setAccountBean(Account accountBean) {
 this.accountBean = accountBean;
 }
}


第2种类型的Action:

HotAreaBannerVO.java:

package cn.wang.struts;

import java.util.List;

public class HotAreaBannerVO {
 private String bannerId;
 
 public String getBannerId() {
 return bannerId;
 }
 public void setBannerId(String bannerId) {
 this.bannerId = bannerId;
 }
}

BannerAction.java:

package cn.wang.struts;

import org.apache.struts2.json.annotations.JSON;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
/**
 * 
 * 这个控制器用在管理端,用来控制banner获取、修改、新增等操作
 *
 */
@Component
@Scope("prototype")
public class BannerAction extends ActionSupport implements ModelDriven<HotAreaBannerVO> {
 private static final long serialVersionUID = 2181649396520798881L;
 private HotAreaBannerVO hotAreaBannerVO = new HotAreaBannerVO();
 private String pguid;
 private String bannerId;
 private String imageUrl;
 private String newsUrl;
 private String tag;
 private int sortRank; 
        private int putPeriod;
 private String errorCode = "";
 
 @JSON(serialize = false)
 public String get() throws Exception {
 return super.execute();
 }
 
 @JSON(serialize = false)
 public String updateBanner() throws Exception {
 return super.execute();
 }
 
 @JSON(serialize = false)
 public String delete() throws Exception {
 return super.execute();
 }
 public String getPguid() {
 return pguid;
 }

 public void setPguid(String pguid) {
 this.pguid = pguid;
 }

 @Override
 public HotAreaBannerVO getModel() {
 return hotAreaBannerVO;
 }

 @JSON(serialize=false)
 public HotAreaBannerVO getHotAreaBannerVO() {
 return hotAreaBannerVO;
 }

 public void setHotAreaBannerVO(HotAreaBannerVO hotAreaBannerVO) {
 this.hotAreaBannerVO = hotAreaBannerVO;
 }

 public String getErrorCode() {
 return errorCode;
 }

 public void setErrorCode(String errorCode) {
 this.errorCode = errorCode;
 }

 public String getBannerId() {
 return bannerId;
 }

 public void setBannerId(String bannerId) {
 this.bannerId = bannerId;
 }

 public String getImageUrl() {
 return imageUrl;
 }

 public void setImageUrl(String imageUrl) {
 this.imageUrl = imageUrl;
 }

 public String getNewsUrl() {
 return newsUrl;
 }

 public void setNewsUrl(String newsUrl) {
 this.newsUrl = newsUrl;
 }

 public String getTag() {
 return tag;
 }

 public void setTag(String tag) {
 this.tag = tag;
 }

 public int getSortRank() {
 return sortRank;
 }

 public void setSortRank(int sortRank) {
 this.sortRank = sortRank;
 }

 public int getPutPeriod() {
 return putPeriod;
 }

 public void setPutPeriod(int putPeriod) {
 this.putPeriod = putPeriod;
 }
}



配置文件:

src/applicationContext.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xmlns:context="http://www.springframework.org/schema/context"
     xmlns:tx="http://www.springframework.org/schema/tx"
     xsi:schemaLocation="http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
         http://www.springframework.org/schema/context
         http://www.springframework.org/schema/context/spring-context-3.0.xsd
         http://www.springframework.org/schema/tx
         http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
</beans>


src/struts.xml:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
 <constant name="struts.devMode" value="true"></constant>
 <constant name="struts.ognl.allowStaticMethodAccess" value="true" /> 
 <!-- 上传文件大小限制为10M -->
 <constant name="struts.mutipart.maxSize" value="10485769"/>
 <include file="struts/test.xml"></include>
</struts>


src/struts/test.xml:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
 <package name="test" namespace="/test" extends="struts-default">
 <action name="createaccount"
 class="cn.wang.struts.AccountAction">
 <result>/thankyou.jsp</result>
 <result name="input">/createaccount.jsp</result>
 </action>
 </package>
 <package name="adminajax" namespace="/adminajax" extends="json-default">
 <action name="banner" class="cn.wang.struts.BannerAction">
 <result type="json"></result>
 </action>
 </package>
</struts>


测试代码:

TestAccountActionUsingStrutsSpringTestCase.java:

package cn.wang.struts.spring.tests;

import org.apache.struts2.StrutsSpringTestCase;
import org.apache.struts2.dispatcher.mapper.ActionMapping;
import org.junit.Test;

import cn.wang.struts.AccountAction;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionProxy;

public class TestAccountActionUsingStrutsSpringTestCase extends StrutsSpringTestCase {
 @Test
 public void testActionMapping() {
 ActionMapping mapping = getActionMapping("/test/createaccount");
 assertNotNull(mapping);
 assertEquals("/test", mapping.getNamespace());
 assertEquals("createaccount", mapping.getName());
 }
 
 @Test
 public void testUserNameErrorMessage() throws Exception {
     request.setParameter("accountBean.userName", "Bruc");
     request.setParameter("accountBean.password", "test");
     ActionProxy proxy = getActionProxy("/test/createaccount");
     assertNotNull(proxy);
     AccountAction accountAction = (AccountAction) proxy.getAction();
     assertNotNull(accountAction);
        String result = proxy.execute();
        assertEquals(Action.INPUT, result);
        assertTrue("Problem There were no errors present in fieldErrors but there should have been one error present", accountAction.getFieldErrors().size() == 1);
 assertTrue("Problem field account.userName not present in fieldErrors but it should have been",
 accountAction.getFieldErrors().containsKey("accountBean.userName") );
    }

 @Test
    public void testUserNameCorrect() throws Exception {
     request.setParameter("accountBean.userName", "Bruce");
     request.setParameter("accountBean.password", "test");
     ActionProxy proxy = getActionProxy("/test/createaccount");
     AccountAction accountAction = (AccountAction) proxy.getAction();
        String result = proxy.execute();
        assertTrue("Problem There were errors present in fieldErrors but there should not have been any errors present", accountAction.getFieldErrors().size() == 0);
        assertEquals("Result returned form executing the action was not success but it should have been.", "success", result);

    }

 @Override
 public String getContextLocations() {
         return "applicationContext.xml";
 }
}

注:如果spring的配置文件不是默认放在源代码根目录的"applicationContext.xml",则需重写getContextLocations()方法进行指定

GetTest.java:

package cn.wang.struts.spring.tests;

import org.apache.struts2.StrutsSpringTestCase;
import org.apache.struts2.dispatcher.mapper.ActionMapping;
import org.junit.Test;

import cn.wang.struts.BannerAction;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionProxy;

public class GetTest extends StrutsSpringTestCase {
 @Test
 public void testActionMapping() {
 ActionMapping mapping = getActionMapping("/adminajax/banner!get.action");
 assertNotNull(mapping);
 assertEquals("/adminajax", mapping.getNamespace());
 assertEquals("banner", mapping.getName());
 assertEquals("get", mapping.getMethod());
 }
 
 @Test
 public void testNormal()  throws Exception {
 request.setParameter("pguid", "B001D09NUM");
 ActionProxy proxy = getActionProxy("/adminajax/banner!get.action");
 assertNotNull(proxy);
 
 BannerAction bannerAction = (BannerAction) proxy.getAction();
 assertNotNull(bannerAction);
 
 String result = proxy.execute();
 assertEquals(Action.SUCCESS, result);
 assertEquals("B001D09NUM", bannerAction.getPguid());
 }
}

同样需在WebRoot目录下创建两个JSP文件:createaccount.jsp和thankyou.jsp.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值