使用junit测试SpringMVC

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/z244104850/article/details/84268208
架包支持:junit.jar;org.springframework.test-3.1.0.RELEASE.jar


测试Dao基础类:JUnitDaoBase



package test.test;
import javax.annotation.Resource;
import javax.sql.DataSource;

import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* <b>Summary: </b> TODO Junit 基础类,加载环境
* <b>Remarks: </b> TODO DAO测试基础类
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:/config/applicationContext.xml"})
public class JUnitDaoBase extends AbstractTransactionalJUnit4SpringContextTests {

/**
* <b>Summary: </b> 复写方法 setDataSource
*
* @param dataSource
* @see org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests#setDataSource(javax.sql.DataSource)
*/
@Override
@Resource(name = "myDataSource")
public void setDataSource(DataSource dataSource) {
// TODO Auto-generated method stub
super.setDataSource(dataSource);
}
}




具体dao 测试继承daoBaseTest就可以了


package test.java.dao;

import java.util.List;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import com.pinfang.dao.UserDao;
import com.pinfang.vo.User;

import test.test.JUnitDaoBase;
/**
* dao层测试例子
* @author fule
*
*/
public class UserDaoTest extends JUnitDaoBase {
@Autowired
private UserDao userDao;



@Test
public void testUserDao() {
User user = new User();
user.setPassword("123456");
user.setName("大妈");
user.setSex(1);
//System.out.println(userDao.findOnValidate(user).getMark());
List<User> list = userDao.getAll();
System.out.println(list);
//System.out.println(userDao.findOneByName("张三s"));
//System.out.println(userDao.addUser(user));
}
}



action层测试基础类:JUnitActionBase


package test.test;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.junit.BeforeClass;
import org.springframework.mock.web.MockServletContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.XmlWebApplicationContext;
import org.springframework.web.servlet.HandlerAdapter;
import org.springframework.web.servlet.HandlerExecutionChain;
import org.springframework.web.servlet.HandlerMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter;
import org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping;

/**
* JUnit测试action时使用的基类
*
* @author fule
*
*/
public class JUnitActionBase {
private static HandlerMapping handlerMapping;
private static HandlerAdapter handlerAdapter;

/**
* 读取配置文件
*/
@BeforeClass
public static void setUp() {
if (handlerMapping == null) {
String[] configs = {
"file:src/config/applicationContext.xml" };
XmlWebApplicationContext context = new XmlWebApplicationContext();
context.setConfigLocations(configs);
MockServletContext msc = new MockServletContext();
context.setServletContext(msc);
context.refresh();
msc.setAttribute(
WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE,
context);// TODO
handlerMapping = (HandlerMapping) context
.getBean(DefaultAnnotationHandlerMapping.class);

handlerAdapter = (HandlerAdapter) context
.getBean(context
.getBeanNamesForType(AnnotationMethodHandlerAdapter.class)[0]);

// handlerAdapter = (HandlerAdapter) context.getBean(context
// .getNamespace());
}
}

/**
* 执行request请求的action
*
* @param request
* @param response
* @return
* @throws Exception
*/
public ModelAndView excuteAction(HttpServletRequest request,
HttpServletResponse response) throws Exception {
// 这里需要声明request的实际类型,否则会报错
request.setAttribute(HandlerMapping.INTROSPECT_TYPE_LEVEL_MAPPING, true);
HandlerExecutionChain chain = handlerMapping.getHandler(request);
ModelAndView model = null;
try {
model = handlerAdapter
.handle(request, response, chain.getHandler());
} catch (Exception e) {
e.printStackTrace();
}
return model;
}
}


测试action类继承它就可以了

package test.java.action;

import org.junit.Assert;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.web.servlet.ModelAndView;

import com.pinfang.logic.service.UserService;

import test.test.JUnitActionBase;
/**
* action测试列子
* @author fule
*
*/
public class UserActionTest extends JUnitActionBase {
@Autowired UserService service;
@Test
public void testUserShow() throws Exception{
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
request.setServletPath("/userManager/user.show");
request.addParameter("name", "张三");
request.addParameter("password", "123456");
request.setMethod("post");
request.setAttribute("msg", "测试action成功");
final ModelAndView mav = this.excuteAction(request, response);
Assert.assertEquals("userManager/userlist", mav.getViewName());
String msg=(String)request.getAttribute("msg");
System.out.println(msg);
}
}


配置文件记得声明两个bean:


<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />


Spring读取WEB-INF下配置文件的方法:
配置文件放在class目录下:
view plaincopyprint?
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("springMVCForm-servlet.xml");

WEB-INF下:
[java] view plaincopyprint?
ApplicationContext applicationContext = new FileSystemXmlApplicationContext("WebContent/WEB-INF/springMVCForm-servlet.xml");

多个文件可用*表示:
[java] view plaincopyprint?
ApplicationContext applicationContext = new FileSystemXmlApplicationContext("WebContent/WEB-INF/springMVCForm-*.xml");

注解方式:
配置文件放在class目录下:
[java] view plaincopyprint?
@ContextConfiguration(locations={"classpath:springMVCForm-servlet.xml"})

WEB-INF下:
view plaincopyprint?
@ContextConfiguration(locations={"file:WebContent/WEB-INF/springMVCForm-servlet.xml"})



参考:
[url]http://blog.csdn.net/yeohcooller/article/details/7631202[/url]
[url]http://a52071453.iteye.com/blog/1559000[/url]
[url]http://www.iteye.com/topic/828513[/url]
这几个帖子很详细很强大
展开阅读全文

没有更多推荐了,返回首页