Spring04 第四 spring整合Junit
3 Spring整合junit
3.1 原始Junit测试spring的问题
原始junit测试Spring的问题,在测试类中,每个测试方法都有以下两行代码:
@Test
public void Test(){
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
UserService us= ac.getBean("UserService"UserService.class);
}
这两行代码的作用是获取容器,如果不写的话,直接会提示空指针异常。所以又不能轻易删掉。
上述问题解决思路•让SpringJunit负责创建Spring容器,但是需要将配置文件的名称告诉它•将需要进行测试Bean直接在测试类中进行注入
3.2 Spring 集成Junit
Spring集成Junit步骤
①导入spring集成Junit的坐标以及junit的坐标(之前测试已导)
②使用@Runwith注解替换原来的运行期
③使用@ContextConfiguration指定配置文件或配置类
④使用@Autowired注入需要测试的对象
⑤创建测试方法进行测试
(第一步)导入spring集成Junit的坐标<!--此处需要注意的是,spring5 及以上版本要求junit 的版本必须是4.12 及以上-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
(第二步)使用@Runwith注解替换原来的运行期@RunWith(SpringJUnit4ClassRunner.class)
public class SpringJunitTest {}
(第三步)使用@ContextConfiguration指定配置文件或配置类@RunWith(SpringJUnit4ClassRunner.class)
//加载spring核心配置文件
//@ContextConfiguration(value = {"classpath:applicationContext.xml"})
//加载spring核心配置类@
ContextConfiguration(classes = {SpringConfiguration.class})
public class SpringJunitTest {}
(第四步)使用@Autowired注入需要测试的对象@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {SpringConfiguration.class})
public class SpringJunitTest {
@Autowiredprivate UserService userService;
(第五步)写测试方法
@Test
public void testUserService(){
userService.save();}
}
【推荐】国内首个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 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构