spring boot junit controller
MockMvc 来自Spring Test,它允许您通过一组方便的builder类向 DispatcherServlet 发送HTTP请求,并对结果作出断言。请注意,@AutoConfigureMockMvc 与@SpringBootTest 需要一起注入一个MockMvc 实例。在使用@SpringBootTest 时候,我们需要创建整个应用程序上下文。
示例代码:
import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; 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.annotation.Rollback; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.result.MockMvcResultMatchers; import org.springframework.transaction.annotation.Transactional; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @RunWith(SpringRunner.class)//表示使用Spring Test组件进行单元测试 @Transactional//回滚所有增删改 @SpringBootTest @AutoConfigureMockMvc//注入一个MockMvc实例 public class DingControllerTest { private final static Logger logger = LoggerFactory.getLogger(DingControllerTest.class); @Autowired private MockMvc mockMvc; @Test @Rollback(false)//取消回滚public void getSignature() throws Exception { String responseString = mockMvc.perform( post("/ding/getSignature")//请求的url,请求的方法是post .contentType(MediaType.APPLICATION_JSON)//数据的格式 .param("url", "https://www.baidu.com/")//添加参数 ).andExpect(status().isOk())//返回的状态是200 .andExpect(MockMvcResultMatchers.jsonPath("$.state").value(1)) //判断某返回值是否符合预期 .andDo(print())//打印出请求和相应的内容 .andReturn().getResponse().getContentAsString();//将相应的数据转换为字符串 logger.info("post方法/ding/getSignature,{}", responseString); } }
官方文档:
https://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#boot-features-testing-spring-boot-applications-testing-with-mock-environment
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律