DevOps系列文章 之 Springboot单元测试

在没有代码生成工具或尝试一门新的 ORM框架时,当我们希望不去另外写 Service 和 Controller 来验证 DAO 层的代码不希望只通过接口请求的方式来验证时,这时候单元测试的方式就可以帮助我们满足这一需求。

在我们开发Web应用时,经常会直接去观察结果进行测试。虽然也是一种方式,但是并不严谨。作为开发者编写测试代码来测试自己所写的业务逻辑是,以提高代码的质量、降低错误方法的概率以及进行性能测试等。经常作为开发这写的最多就是单元测试。引入spring-boot-starter-testSpringBoot的测试依赖。该依赖会引入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` 不启动应用 数据库已配

目录:

  1. @Repository注解
  2. @DataJpaTest 注解
  3. @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  # 构建基于内存的数据库环境

步骤:

  1. @DataJpaTest 注解
  2. @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

(实际代码)https://github.com/lokeshgupta1981/jakarta-projects/tree/master/spring-boot-projects/hibernate-examples

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Coder_Boy_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值