栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SpringBoot整合junit测试案例

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringBoot整合junit测试案例

1.之前开发项目是不要求写单测的,最近公司管理严格需要对开发的功能编写单测,所以在此记录下springboot对junit的整合以及使用的方式

2.引入需要用到的依赖jar包,一般创建好springboot项目都会自带test依赖

3.一般我们新建的springboot项目都带有测试包,我们直接使用,在里面编写测试类即可

 4.因为项目中可能会存在很多测试类,那么就会存在很多注解重复被添加的冗余,因此我们写一个基类,其他测试类只需要继承基类就行,基类名字就叫做baseTestClass,如下:

package com.example.mybatisplus;

import org.junit.After;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.WebAppConfiguration;

@SpringBootTest
@WebAppConfiguration
@RunWith(SpringRunner.class)
public class baseTestClass {

    @Before
    public void init(){
        System.out.println("before");
    }

    @After
    public void after(){
        System.out.println("after");
    }
}

 5.然后就可以编写测试类了,测试类里面注入service层,然后通过断言进行返回数据的判断,下面就是我测试的一个查询接口的测试类:

package com.example.mybatisplus;

import com.example.mybatisplus.entity.Employee;
import com.example.mybatisplus.service.EmployeeService;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;

import static org.junit.Assert.assertEquals;

public class OperateDataTest extends baseTestClass{
    @Autowired
    private EmployeeService employeeService;

    @Test
    public void testQueryById(){
        Employee employee = employeeService.selectById("2");
        assertEquals("Jerry",employee.getLastName());
        assertEquals("jerry@qq.com",employee.getEmail());
    }
}

注意:由于业务逻辑层都是要求写在service层,所以我们这里就注入了service进行测试。

那有同学要问了,我直接测试controller层可以吗?答案肯定是可以的,下面我就演示一下直接注入controller层,其实和service是一样的,如下所示:

package com.example.mybatisplus;

import com.example.mybatisplus.controller.MybatisPlusController;
import com.example.mybatisplus.entity.Employee;
import com.example.mybatisplus.service.EmployeeService;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

import static org.junit.Assert.assertEquals;

public class OperateDataTest extends baseTestClass{
    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private MybatisPlusController mybatisPlusController;

    @Test
    public void testQueryById(){
        Employee employee = employeeService.selectById("2");
        assertEquals("Jerry",employee.getLastName());
        assertEquals("jerry@qq.com",employee.getEmail());
    }

    @Test
    public void testController(){
        List employeeList = mybatisPlusController.queryList();
        System.out.println("employee="+employeeList.get(0));

    }
}

项目代码已上传csdn,下载链接:springboot整合junit测试用例demo-Java文档类资源-CSDN下载

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/715940.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号