4.新建Service。
package action; import org.springframework.stereotype.Service; @Service public class UserService { /** * 简单的返回用户名 */ public String getName(String name) { // 这个地方实际上应该调用Dao持久层的代码,在此简化了。 // 本文只是单元测试Struts2Spring整合中,Struts的Action和Spring注入的Service。 // Struts2Spring+Hibernate/Mybatis将在后续篇章中介绍。 return name; } } |
5.单元测试Action。
package unittest; import org.apache.struts2.StrutsSpringTestCase; import org.junit.Test; import action.UserAction; import com.opensymphony.xwork2.ActionProxy; /** * 测试StrutsSpring集成的时候,需要继承StrutsSpringTestCase这个类, * 而单独测试Struts的时候,继承StrutsTestCase。 * * @author http://blog.csdn.net/fansunion/ * */ public class ActionUnitTest extends StrutsSpringTestCase { // 重写父类方法,指定配置文件的名字 protected String[] getContextLocations() { return new String[] { "struts.xml", "applicationContext-spring.xml" }; } @Test public void testExecute() throws Exception { ActionProxy proxy = getActionProxy("/unitTest"); UserAction test = (UserAction) proxy.getAction(); assertNotNull(test); String result = proxy.execute(); assertEquals("success", result); } } |