How to test actions and daoes in struts2 wired with spring

Remember that in Struts 2, an action is usually called before and after various other interceptors are invoked.
Interceptor configuration is usually specified in the struts.xml file.
At this point we need to cover three different methods of how you might want to call your actions.

1. Specify request parameters which are translated and mapped to the actions domain objects (id in the PersonAction class) and then execute the action while also executing all configured interceptors.

 

2. Instead of specifying request parameters, directly specify the values of the domain objects and then execute the action while also executing all configured interceptors.

 


3.Finally, you just might want to execute the action and not worry about executing the interceptors. Here you’ll specify the values of the actions domain objects and then
execute the action.

 

 

http://depressedprogrammer.wordpress.com/2007/06/18/unit-testing-struts-2-actions-spring-junit/

 

为了防止原文不能打开,现把其内容COPY如下:
Depending on what you’re testing and what scenario you want to reproduce, you should pick the one that suits the case. There’s an example of all three cases below. The best way I find to test all your action classes is to have one base class which sets up the Struts 2 environment and then your action test classes can extend it. Here’s a class that could be used as one of those base classes.

 

要测试的ACTION

public class PersonAction extend ActionSupport {  

02    

03   private int id;  

04    

05   public int getId() {  

06     return id;  

07   }  

08   public void setId(int id) {  

09     this.id = id;  

10   }  

11   public String deletePerson() {  

12     ....  

13     return SUCCESS;  

14   }  

 

 

BaseStrutsTestCase

import com.opensymphony.xwork2.ActionProxy;  

02 import com.opensymphony.xwork2.ActionProxyFactory;  

03 import junit.framework.TestCase;  

04 import org.apache.struts2.ServletActionContext;  

05 import org.apache.struts2.dispatcher.Dispatcher;  

06 import org.apache.struts2.views.JspSupportServlet;  

07 import org.springframework.context.ApplicationContext;  

08 import org.springframework.mock.web.MockHttpServletRequest;  

09 import org.springframework.mock.web.MockHttpServletResponse;  

10 import org.springframework.mock.web.MockServletConfig;  

11 import org.springframework.mock.web.MockServletContext;  

12 import org.springframework.web.context.ContextLoader;  

13    

14 import java.util.HashMap;  

15    

16 /**  

17  * @author Zarar Siddiqi  

18  */ 

19 public abstract class BaseStrutsTestCase extends TestCase {  

20     private static final String CONFIG_LOCATIONS = "META-INF/applicationContext-app.xml," +  

21                 "META-INF/applicationContext-security.xml";  

22     private static ApplicationContext applicationContext;  

23     private Dispatcher dispatcher;  

24     protected ActionProxy proxy;  

25     protected static MockServletContext servletContext;  

26     protected static MockServletConfig servletConfig;  

27     protected MockHttpServletRequest request;  

28     protected MockHttpServletResponse response;  

29    

30     public BaseStrutsTestCase(String name) {  

31         super(name);  

32     }  

33    

34     /**  

35      * Created action class based on namespace and name  

36      * @param clazz Class for which to create Action  

37      * @param namespace Namespace of action  

38      * @param name Action name  

39      * @return Action class  

40      * @throws Exception Catch-all exception  

41      */ 

42     @SuppressWarnings("unchecked")  

43     protected <t> T createAction(Class<t> clazz, String namespace, String name)  

44             throws Exception {  

45    

46         // create a proxy class which is just a wrapper around the action call.  

47         // The proxy is created by checking the namespace and name against the  

48         // struts.xml configuration  

49         proxy = dispatcher.getContainer().getInstance(ActionProxyFactory.class).  

50                 createActionProxy(  

51                 namespace, name, null, true, false);  

52    

53         // by default, don't pass in any request parameters  

54         proxy.getInvocation().getInvocationContext().  

55                 setParameters(new HashMap());  

56    

57         // do not execute the result after executing the action  

58         proxy.setExecuteResult(true);  

59    

60         // set the actions context to the one which the proxy is using  

61         ServletActionContext.setContext(  

62                 proxy.getInvocation().getInvocationContext());  

63         request = new MockHttpServletRequest();  

64         response = new MockHttpServletResponse();  

65         ServletActionContext.setRequest(request);  

66         ServletActionContext.setResponse(response);  

67         ServletActionContext.setServletContext(servletContext);  

68         return (T) proxy.getAction();  

69     }  

70    

71     protected void setUp() throws Exception {  

72         if( applicationContext == null ) {  

73             // this is the first time so initialize Spring context  

74             servletContext = new MockServletContext();  

75             servletContext.addInitParameter(ContextLoader.CONFIG_LOCATION_PARAM,  

76                     CONFIG_LOCATIONS);  

77             applicationContext = (new ContextLoader()).initWebApplicationContext(servletContext);  

78    

79             // Struts JSP support servlet (for Freemarker)  

80             new JspSupportServlet().init(new MockServletConfig(servletContext));  

81         }  

82         // Dispatcher is the guy that actually handles all requests.  Pass in  

83         // an empty. Map as the parameters but if you want to change stuff like  

84         // what config files to read, you need to specify them here.  Here's how to  

85         // scan packages for actions (thanks to Hardy Ferentschik - Comment 66)  

86         // (see Dispatcher's source code)  

87         HashMap params = new HashMap();  

88         params.put("actionPackages", "com.arsenalist.action");  

89         dispatcher = new Dispatcher(servletContext, params);  

90         dispatcher.init();  

91         Dispatcher.setInstance(dispatcher);  

92     }  

93 } 

 

By extending the above class for our action test classes we can easily simulate any of the three scenarios listed above. I’ve added three methods to PersonActionTest which illustrate how to test the above three cases: testInterceptorsBySettingRequestParameters, testInterceptorsBySettingDomainObjects() and testActionAndSkipInterceptors(), respectively.

 

public class PersonActionTest extends BaseStrutsTestCase {  

02    

03  /**  

04   * Invoke all interceptors and specify value of the action  

05   * class' domain objects directly.  

06   * @throws Exception Exception  

07   */ 

08  public void testInterceptorsBySettingDomainObjects()  

09          throws Exception {  

10   PersonAction action = createAction(PersonAction.class,  

11                 "/site", "deletePerson");  

12   action.setId(123);  

13   String result = proxy.execute();  

14   assertEquals(result, "success");  

15  }  

16    

17  /**  

18   * Invoke all interceptors and specify value of action class'  

19   * domain objects through request parameters.  

20   * @throws Exception Exception  

21   */ 

22  public void testInterceptorsBySettingRequestParameters()  

23                      throws Exception {  

24   createAction(PersonAction.class, "/site", "deletePerson");  

25   request.addParameter("id", "123");  

26   String result = proxy.execute();  

27   assertEquals(result, "success");  

28  }  

29    

30  /**  

31   * Skip interceptors and specify value of action class'  

32   * domain objects by setting them directly.  

33   * @throws Exception Exception  

34   */ 

35  public void testActionAndSkipInterceptors() throws Exception {  

36   PersonAction action = createAction(PersonAction.class,  

37                   "/site", "deletePerson");  

38   action.setId(123);  

39   String result = action.deletePerson();  

40   assertEquals(result, "success");  

41  }  

42 } 

 

 

 

 

 

 

 

 

 

 

 

 

 

下面就举几个例子加以说

 

1 测试DAO

 

/**
 * 
 */
package org.macaulites.test;

import org.macaulites.dao.LegislationDao;
import org.macaulites.dao.hibernate.LegislationDaoHibernate;
import junit.framework.TestCase;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
/**
 * @author zhj-macau
 *
 */
public class LegislationDaoTest extends TestCase {

	private LegislationDao legDao;

	/**
	 * @param name
	 */
	public LegislationDaoTest(String name) {
		super(name);
	}

	/* (non-Javadoc)
	 * @see junit.framework.TestCase#setUp()
	 */
	protected void setUp() throws Exception {
		super.setUp();
		legDao = new LegislationDaoHibernate();
		ApplicationContext ctx = new FileSystemXmlApplicationContext("C:\\Users\\zhj-macau\\workspace\\macaulites\\src\\applicationContext.xml");
	    legDao = (LegislationDao) ctx.getBean("legDao");
	}

	/* (non-Javadoc)
	 * @see junit.framework.TestCase#tearDown()
	 */
	protected void tearDown() throws Exception {
		super.tearDown();
	}
	
	
	public void testFindByName() throws Exception
	{
		assertNotNull(legDao.findByName("taxLaw"));		
	}

}

 这种测试会加载配置文件,连接数据库

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值