1、创建一个测试用的TestController
@RestController
public class TestController {
@GetMapping("/test")
public String test() {
System.out.println("TestController ... ");
return "test";
}
}
2、编写一个测试类用来发送虚拟请求
package com.qbb;
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.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.ResultActions;
import org.springframework.test.web.servlet.ResultMatcher;
import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.ContentResultMatchers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
import org.springframework.test.web.servlet.result.StatusResultMatchers;
/**
* @author startqbb (个人博客:https://www.cnblogs.com/qbbit)
* @date 2023-02-02 23:24
* @tags 我爱的人在很远的地方, 我必须更加努力
*/
// 测试使用WEB环境启动
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
// 开启虚拟MVC调用
@AutoConfigureMockMvc
public class WebTest {
/**
* @param mockMvc 注入虚拟MockMvc对象
*/
@Test
public void test1(@Autowired MockMvc mockMvc){
try {
// 创建虚拟请求
MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get("/test1");
// 执行请求
ResultActions perform = mockMvc.perform(builder);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Test
public void test2(@Autowired MockMvc mockMvc){
try {
// 创建虚拟请求
MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get("/test1");
// 执行请求
ResultActions perform = mockMvc.perform(builder);
// 设置预期值
StatusResultMatchers status = MockMvcResultMatchers.status();
ResultMatcher ok = status.isOk();
// 预期值和真实值比较
perform.andExpect(ok);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Test
public void testBody(@Autowired MockMvc mockMvc){
try {
// 创建虚拟请求
MockHttpServletRequestBuilder builder = MockMvcRequestBuilders.get("/test");
// 执行请求
ResultActions perform = mockMvc.perform(builder);
// 设置预期值
ContentResultMatchers content = MockMvcResultMatchers.content();
ResultMatcher body = content.string("test");
// 预期值和真实值比较 响应体匹配
perform.andExpect(body);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}