springboot 测试controller
时间: 2023-10-13 12:04:00 浏览: 193
您好!要测试Spring Boot中的Controller,您可以使用JUnit框架和MockMvc类来进行单元测试。以下是一个简单的示例:
```java
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.boot.test.mock.mockito.MockBean;
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.MockMvcResultMatchers;
@WebMvcTest(YourController.class)
public class YourControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private YourService yourService;
@Test
public void testYourController() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get("/your-endpoint")
.contentType(MediaType.APPLICATION_JSON))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.content().string("Expected response"));
}
}
```
上述示例使用`@WebMvcTest`注解来指定要测试的Controller类。通过`MockMvc`类模拟HTTP请求并对返回结果进行断言。
您需要根据实际情况修改`YourController`和`/your-endpoint`以适应您的应用程序。同时,您还可以使用`@MockBean`注解来模拟您的Service类,以便在测试中使用。
阅读全文
相关推荐















