springboot @SpringBootTest单元测试调用controller接口

本文介绍了一种使用MockMvc进行RESTful API测试的方法,包括GET、POST、PUT和DELETE四种请求方式。通过具体示例展示了如何模拟发送请求、设置请求参数及预期返回结果。
下面介绍了get、post、put、delete四种请求方式
@Test
public void testGetMethod() throws Exception {
   MvcResult result = mockMvc.perform(get("/face/match"))
         .andExpect(status().isOk())// 模拟向testRest发送get请求
         .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))// 预期返回值的媒体类型text/plain;charset=UTF-8
         .andReturn();// 返回执行请求的结果
   System.out.println(result.getResponse().getContentAsString());
}

/**添加人脸图片*/
@Test
public void testAddFace() throws Exception {
   FaceDTO faceDTO = new FaceDTO();
   faceDTO.setGroupId("litsoft07");
   faceDTO.setUserId("xf");
   String image = ImageToBase64Utils.GetImageStrFromPath("C:\\Users\\Administrator\\Desktop\\test.jpg");
   log.info(image);
   faceDTO.setImage(image);
   faceDTO.setImageType(BaiduImageTypeMenu.BASE64.getCode());
   log.info("添加人脸数据:"+JSON.toJSONString(faceDTO));

   MvcResult result = mockMvc.perform(
         post("/face/addFace").contentType(MediaType.APPLICATION_JSON_UTF8_VALUE).content(JSON.toJSONString(faceDTO)))
         .andReturn();
   System.out.println(result.getResponse().getContentAsString());
}

/**修改图片*/
@Test
public void testUpateFace() throws Exception {
   FaceDTO faceDTO = new FaceDTO();
   faceDTO.setGroupId("litsoft07");
   faceDTO.setUserId("xf");
   String image = ImageToBase64Utils.GetImageStrFromPath("C:\\Users\\Administrator\\Desktop\\test.jpg");
   log.info(image);
   faceDTO.setImage(image);
   faceDTO.setImageType(BaiduImageTypeMenu.BASE64.getCode());
   log.info("修改人脸数据:"+JSON.toJSONString(faceDTO));
   MvcResult result = mockMvc.perform(
         put("/face/updateFace").contentType(MediaType.APPLICATION_JSON_UTF8_VALUE).content(JSON.toJSONString(faceDTO)))
         .andReturn();
   System.out.println(result.getResponse().getContentAsString());
}

/**删除人脸*/
@Test
public void testDeleteFace() throws Exception {
   FaceDTO faceDTO = new FaceDTO();
   faceDTO.setGroupId("litsoft07");
   faceDTO.setUserId("xf");
   faceDTO.setFaceToken("11c7a123a10bcbf3bcc46e5ef0a01767");
   log.info("删除人脸数据:"+JSON.toJSONString(faceDTO));
   MvcResult result = mockMvc.perform(
         delete("/face/deleteFace").contentType(MediaType.APPLICATION_JSON_UTF8_VALUE).content(JSON.toJSONString(faceDTO)))
         .andReturn();
   System.out.println(result.getResponse().getContentAsString());
}
### 如何在 Spring Boot 中对 Controller 进行单元测试 #### 使用 `@WebMvcTest` 注解进行控制器测试 为了专注于测试Spring Boot应用程序中的Controller层,可以使用`@WebMvcTest`注解。此注解会指示Spring Test框架只加载必要的组件来运行MVC栈,而不需要启动整个应用上下文[^3]。 ```java import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; @RunWith(SpringRunner.class) @WebMvcTest(controllers = ExampleController.class) public class ExampleControllerTests { @Autowired private MockMvc mockMvc; @MockBean private ExampleService exampleService; @Test public void shouldReturnDefaultMessage() throws Exception { this.mockMvc.perform(get("/api/example")) .andExpect(status().isOk()) .andExpect(content().string("Hello, World")); } } ``` 这段代码展示了如何设置一个简单的JUnit测试类来检验名为`ExampleController`的RESTful Web服务端点的行为。通过`mockMvc.perform()`方法发送GET请求到指定路径,并利用链式的`.andExpect()`调用来定义期望的结果状态码以及返回的内容字符串匹配[^2]。 #### 利用 `Mockito` 模拟依赖对象 当测试controller时,通常希望隔离被测部分与其他业务逻辑或外部资源之间的交互。这可以通过引入像`@MockBean`这样的注解来创建模拟的服务实完成,在上面的子中就是`exampleService`。这样可以在不实际执行这些服务的情况下验证controller的工作方式。 #### 验证 HTTP 响应细节 除了检查HTTP的状态码外,还可以进一步深入地去校验响应体的具体结构和数据准确性。比如: - JSON格式的数据解析; - 特定字段的存在性和值; - 头部信息等其他元数据。 对于JSON类型的API接口来说,推荐采用JsonPath表达式来进行更精确细致的断言操作。 ```java @Test public void testGetUserDetailsReturnsCorrectData() throws Exception{ User userDetails = new User(); userDetails.setName("John Doe"); when(userDetailsService.getUserById(anyLong())).thenReturn(userDetails); this.mockMvc.perform(get("/users/1")) .andExpect(jsonPath("$.name").value("John Doe")); } ``` 上述子说明了怎样借助`jsonPath()`函数针对特定属性做对比分析,从而确保API按预期工作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值