在没有代码生成工具或尝试一门新的
ORM
框架时,当我们希望不去另外写 Service 和 Controller 来验证 DAO 层的代码不希望只通过接口请求的方式来验证时,这时候单元测试的方式就可以帮助我们满足这一需求。
在我们开发Web应用时,经常会直接去观察结果进行测试。虽然也是一种方式,但是并不严谨。作为开发者编写测试代码来测试自己所写的业务逻辑是,以提高代码的质量、降低错误方法的概率以及进行性能测试等。经常作为开发这写的最多就是单元测试。引入
spring-boot-starter-test
SpringBoot的测试依赖。该依赖会引入JUnit的测试包,也是我们用的做多的单元测试包。而Spring Boot在此基础上做了很多增强,支持很多方面的测试,例如JPA,MongoDB,Spring MVC(REST)和Redis等。接下来主要是测试业务逻辑层的代码,REST和Mock测试。
- 以下测试时均不用另外启动应用
springboot-2.7.1
默认绑定junit5
而不再是junit4
,后期若想使用junit4
也可以Add JUnit4 to classpath
- 若数据库密码配置是密文,解密密钥在启动参数里,先改回明文再测(否则会
fail to load ApplicationContext
) - 新版本的单测都有对应的专门注解,它们内置了启动环境容器。不再需要另外写
@RunWith(SpringRunner.class)
或@SpringBootTest
注解说明
专门的注解 | 提供方 | 说明 | |
---|---|---|---|
JPA | @DataJpaTest | org.springframework.boot.test | 会默认扫描@Entity和@Repository注解 |
MyBatis | @MybatisTest | com.baomidou.mybatis-spring-boot-starter-test | 官方提供支持 |
MyBatis-Plus | @MybatisPlusTest | com.baomidou.mybatis-plus-boot-starter-test | 官方提供支持 |
其它注解说明:
@AutoConfigureTestDatabase | 会自动配置一个基于内存的数据库,只要依赖中含有一个可用的基于内存的嵌入式数据库。 结果会自动回滚,不会发生数据库变化。若使用实际数据库可设置 replace值为Replace.NONE |
|
@Rollback | 是否回滚,通过设置 value 为 true or false 决定测试数据是否写入数据库 |
1.打印版单测
package com.imooc;
import org.junit.jupiter.api.Test;
/**
*
*/
public class LoggerTest {
@Test
public void test1() {
System.out.println("=========");
}
}
2
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Logger2Test {
// 选择org.slf4j下的接口
private final Logger logger = LoggerFactory.getLogger(Logger2Test.class);
@Test
public void test1() {
logger.info("info...");
}
}
2.测试 JPA
版本:
junit5
springboot-2.7.2` 不启动应用 数据库已配
目录:
@Repository
注解@DataJpaTest
注解@AutoConfigureTestDatabase
注解
依赖
spring-boot-starter-web (2.7.2)
spring-boot-starter-test (with junit5)
mysql-connector-java (8.0)
spring-boot-starter-data-jpa
h2 # 构建基于内存的数据库环境
步骤:
@DataJpaTest
注解@AutoConfigureTestDatabase
注解:
最终元素(已验证)
/
@Data
@Entity // JPA
public class ProductCategory implements Serializable {
// ...
}
/
@Repository
public interface ProductCategoryRepository extends JpaRepository<ProductCategory, Integer> {
}
/
@DataJpaTest // 只启动JPA组件不启动全环境
@AutoConfigureTestDatabase(replace= AutoConfigureTestDatabase.Replace.NONE) // 创建一个基于内存的数据库环境
class ProductCategoryRepositoryTest {
@Autowired
ProductCategoryRepository repository;
@Test
public void testFindById() {
Optional<ProductCategory> byId = repository.findById(1);
System.out.println("查询结果:");
System.out.println(byId);
}
}
控制台
查询结果:
Optional[ProductCategory(categoryId=1, categoryType=1, categoryName=热销榜, createTime=2022-08-03 06:37:48.0, updateTime=2022-08-03 06:37:48.0)]
参考资料:
(方法讲解)https://howtodoinjava.com/spring-boot2/testing/datajpatest-annotation/#1-repository-annotation