携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第24天,点击查看活动详情
目录
简单介绍
JUnit 是一个Java语言的单元测试框架。它由Kent Beck和Erich Gamma建立,逐渐成为源于Kent Beck的sUnit的xUnit家族中最为成功的一个。
JUnit有它自己的JUnit扩展生态圈。多数Java的开发环境都已经集成了JUnit作为单元测试的工具。
JUnit是由 Erich Gamma 和 Kent Beck 编写的一个回归测试框架(regression testing framework)。
Junit测试是程序员测试,即所谓白盒测试,因为程序员知道被测试的软件如何(How)完成功能和完成什么样(What)的功能。
Junit是一套框架,继承TestCase类,就可以用Junit进行自动测试了。
下面我们来看看,具体集成操作。。。
一、在 pom.xml 文件中导入 Junit 相关的依赖
<!--导入Junit单元测试依赖-->
<!--SpringBootTest-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-test</artifactId>
</dependency>
<!--@RunWith-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</dependency>
<!--SpringJUnit4ClassRunner-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
</dependency>
二、新建测试类,在方法上加 test 等相关注解
package com.example.demo.test;
import com.example.demo.DemoApplication;
import com.example.demo.service.IUserService;
import lombok.extern.slf4j.Slf4j;
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.SpringJUnit4ClassRunner;
import java.util.List;
/**
*
* springboot整合 Junit 单元测试
* @author yyh
*
* java.lang.NoClassDefFoundError: org/springframework/test/context/TestContextAnnotationUtils * 我的解决方式:最近加入的几个单元测试的依赖 version 版本给去掉了,让他自动引入
* 参考博文:
* Spring Boot 进行测试提示 TestContextAnnotationUtils 错误
* https://blog.csdn.net/huyuchengus/article/details/113161506
*
*
*/
@RunWith(SpringJUnit4ClassRunner.class)//添加替换运行器的注解,帮我们加载容器类SpringJUnit4ClassRunner
@SpringBootTest(classes = DemoApplication.class)//classes属性:用于指定本程序的引导类
@Slf4j //lombok输出日志
public class SpringBootJunitTest {
@Autowired
private IUserService userService;
@Test
public void testFindAll(){
List list = userService.findAllUser();
System.out.println(list);
}
}
java.lang.NoClassDefFoundError: org/springframework/test/context/TestContextAnnotationUtils
我的解决方式:
最近加入的几个单元测试的依赖 version 版本给去掉了,让他自动引入
顺便 clean 和 刷新一下
参考博文:
Spring Boot 进行测试提示 TestContextAnnotationUtils 错误
三、点击方法,右击运行,查看结果
别忘了,首先启动项目【这个不对!无需单独启动,单元测试会自动启动下,这个和以前开发经验不一样!!!】,然后再方法进行单元测试
输出结果: