SpringBoot+Maven项目进行junit单元测试-入门篇

本文介绍了如何在SpringBoot项目中使用Maven和JUnit进行单元测试的配置与安装,包括设置JunitGenerator插件,配置测试目录,以及编写和运行测试用例。示例代码展示了如何自动生成并执行StudentServiceImpl的测试类,通过断言确保loadStudentInfos方法的正确性。此外,文章还提供了相关依赖的引入和测试类的生成步骤。
摘要由CSDN通过智能技术生成

SpringBoot+Maven项目进行junit单元测试-入门篇

配置与安装

  1. 安装插件 File - Settings - Plugins 搜索JunitGenerator V2.0 然后点Install,再进入Other Settings 设置Output Path 中测试文件存放位置(我的位置是src/test,所以我这里添加了…/…/),然后选择Junit4 设置默认想要自动生成的内容
    在这里插入图片描述
    在这里插入图片描述
    在这里插入图片描述
    方便复制~附上代码
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.List;
import java.util.Random;

@RunWith(SpringRunner.class)
@SpringBootTest
public class StudentServiceImplTest {
    @Autowired
    StudentServiceImpl studentService;

    @Before
    public void before() throws Exception { 
    } 

    @After
    public void after() throws Exception { 
    } 

    /**
    * 查询学生信息
    * Method: loadStudentInfos() 
    */ 
    @Test
    public void testLoadStudentInfos() throws Exception {
        List<Student> list = studentService.loadStudentInfos();
        Assert.assertThat(list, Matchers.notNullValue());
    } 
 }
  1. pom.xml引入jar
		<!-- junit相关jar包 -->
        <dependency>
            <groupId>org.hamcrest</groupId>
            <artifactId>hamcrest-core</artifactId>
            <version>1.3</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
  1. 配置测试文件目录 File - Project Structure - Modules - 选择test文件夹在点击Tests
    在这里插入图片描述
  2. 开始自动生成test文件,选中要测试的类 alt+inser(或者鼠标右击) - Generater… - JUnit Test - JUnit 4 就会自动在test文件夹下对应包下生成对应名字的测试类
    在这里插入图片描述
    在这里插入图片描述
    然后直接运行就好了。绿油油的通过~
    在这里插入图片描述
    基本上都是自动生成的,所以写的很少,也很方便,入个门是不是超级简单,关于Assert断言,暂时不多说,可以自行百度(主要是我这个小白也还没搞明白)

自己写了一个小demo,地址是https://download.csdn.net/download/notHavaBug/14949381?spm=1001.2014.3001.5503

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值