Spring Controller 单元测试

常规的方法则是启动WEB服务器 测试 出错 停掉WEB 改代码 重启WEB 测试 

大量的时间都浪费在WEB服务器的启动上

今天给大家介绍一种不用启动WEB 直接采用单元测试的方法来测试请求是否准确 

该方法基于SpringMVC 与 Spring Test 框架

package com.spring;  
  
import java.io.FileNotFoundException;  
import java.io.IOException;  
import java.util.ArrayList;  
import java.util.List;  
import java.util.Map;  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  
  
import org.json.JSONObject;  
import org.springframework.beans.factory.annotation.Autowired;  
import org.springframework.http.MediaType;  
import org.springframework.stereotype.Controller;  
import org.springframework.ui.Model;  
import org.springframework.web.bind.annotation.PathVariable;  
import org.springframework.web.bind.annotation.RequestMapping;  
import org.springframework.web.bind.annotation.RequestMethod;  
import org.springframework.web.bind.annotation.ResponseBody;  
import org.springframework.web.context.ContextLoader;  
import org.springframework.web.context.WebApplicationContext;  
import org.springframework.web.context.support.WebApplicationContextUtils;  
import org.springframework.web.servlet.ModelAndView;  
  
@Controller  
@RequestMapping(value = "/spring")  
public class Action {  
  
    @Autowired  
    Teacher teacher;  
    // spring 支持restful的格式  
      
    @ResponseBody  
    @RequestMapping(value = "/rest/{ownerId}.do", method = RequestMethod.GET)  
    public String findOwner(@PathVariable String ownerId, Model model,  
            HttpServletResponse rep) throws IOException {  
        return ownerId;  
    }  
  
    @RequestMapping(value = "/test.do", method = RequestMethod.GET)  
    public String testa(Model model, HttpServletResponse rep)  
            throws IOException {  
        model.addAttribute("abc", "efd");  
        model.addAttribute(teacher);  
        return "a";  
    }  
  
    @ResponseBody  
    // 理论上可以@ResponseBody 支持直接返回teacher对象 但是3.2里有问题 我们还是老实返回字符串吧  
    @RequestMapping(value = "/testb.do", method = RequestMethod.GET)  
    public String testb(Model model, HttpServletResponse rep,  
            HttpServletRequest req, String ex) throws IOException {  
        // WEB中获得SPRING容器  
        WebApplicationContext wac = WebApplicationContextUtils  
                .getRequiredWebApplicationContext(req.getServletContext());  
        return new JSONObject(wac.getBean(Teacher.class)).toString();  
    }  
  
    @ResponseBody  
    @RequestMapping(value = "/post.do", method = RequestMethod.POST)  
    public String post(Model model, HttpServletResponse rep,  
            HttpServletRequest req, String ex) throws IOException {  
        return new JSONObject(req.getParameterMap()).toString();  
    }  
  
}

  

再上单元测试代码

import java.awt.print.Printable;  
import java.io.IOException;  
  
import javax.servlet.http.HttpServletResponse;  
  
import org.junit.Before;  
import org.junit.Test;  
import org.junit.runner.RunWith;  
import org.springframework.beans.factory.annotation.Autowired;  
import org.springframework.http.MediaType;  
import org.springframework.test.context.ContextConfiguration;  
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;  
import org.springframework.test.context.web.WebAppConfiguration;  
import org.springframework.test.web.servlet.MockMvc;  
import org.springframework.test.web.servlet.ResultHandler;  
import org.springframework.test.web.servlet.ResultMatcher;  
import org.springframework.ui.Model;  
import org.springframework.test.context.transaction.TransactionConfiguration;  
import org.springframework.transaction.annotation.Transactional;  
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.*;  
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.*;  
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;  
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;  
import org.springframework.web.bind.annotation.RequestMapping;  
import org.springframework.web.bind.annotation.RequestMethod;  
import org.springframework.web.context.WebApplicationContext;  
  
@RunWith(SpringJUnit4ClassRunner.class)  
@WebAppConfiguration  
@ContextConfiguration(locations = { "classpath:applicationContext.xml" })  
//当然 你可以声明一个事务管理 每个单元测试都进行事务回滚 无论成功与否  
@TransactionConfiguration(defaultRollback = true)  
//记得要在XML文件中声明事务哦~~~我是采用注解的方式  
@Transactional  
public class ExampleTests {  
  
    @Autowired  
    private WebApplicationContext wac;  
  
    private MockMvc mockMvc;  
  
    @Before  
    public void setup() {  
        // webAppContextSetup 注意上面的static import  
        // webAppContextSetup 构造的WEB容器可以添加fileter 但是不能添加listenCLASS  
        // WebApplicationContext context =  
        // ContextLoader.getCurrentWebApplicationContext();  
        // 如果控制器包含如上方法 则会报空指针  
        this.mockMvc = webAppContextSetup(this.wac).build();  
    }  
  
    @Test  
        //有些单元测试你不希望回滚  
        @Rollback(false)  
    public void ownerId() throws Exception {  
        mockMvc.perform((get("/spring/rest/4.do"))).andExpect(status().isOk())  
                .andDo(print());  
    }  
  
    @Test  
    public void test() throws Exception {  
        mockMvc.perform((get("/spring/test.do"))).andExpect(status().isOk())  
                .andDo(print())  
                .andExpect(model().attributeHasNoErrors("teacher"));  
    }  
  
    @Test  
    public void testb() throws Exception {  
        mockMvc.perform((get("/spring/testb.do"))).andExpect(status().isOk())  
                .andDo(print());  
    }  
  
