面试题答案
一键面试- 添加依赖:
在
pom.xml
中添加JUnit 5和Spring Boot Test相关依赖。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope>
</dependency>
- 创建测试类:
假设Controller类为
HelloController
,创建测试类HelloControllerTest
。
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.test.web.servlet.MockMvc;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@WebMvcTest(HelloController.class)
public class HelloControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
public void testGetHello() throws Exception {
mockMvc.perform(get("/hello"))
.andExpect(status().isOk())
.andExpect(content().string("Hello, World!"));
}
}
- 注解说明:
@WebMvcTest
:该注解用于测试Spring MVC控制器。它会自动配置MockMvc
,并且只加载与Web MVC相关的组件,而不会加载整个应用上下文,大大提高测试速度。@Autowired
:用于注入MockMvc
实例,MockMvc
提供了一套便捷的API用于模拟HTTP请求并验证响应。
- 测试方法说明:
mockMvc.perform(get("/hello"))
:使用MockMvc
模拟发送一个HTTP GET请求到/hello
路径。.andExpect(status().isOk())
:验证响应状态码为200(OK)。.andExpect(content().string("Hello, World!"))
:验证响应内容为Hello, World!
。
注意,以上示例中的/hello
路径和Hello, World!
响应内容需根据实际的HelloController
实现进行调整。