道阻且长,行则将至,走慢一点没关系,不停下就好了.|

Ac_c0mpany丶

园龄:3年7个月粉丝:6关注:3

2022-11-29 10:27阅读: 90评论: 0推荐: 0

Spring Boot测试

Spring Boot测试

一、了解单元测试

单元测试(Unit Test)是为了检验程序的正确性。一个单元可能是单个程序、类、对象、方法等,它是应用程序的最小可测试部件。

单元测试的必要性:

  • 预防Bug
  • 快速定位Bug
  • 提高代码质量,减少耦合
  • 减少调试时间
  • 减少重构的风险

二、Spring Boot的测试库

Spring Boot提供了spring-boot-starter-test启动器。通过它,能引入一些有用的测试库,如下所示。

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

三、Junit

四、断言测试Assert(了解)

package tech.pdai.junit4;

import org.junit.Assert;
import org.junit.Test;

/**
 * Assertion Test.
 */
public class AssertionTest {

    @Test
    public void test() {
        String obj1 = "junit";
        String obj2 = "junit";
        String obj3 = "test";
        String obj4 = "test";
        String obj5 = null;

        int var1 = 1;
        int var2 = 2;

        int[] array1 = {1, 2, 3};
        int[] array2 = {1, 2, 3};

        Assert.assertEquals(obj1, obj2);

        Assert.assertSame(obj3, obj4);
        Assert.assertNotSame(obj2, obj4);

        Assert.assertNotNull(obj1);
        Assert.assertNull(obj5);

        Assert.assertTrue(var1 < var2);
        Assert.assertFalse(var1 > var2);

        Assert.assertArrayEquals(array1, array2);

    }
}

五、测试的回滚

在单元测试可能会产生垃圾数据,可以开启事务功能进行回滚——在方法或类头部添加注解@Transactional即可。在类上添加了注解@Transactional,测试完成后就可以回滚,不会产生垃圾数据。如果要关闭回滚,则只要加上注解@Rollback(false)即可。

六、Spring Boot快速创建测试单元

代码解释:

  • @SpringBootTest:是Spring Boot用于测试的注解,可指定入口类或测试环境等。
  • @RunWith(SpringRunner.class):让测试运行于Spring的测试环境。
  • @Test:表示为一个测试单元。

本文作者:Ac_c0mpany丶

本文链接:https://www.cnblogs.com/keyongkang/p/16934685.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   Ac_c0mpany丶  阅读(90)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起
  1. 1 You Are My Sunshine REOL
You Are My Sunshine - REOL
00:00 / 00:00
An audio error has occurred.

作曲 : Traditional

You are my sunshine

My only sunshine.

You make me happy

When skies are gray.

You'll never know, dear,

How much I love you.

Please don't take my sunshine away

The other night, dear,

When I lay sleeping

I dreamed I held you in my arms.

When I awoke, dear,

I was mistaken

So I hung my head and cried.

You are my sunshine,

My only sunshine.

You make me happy

When skies are gray.

You'll never know, dear,

How much I love you.

Please don't take my sunshine away.

You are my sunshine,

My only sunshine

You make me happy

When skies are gray.

You'll never know, dear

How much I love you

Please don't take my sunshine away

Please don't take my sunshine away.

Please don't take my sunshine away.