Controller 层编写测试类

前后端分离以后,Controller 部分的代码当然也要进行测试,但是往常我们的测试类无法发送http请求,这时就需要用到 MockMvc,

一个简单的例子:

测试类:

@RunWith(SpringRunner.class)
@SpringBootTest
public class ControllerTest {
    protected MockMvc mockMvc;
    //集成Web环境,将会从该上下文获取相应的控制器并得到相应的MockMvc;
    @Autowired
    protected WebApplicationContext wac;

    @Before()
    public void setup() {
        mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();  //构造MockMvc对象
    }
    //单位数据量统计服务
    @Test
    public void goUnitDataStatSvcTest() throws Exception {
        Map<String, Object> map = new HashMap<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date startDate = sdf.parse("2018-11-20");
        Date endDate = sdf.parse("2018-11-23");
        map.put("startDate", "2018-11-20");
        map.put("endDate", sdf.format(endDate));
        map.put("instid", "2000");
        map.put("dateType", "other");
        log.info("总天数:"+UsedUtil.daysBetween(startDate, endDate));
        String content = JSONObject.toJSONString(map);
        String result = mockMvc.perform(post("/statistic/goUnitDataStatSvc")
                .contentType(MediaType.APPLICATION_JSON_UTF8)   // 请求中的媒体类型信息—json数据格式
                .content(content))  // RequestBody信息
                .andDo(print()) // 打印出请求和相应的内容
                .andExpect(status().isOk()) // 返回的状态是200
                .andReturn().getResponse().getContentAsString();    // 返回MvcResult并且转为字符串
        Assert.assertNotNull(result);
    }
}

 

控制层 Controller.java
@Controller
@RequestMapping("/statistic")
public class StatisticInfoController {
    @RequestMapping(value = "/goUnitDataStatSvc")
    @ResponseBody
    public ResponseMsg<Object[]> goUnitDataStatSvc(HttpServletRequest request, @RequestBody Map<String,Object> param) throws ParseException {
        // 获得参数
        String instid = userPlugins.getUser(request).getBackup1();
        Date startDate = startDateTransfer(param);
        Date endDate = endDateTransfer(param);
        // 是否选择了快捷选项,目前只有选择“全年-(month)”才有意义
        String dateType = String.valueOf(param.get("dateType")==null?"":param.get("dateType"));
        if(startDate == null || endDate == null || "".equals(instid)|| "".equals(dateType)){
            return new ResponseMsg<>();
        }
        // TODO 调用后台服务
        Object[] obj = statisticInfoService.unitDataStatSvc(startDate, endDate, instid, dateType);
        return ResponsePlugins.ok(obj);
    }
}

方法解析:

  • perform执行一个 RequestBuilder 请求,会自动执行SpringMVC的流程并映射到相应的控制器执行处理;
  • get:声明发送一个get请求的方法。MockHttpServletRequestBuilder get(String urlTemplate, Object... urlVariables):根据uri模板和uri变量值得到一个GET请求方式的。另外提供了其他的请求的方法,如:post、put、delete等。
  • param:添加request的参数,如上面发送请求的时候带上了了pcode = root的参数。假如使用需要发送json数据格式的时将不能使用这种方式,可见后面被@ResponseBody注解参数的解决方法
  • andExpect:添加ResultMatcher验证规则,验证控制器执行完成结果是否正确(对返回的数据进行的判断);
  • andDo:添加ResultHandler结果处理器,比如调试时打印结果到控制台(对返回的数据进行的判断);
  • andReturn:最后返回相应的MvcResult;然后进行自定义验证/进行下一步的异步处理(对返回的数据进行的判断);

 

 友情提示:如果自己的测试类怎么也跑不通,请粘贴如上代码,稍加改动,跑起来在修改自己的!

 

  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
编写 Spring Boot 2.7 版本的 Controller 测试时,你可以使用 Spring MVC测试框架来进行测试。以下是一个简单的示例: 首先,确保你的项目中已经添加了相关的测试依赖,例如 `spring-boot-starter-test`。 然后,创建一个测试,可以使用 JUnit 或者其他测试框架来进行测试。示例代码如下: ```java import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; @SpringBootTest @AutoConfigureMockMvc public class UserControllerTest { @Autowired private MockMvc mockMvc; @Test public void testGetUser() throws Exception { mockMvc.perform(MockMvcRequestBuilders.get("/users/{id}", 1) .contentType(MediaType.APPLICATION_JSON)) .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.jsonPath("$.id").value(1)) .andExpect(MockMvcResultMatchers.jsonPath("$.name").value("John Doe")); } @Test public void testCreateUser() throws Exception { mockMvc.perform(MockMvcRequestBuilders.post("/users") .contentType(MediaType.APPLICATION_JSON) .content("{\"name\": \"Jane Smith\"}")) .andExpect(MockMvcResultMatchers.status().isOk()) .andExpect(MockMvcResultMatchers.jsonPath("$.id").exists()); } // 更多测试方法... } ``` 在上述示例中,我们使用了 `@SpringBootTest` 注解来指

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值