    @Test  
    public void getAccount() throws Exception {  
        mockMvc.perform((post("/spring/post.do").param("abc", "def")))  
                .andExpect(status().isOk()).andDo(print());  
    }  
  
}




package com.spring;  
  
import java.io.FileNotFoundException;  
import java.io.IOException;  
import java.util.ArrayList;  
import java.util.List;  
import java.util.Map;  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  
  
import org.json.JSONObject;  
import org.springframework.beans.factory.annotation.Autowired;  
import org.springframework.http.MediaType;  
import org.springframework.stereotype.Controller;  
import org.springframework.ui.Model;  
import org.springframework.web.bind.annotation.PathVariable;  
import org.springframework.web.bind.annotation.RequestMapping;  
import org.springframework.web.bind.annotation.RequestMethod;  
import org.springframework.web.bind.annotation.ResponseBody;  
import org.springframework.web.context.ContextLoader;  
import org.springframework.web.context.WebApplicationContext;  
import org.springframework.web.context.support.WebApplicationContextUtils;  
import org.springframework.web.servlet.ModelAndView;  
  
@Controller  
@RequestMapping(value = "/spring")  
public class Action {  
  
    @Autowired  
    Teacher teacher;  
    // spring 支持restful的格式  
      
    @ResponseBody  
    @RequestMapping(value = "/rest/{ownerId}.do", method = RequestMethod.GET)  
    public String findOwner(@PathVariable String ownerId, Model model,  
            HttpServletResponse rep) throws IOException {  
        return ownerId;  
    }  
  
    @RequestMapping(value = "/test.do", method = RequestMethod.GET)  
    public String testa(Model model, HttpServletResponse rep)  
            throws IOException {  
        model.addAttribute("abc", "efd");  
        model.addAttribute(teacher);  
        return "a";  
    }  
  
    @ResponseBody  
    // 理论上可以@ResponseBody 支持直接返回teacher对象 但是3.2里有问题 我们还是老实返回字符串吧  
    @RequestMapping(value = "/testb.do", method = RequestMethod.GET)  
    public String testb(Model model, HttpServletResponse rep,  
            HttpServletRequest req, String ex) throws IOException {  
        // WEB中获得SPRING容器  
        WebApplicationContext wac = WebApplicationContextUtils  
                .getRequiredWebApplicationContext(req.getServletContext());  
        return new JSONObject(wac.getBean(Teacher.class)).toString();  
    }  
  
    @ResponseBody  
    @RequestMapping(value = "/post.do", method = RequestMethod.POST)  
    public String post(Model model, HttpServletResponse rep,  
            HttpServletRequest req, String ex) throws IOException {  
        return new JSONObject(req.getParameterMap()).toString();  
    }  
  
}

  

再上单元测试代码

import java.awt.print.Printable;  
import java.io.IOException;  
  
import javax.servlet.http.HttpServletResponse;  
  
import org.junit.Before;  
import org.junit.Test;  
import org.junit.runner.RunWith;  
import org.springframework.beans.factory.annotation.Autowired;  
import org.springframework.http.MediaType;  
import org.springframework.test.context.ContextConfiguration;  
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;  
import org.springframework.test.context.web.WebAppConfiguration;  
import org.springframework.test.web.servlet.MockMvc;  
import org.springframework.test.web.servlet.ResultHandler;  
import org.springframework.test.web.servlet.ResultMatcher;  
import org.springframework.ui.Model;  
import org.springframework.test.context.transaction.TransactionConfiguration;  
import org.springframework.transaction.annotation.Transactional;  
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.*;  
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.*;  
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;  
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;  
import org.springframework.web.bind.annotation.RequestMapping;  
import org.springframework.web.bind.annotation.RequestMethod;  
import org.springframework.web.context.WebApplicationContext;  
  
@RunWith(SpringJUnit4ClassRunner.class)  
@WebAppConfiguration  
@ContextConfiguration(locations = { "classpath:applicationContext.xml" })  
//当然 你可以声明一个事务管理 每个单元测试都进行事务回滚 无论成功与否  
@TransactionConfiguration(defaultRollback = true)  
//记得要在XML文件中声明事务哦~~~我是采用注解的方式  
@Transactional  
public class ExampleTests {  
  
    @Autowired  
    private WebApplicationContext wac;  
  
    private MockMvc mockMvc;  
  
    @Before  
    public void setup() {  
        // webAppContextSetup 注意上面的static import  
        // webAppContextSetup 构造的WEB容器可以添加fileter 但是不能添加listenCLASS  
        // WebApplicationContext context =  
        // ContextLoader.getCurrentWebApplicationContext();  
        // 如果控制器包含如上方法 则会报空指针  
        this.mockMvc = webAppContextSetup(this.wac).build();  
    }  
  
    @Test  
        //有些单元测试你不希望回滚  
        @Rollback(false)  
    public void ownerId() throws Exception {  
        mockMvc.perform((get("/spring/rest/4.do"))).andExpect(status().isOk())  
                .andDo(print());  
    }  
  
    @Test  
    public void test() throws Exception {  
        mockMvc.perform((get("/spring/test.do"))).andExpect(status().isOk())  
                .andDo(print())  
                .andExpect(model().attributeHasNoErrors("teacher"));  
    }  
  
    @Test  
    public void testb() throws Exception {  
        mockMvc.perform((get("/spring/testb.do"))).andExpect(status().isOk())  
                .andDo(print())


转载于:https://my.oschina.net/huhaoren/blog/549939

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值