15、springboot整合 Junit 单元测试

目录

简单介绍

一、在 pom.xml 文件中导入 Junit 相关的依赖

二、新建测试类,在方法上加 test 等相关注解

三、点击方法,右击运行,查看结果


简单介绍

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 错误

https://blog.csdn.net/huyuchengus/article/details/113161506

三、点击方法,右击运行,查看结果

别忘了,首先启动项目【这个不对!无需单独启动,单元测试会自动启动下,这个和以前开发经验不一样!!!】,然后再方法进行单元测试

输出结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

被开发耽误的大厨

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值