SpringBoot&Spring单元测试
SpringBoot
一、Service层Junit单元测试
需要的jar包
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency>
Springboot 1.3的版本与1.4的版本稍有不同
1.3及以下版本:
package com.suning.epp.fmasosweb.service.impl; import com.suning.epp.fmasosweb.FmasosWebApplication; import com.suning.epp.fmasosweb.result.RankGenreResult; import com.suning.epp.fmasosweb.service.intf.CommentService; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import java.util.HashMap; import java.util.List; import java.util.Map; /** * 〈一句话功能简述〉 * 〈功能详细描述〉 * * @author 17090889 * @see [相关类/方法](可选) * @since [产品/模块版本] (可选) */ @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = FmasosWebApplication.class) @WebAppConfiguration public class CommentServiceImplTest { @Autowired private CommentService commentService; @Test public void queryAppRankGenreResultTest() { Map<String, String> param = new HashMap<>(); List<RankGenreResult> rankGenreResultList = commentService.queryAppRankGenreResult(param); System.out.println(rankGenreResultList); } }
注解解释:
@SpringBootTest
:获取启动类,加载配置,寻找主配置启动类(被 @SpringBootApplication 注解的)
@RunWith(SpringRunner.class)
:让JUnit运行Spring的测试环境,获得Spring环境的上下文的支持
1.4及以上版本:
@SpringApplicationConfiguration 注解标记为过时了
提供了注解@SpringBootTest
使用SpringRunner 替代 SpringJUnit4ClassRunner
package com.suning.epp.fmasosweb.service.impl; import com.suning.epp.fmasosweb.result.RankGenreResult; import com.suning.epp.fmasosweb.service.intf.CommentService; 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.test.context.junit4.SpringRunner; import java.util.HashMap; import java.util.List; import java.util.Map; /** * 〈一句话功能简述〉 * 〈功能详细描述〉 * * @author 17090889 * @see [相关类/方法](可选) * @since [产品/模块版本] (可选) */ @RunWith(SpringRunner.class) @SpringBootTest public class CommentServiceImplTest { @Autowired private CommentService commentService; @Test public void queryAppRankGenreResultTest() { Map<String, String> param = new HashMap<>(); List<RankGenreResult> rankGenreResultList = commentService.queryAppRankGenreResult(param); System.out.println(rankGenreResultList); } }
经测试,2.4.2版本不加 @RunWith(SpringRunner.class) 也行
二、Controller层Mock测试
Mock介绍:
1、什么是Mock?
在面向对象的程序设计中,模拟对象(mock object)是以可控的方式模拟真实对象行为的假对象。
在编程过程中,通常通过模拟一些输入数据,来验证程序是否达到预期效果
2、为什么使用Mock对象?
使用模拟对象,可以模拟复杂的、真实的对象行为。如果在单元测试中无法使用真实对象,可采用模拟对象进行替代
3、MockMvc的概念
MockMvc是由spring-test包提供,实现了对Http请求的模拟,能够直接使用网络的形式,转换到Controller的调用,使得测试速度快、不依赖网络环境。同时提供了一套验证的工具,结果的验证十分方便。
接口MockMvcBuilder,提供一个唯一的build方法,用来构造MockMvc。主要有两个实现:StandaloneMockMvcBuilder和DefaultMockMvcBuilder
4、MockMvc的基本步骤
(1) mockMvc.perform执行一个请求。
(2) MockMvcRequestBuilders.get(“XXX”)构造一个请求,Post请求使用post方法。
(3) ResultActions.param添加请求传值
(4) ResultActions.accept()设置返回类型
(5) ResultActions.andExpect添加执行完成后的断言。
(6) ResultActions.andDo添加一个结果处理器,表示要对结果做点什么事情,比如处使用print()输出整个响应结果信息。
(7) ResultActions.andReturn表示执行完成后返回相应的结果
1.3及以下版本:
package com.suning.epp.fmasosadmin.mapper; import com.suning.epp.fmasos.FmasosApplication; 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.SpringApplicationConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; 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.transaction.annotation.Transactional; import org.springframework.web.context.WebApplicationContext; /** * 〈一句话功能简述〉 * 〈功能详细描述〉 * * @author 17090889 * @see [相关类/方法](可选) * @since [产品/模块版本] (可选) */ @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = FmasosApplication.class) @WebAppConfiguration @Transactional public class ProcessorServiceTest { // @Autowired // @Qualifier("commentProcessorServiceImpl") // private CommentProcessorService commentProcessorServiceImpl; @Autowired private WebApplicationContext webApplicationContext; private MockMvc mockMvc; @Before public void setUp() throws Exception { //构造MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build(); } @Test public void spiderRun() throws Exception { String url = "/comment/spiderRun2"; mockMvc.perform(MockMvcRequestBuilders.get(url)); } }
1.4及以上版本:
import org.junit.Test; import org.junit.runner.RunWith; 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.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.result.MockMvcResultMatchers; import static org.junit.Assert.*; @RunWith(SpringRunner.class) @SpringBootTest @AutoConfigureMockMvc public class CommentControllerTest { @Autowired private MockMvc mvc; @Test public void spiderRun() throws Exception { mvc.perform(MockMvcRequestBuilders.get("/spiderRun")) .andExpect(MockMvcResultMatchers.status().isOk()); //.andExpect(MockMvcResultMatchers.content().string("365")); //测试接口返回内容 } }
Spring
1、需要在test/resources下新建spring配置文件,扫描注入测试需要的所有bean及依赖bean
/** * @author yangyongjie * @date 2020/2/26 * @desc */ @RunWith(SpringJUnit4ClassRunner.class) // 启动 Spring 对测试类的支持 @ContextConfiguration("classpath:spring-*.xml") // 指定 Spring 配置文件或者配置类的位置,classpath路径为test/resources public class AutoRenewCheckTaskTest { @Autowired private AutoRenewCheckTask autoRenewCheckTask; @Test public void executeTest(){ autoRenewCheckTask.execute(); } }
2、不在test/resources下新建spring配置文件也可,使用main/resources 下的Spring配置文件,此时需要使用 @ContextConfiguration 注解的 locations 属性指定配置文件在计算机上的绝对路径,如:
@RunWith(SpringJUnit4ClassRunner.class) // 启动 Spring 对测试类的支持 @ContextConfiguration(locations = {"file:D:\\IdeaProjects\\taskModuleOptimize\\bssadmin-task\\src\\main\\webapp\\WEB-INF\\spring\\spring-*.xml"}) // 指定 Spring 配置文件或者配置类的位置 public class AutoRenewCheckTaskTest { @Autowired private AutoRenewCheckTask autoRenewCheckTask; @Test public void executeTest(){ autoRenewCheckTask.execute(); } }
END.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· AI与.NET技术实操系列(六):基于图像分类模型对图像进行分类