首先编写一个controller
package com.example.lchtest.springbootdemo1.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class GetController {
@RequestMapping("/test/getName")
@ResponseBody
public String test(){
System.out.println("********* 请求处理中 *********");
return "hello";
}
}
MockMvc的作用: 模拟接口请求,等同于一个http客户端
(1) 测试类上面加上@AutoConfigureMockMvc注解
(2) MockMvc常用方法
perform()方法 : 执行一个RequestBuilder请求
andExpect: 添加ResultMatcher-> MockMvcResultMatchers验证规则
andReturn 返回相应的MvcResult
package com.example.lchtest.springbootdemo1;
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.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
/**
* springboot测试 @SpringBootTest注解后面要加上主启动类,否则会报错
*/
@AutoConfigureMockMvc
@SpringBootTest(classes={App.class})
public class MockMvcTest {
/**
* mockMvc等同于一个http客户端
*/
@Autowired
private MockMvc mockMvc;
@Test
public void apiTest() throws Exception {
MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.get("/test/getName"))
.andExpect(MockMvcResultMatchers.status().isOk())
.andReturn();
int status = mvcResult.getResponse().getStatus();
System.out.println(status);
}
}
测试结果