在Spring使用junit注解进行单元测试

在Spring中可以使用junit配合注解进行单元测试

零、添加jar包:

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
    </dependency>

 

 

一、常用注解

1、@RunWith(SpringJUnit4ClassRunner.class),让测试运行于spring测试环境
2、@ContextConfiguration 用来指定加载的Spring配置文件的位置,会加载默认配置文件,  
@ContextConfiguration 注解有以下两个常用的属性:
locations:可以通过该属性手工指定 Spring 配置文件所在的位置,可以指定一个或多个 Spring 配置文件用,分开。
inheritLocations:是否要继承父测试用例类中的 Spring 配置文件,默认为 true。

二、常用方法

1、assertEquals(Object expected, Object actual)

比较两者是否相等

2. assertTrue(boolean condition)

比较参数是否为 true

 

三、配置文件:

可以在 测试类中添加注解,引用已有的配置文件 :

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:spring-mvc.xml","classpath:spring-mybatis.xml"})

 

也可以在项目的 src/test/resources文件夹下, 新增测试专用的配置文件,再引用:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath*:spring-test-service.xml")

spring-test-service.xml 如下:

复制代码
<?xml version="1.0" encoding="UTF-8"?>
<beans
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://www.springframework.org/schema/beans"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
                        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">

  <!-- 引入src/main/resources 已有的配置文件  -->
  <!-- 以下的 META-INF/spring 是resuource文件夹下的xml文件的路径,如果是其他的文件名,自行修改 -->
  <import resource="classpath*:META-INF/spring/*.xml"/>

  <!-- support message international -->
  <aop:aspectj-autoproxy/>

</beans>
复制代码

 

 

四、示例代码 (仅显示测试代码,xml配置、Service层代码略)

复制代码
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:spring-mvc.xml","classpath:spring-mybatis.xml"})
public class UserServiceImplTest {

    @Autowired
    private UserServiceImpl userService;

@Before
public void before() throws Exception { 
} 

@After
public void after() throws Exception { 
} 


@Test
public void testGetUserById() throws Exception { 
//TODO: Test goes here...
    Assert.assertEquals( "lin" , userService.getUserById(2).getUserName());
} 


} 

SpringBoot单元测试,详情见: https://www.cnblogs.com/expiator/p/8651045.html
复制代码

 

posted on   乐之者v  阅读(589)  评论(0编辑  收藏  举报

编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示