SpringBoot使用MockMVC单元测试Controller
import org.junit.Before;
import org.junit.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.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(SpringRunner.class)
@SpringBootTest
public class MyControllerTest {
private MockMvc mockMvc;
@Autowired
private WebApplicationContext webApplicationContext;
@Before
public void setup() {
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
@Test
public void testMyController() throws Exception {
mockMvc.perform(MockMvcRequestBuilders.get("/myEndpoint")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andDo(print());
}
}
这段代码使用了Spring Boot的SpringRunner来运行测试,并利用MockMVC来模拟HTTP请求,测试了Controller中/myEndpoint
的GET请求是否返回正确的响应(状态码200)。在实际的测试环境中,你需要替换MyControllerTest
为你的测试类名,/myEndpoint
为你的Controller端点,并根据你的Controller的实际行为调整测试逻辑。
评论已关闭