Spring Boot Controller层单元测试
程序员文章站
2022-04-26 09:17:33
...
package com.thrall.dongrj.controller;
import com.alibaba.fastjson.JSON;
import com.thrall.Application;
import com.thrall.business.vo.QuoteGroupVO;
import com.thrall.common.utils.Constants;
import com.thrall.common.utils.page.PageParam;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
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.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Application.class)
@WebAppConfiguration
public class ControllerTest {
@Autowired
private WebApplicationContext wac;
private MockMvc mockMvc;
@Before
public void setUp() throws Exception {
mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
}
@Test
public void test01() throws Exception {
MvcResult result = mockMvc.perform(MockMvcRequestBuilders.get("/customer/{id}", 123)).andDo(print()).andReturn();
System.out.println(result.getResponse().getContentAsString());
}
/**
* 添加报价
*/
@Test
public void test02() throws Exception {
PageParam<QuoteGroupVO> pageParam = new PageParam<>();
pageParam.setCurrentPage(1);
pageParam.setPageSize(20);
QuoteGroupVO quoteGroup = new QuoteGroupVO();
quoteGroup.setStatus(1);
pageParam.setModel(quoteGroup);
String requestBody = JSON.toJSONString(pageParam);
System.out.println(requestBody);
MvcResult result = mockMvc.perform(MockMvcRequestBuilders.get("/quotegroup").
contentType(MediaType.APPLICATION_JSON).content(requestBody))
.andDo(print()).andReturn();
System.out.println(result);
}
}
转载于:https://my.oschina.net/famiover/blog/828441
上一篇: Spring Boot 单元测试
下一篇: SpringBoot单元测试
推荐阅读
-
关于Spring MVC在Controller层中注入request的坑详解
-
详解Spring Boot Junit单元测试
-
详解Spring Boot实战之单元测试
-
idea创建一个入门Spring Boot项目(controller层)使用Moven代码管理
-
Spring Boot通过Junit实现单元测试过程解析
-
spring boot的应用程序单元测试方案
-
spring boot的应用程序单元测试方案
-
Spring Boot从Controller层进行单元测试的实现
-
Spring Boot中使用AOP统一处理web层异常的方法
-
Spring Boot 整合 TKMybatis 二次简化持久层代码的实现