Spring Boot项目中使用MockMvc进行测试的详细指南
    		       		warning:
    		            这篇文章距离上次修改已过425天,其中的内容可能已经有所变动。
    		        
        		                
                
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.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultHandlers;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
 
@SpringBootTest
@AutoConfigureMockMvc
public class ExampleControllerTest {
 
    @Autowired
    private MockMvc mockMvc;
 
    @Test
    public void shouldReturnDefaultMessage() throws Exception {
        this.mockMvc.perform(MockMvcRequestBuilders.get("/hello"))
            .andDo(MockMvcResultHandlers.print())
            .andExpect(MockMvcResultMatchers.status().isOk())
            .andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
            .andExpect(MockMvcResultMatchers.jsonPath("$.message").value("Hello, World!"));
    }
}这段代码演示了如何使用Spring Boot的@SpringBootTest和@AutoConfigureMockMvc注解来进行集成测试,并使用MockMvc来发起GET请求,检查响应状态、内容类型和JSON内容。
评论已关闭