Spring MVC中编写单元测试(WEB项目):
1. 首先开发一个基类,用于载入配置文件。以下所有的测试实现类都要继承这个类
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
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;
/**
* @ClassName: JUnitActionBase
* @Description: 这里用一句话描述这个类的作用
*
*/
public class JUnitActionBase {
private static HandlerMapping handlerMapping;
private static HandlerAdapter handlerAdapter;
/**
* 读取spring3 MVC配置文件
* @throws UnsupportedEncodingException
*/
@BeforeClass
public static void setUp() throws UnsupportedEncodingException {
if (handlerMapping == null) {
File file = new File(Thread.currentThread().getContextClassLoader().getResource("").getPath());
String separator = File.separator;
String path = URLDecoder.decode(file.getAbsolutePath(), "utf-8").replace("", "").replace("\\", "/");
String[] configs = { "file:" + path + separator + "servlet-context.xml",
"file:" + path + separator + "service-context.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);
handlerMapping = (HandlerMapping) context.getBean(DefaultAnnotationHandlerMapping.class);
handlerAdapter = (HandlerAdapter) context.getBean(context
.getBeanNamesForType(AnnotationMethodHandlerAdapter.class)[0]);
}
}
/**
* 执行request对象请求的action
*
* @param request
* @param response
* @return
* @throws Exception
*/
public ModelAndView excuteAction(HttpServletRequest request, HttpServletResponse response) throws Exception {
HandlerExecutionChain chain = handlerMapping.getHandler(request);
ModelAndView model = null;/* handlerAdapter.handle(request, response, chain.getHandler());*/
// 这里需要声明request的实际类型,否则会报错
request.setAttribute(HandlerMapping.INTROSPECT_TYPE_LEVEL_MAPPING, true);
try {
model = handlerAdapter.handle(request, response, chain.getHandler());
} catch (Exception e) {
e.printStackTrace();
}
return model;
}
}
后面所没有Controller类测试时都需要继承上面的类
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.chlitina.register.service.UserService;
public class JUnitTestController 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);
}
@Test
public void testJSONDataSourceServiceSQL() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
request.setRequestURI("/billPay/sendNoRegSMS");
request.setMethod("GET");
// 执行URI对应的action
super.excuteAction(request, response);
String result = response.getContentAsString();
Assert.assertNotNull(result);
}
}