本文适用于对SpringBoot里编写的MVC请求进行测试,更多属性设定请进入各个类中去查找。
第一步:注入WebMVC的IOC容器对象 WebApplicationContext
@Autowired
private WebApplicationContect wac;
第二步:伪造一个MVC环境 MockMvc
private MockMvc nockMvc = MockMvcBuilders.webAppContextSetip(wac).build();
第三步:通过 MockMvcRequestBuilders
构造一个请求 RequestBuilder
MockMvcRequestBuilders 支持 get、post、put、delete、option、head方法,还支持request和multipart方法
MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.get("/hello");
第四步:指定自己想要的结果 ResultMatcher
ResultMatcher resultMatcher = MockMvcResultMatchers.status().isOk();
第五步:通过WebApplicationContext
的 perform 方法开始执行请求,设置预期结果为ResultMatcher
mvc.perform(requestBuilder).andExpect(resultMatcher);
完整代码示例:
package com.lqk.learning;
import org.junit.Before;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.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.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
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.MockMvcResultMatchers;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
@RunWith(SpringRunner.class)
@SpringBootTest
class SpringBootLearningApplicationTests {
@Autowired
private WebApplicationContext wac;
private MockMvc mvc;
@Before
public void before(){
mvc = MockMvcBuilders.webAppContextSetup(wac).build();
}
@Test
public void contextLoads() throws Exception {
before();
MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.get("/hello");
ResultMatcher resultMatcher = MockMvcResultMatchers.status().isOk();
mvc.perform(requestBuilder).andExpect(resultMatcher);
}
}