IDEA集成SpringBoot自动生成单元测试和断言开发

1、IDEA生成单元测试流程

在需要测试的接口文件中右键 -> go to -> test subject ->create test

 然后勾选需要测试的方法 -> ok,就在同级包中生产一个test文件,然后补充测试逻辑:

import net.xdclass.xdvidio.domain.Video;
import net.xdclass.xdvidio.mapper.VideoMapper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import javax.swing.*;

import java.util.List;

import static org.junit.Assert.*;

/**
 * @Author Pandas
 * @Date 2020/4/12 22:54
 * @Version 1.0
 * @Description 断言测试
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class VideoServiceTest {

    @Autowired
    private VideoService videoService;

    @Test
    public void findAll() {
        List<Video> list=videoService.findAll();
        assertNotNull(list);//断言
        for (Video video:list){
            System.out.println(video.getTitle());
        }
    }

    @Test
    public void findById() {
        Video video=videoService.findById(1);
        assertNotNull(video);
    }

    @Test
    public void update() {
    }

    @Test
    public void delete() {
    }

    @Test
    public void save() {
    }
}

2、核心注解:

需要在测试类之上加入以下两个注解

@RunWith(SpringRunner.class)//告诉java你这个类通过用什么运行环境运行
@SpringBootTest

3、断言开发

 断言关键字:

assert

,是jdk1.4后加入的新功能。

它主要使用在代码开发和测试时期,用于对某些关键数据的判断,如果这个关键数据不是你程序所预期的数据,程序就提出警告或退出。

语法规则:

assert expression;  //expression代表一个布尔类型的表达式,如果为真,就继续正常运行,如果为假,程序退出
assert expression1 : expression2;//expression1是一个布尔表达式,expression2是一个基本类型或者Object类型,如果expression1为真,则程序忽略expression2继续运行;如果expression1为假,则运行expression2,然后退出程序。

org.junit包中的Assert类中提供了一些常用的断言方法,比如文中的方法:

assertNotNull(video);//若对象不为空,则正常;若空,则异常,断言失败

其源码实现:

    static public void assertNotNull(Object object) {
        assertNotNull(null, object);
    }

    static public void assertNotNull(String message, Object object) {
        assertTrue(message, object != null);
    }

    static public void assertTrue(String message, boolean condition) {
        if (!condition) {
            fail(message);
        }
    }
//
     static public void fail(String message) {
        if (message == null) {
            throw new AssertionError();
        }
        throw new AssertionError(message);
    }

    public AssertionError(Object detailMessage) {
        this(String.valueOf(detailMessage));
        if (detailMessage instanceof Throwable)
            initCause((Throwable) detailMessage);
    }

assertNotNull本质是assertTrue的二次封装,而assertTrue其实就是带messageif语句。。。

源码是个好东西,多看多想,好多方法都是多次封装的俄罗斯套娃。

 

猜你喜欢

转载自www.cnblogs.com/jwmdlm/p/12688885.html
今日推荐