关于SpringBoot的测试类的用法

在实际开发过程中 有时测试一个东西 并不需要启动整个项目 此时就只需要启动一个测试类即可。

在SpringBoot中 启动单元测试很简单:

添加maven依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <version>2.7.2</version>
    <scope>test</scope>
</dependency>
<!-- 单元测试依赖 -->
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
</dependency>

用法

@RunWith(SpringRunner.class) @SpringBootTest 这样在单元测试里就可以直接启动spring容器了。

下面举个例子

public class liwenzhuTest {
    @Autowired
    private RedissonClient redissonClient;
    @Test
    public void testRedisson() throws InterruptedException {
        //获取锁(可重入) 指定锁的名称
        RLock lock = redissonClient.getLock("anyLock");
        //尝试获取锁 参数为获取锁的最大等待时间(期间会重试) 锁自动释放时间 时间单位
        boolean success = lock.tryLock(1, 10, TimeUnit.SECONDS);
        try {
            //判断获取锁成功
            if (success){
                System.out.println("执行业务");
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            //释放锁
            lock.unlock();
        }
    }
}

当然直接贴我的代码是不能运行的 因为我有redisson的配置 这个redisson就是注入进来的,就是拿这个举例子 这个就是大部分情况下都测试类的使用啦 如果对你有帮助 点给👍吧

经验分享 程序员 微信小程序 职场和发展