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.st.context.SpringBootTest;
import st.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.Title());
}
}
@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后加⼊的新功能。
它主要使⽤在代码开发和测试时期,⽤于对某些关键数据的判断,如果这个关键数据不是你程序所预期的数据,程序就提出警告或退出。
语法规则:
springboot其实就是spring
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其实就是带message的if语句。。。
源码是个好东西,多看多想,好多⽅法都是多次封装的俄罗斯套娃。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。