SpringBoot整合junit测试案例

SpringBoot整合junit测试案例,第1张

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("[email protected]",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("[email protected]",employee.getEmail());
    }

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

    }
}

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

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5712579.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存