基本介绍
什么是单元测试
单元测试( unit testing),是指对软件中的最小可测试单元(一般指类中的方法)进行检查和验证的过程就叫单元测试。 单元测试是开发者编写的⼀小段代码,⽤于检验被测代码的⼀个很小的、很明确的(代码)功能是否正确。执⾏单元测试就是为了证明某段代码的执行结果是否符合我们的预期。如果测试结果符合我们的预 期,称之为测试通过,否则就是测试未通过(或者叫测试失败)。
优点
- 可以非常简单、直观、快速的测试某个功能是否正确
- 使用单元测试可以帮我们在打包的时候发现一些问题,因为在打包之前, 所有的单元测试必须通过,否则不能打包成功。
- 使用单元测试,在测试功能的时候,可以不污染连接的数据库,也就是在不对数据库进行任何改变的情况下测试功能
Spring Boot单元测试的使用
-
确认项目中已经内置了测试框架(高版本的Spring Boot会内置测试框架)
Spring Boot 项⽬创建时会默认单元测试框架 spring-boot-test,⽽这个单元测试框架主要是依靠另⼀个著名的测试框架 JUnit 实现的,打开 pom.xml 就可以看到,以下信息是 Spring Boot 项⽬创建是自动添加的:
-
生成单元测试的类
单元测试类代码, 如下:
package com.example.mybatis_demo.mapper; import com.example.mybatis_demo.model.UserInfo; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import javax.annotation.Resource; import static org.junit.jupiter.api.Assertions.*; class UserMapperTest { @Test void getUserById() { UserInfo userInfo = userMapper.getUserById(2); Assertions.assertNotNull(userInfo); // 断言 System.out.println(userInfo); } } -
在单元测试类添加@SpringBootTest注解, 断言和业务代码
package com.example.mybatis_demo.mapper; import com.example.mybatis_demo.model.UserInfo; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import javax.annotation.Resource; import static org.junit.jupiter.api.Assertions.*; @SpringBootTest // 该注解表示当前单元测试运行在Spring Boot中 class UserMapperTest { @Resource // @Autowired 由于UserMapper加了@Mapper注解(@Mapper来自Mybatis), 而且 @Autowired是来自Spring, // 而Spring不支持 MyBatis的@Mapper的, 所以这里可能会报错, 但这是误报, 可以 // 正常运行. 只有@Mapper会出现这个问题 private UserMapper userMapper; @Test void getUserById() { UserInfo userInfo = userMapper.getUserById(2); Assertions.assertNotNull(userInfo); // 断言 System.out.println(userInfo); } }
扩展
-
简单的断言说明
如果断言失败, 则后面的代码都不会执行
-
专业版@Mapper和@Autowired不兼容的问题
-
问题描述:
-
问题解决:
@Autowired 由于UserMapper加了@Mapper注解(@Mapper来自Mybatis), 而且@Autowired是来自Spring, 而Spring不支持 MyBatis的@Mapper的, 所以这里可能会报错, 但这是误报, 可以正常运行. 只有@Mapper会出现这个问题. 其他注解, 例如@Service(因为它是来自Spring的).
但是官方支持@Mapper, 也就是说来自JDK的@Resource不会和@Mapper出现不兼容问题.
总结: @Autowired来自Spring, @Mapper来自MyBatis, 所以有可能出现不兼容的问题, 解决方案使用JDK提供的@Resource来注入Mapper.
-