Junit4单元测试快速上手

文章目录

在工作中我用的最多的单元测试框架是Junit4。通常在写DAO、Service、Web层代码的时候都会进行单元测试,方便后续编码,前端甩锅。

POM依赖引入

xml 复制代码
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>

业务层测试代码

java 复制代码
package org.example.service;

import org.example.mapper.UserMapper;
import org.example.pojo.User;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import javax.annotation.Resource;
import java.util.List;

@RunWith(SpringRunner.class)
@SpringBootTest
class UserServiceTest {
    @Resource
    private UserMapper userMapper;

    @Test
    void getAllUsers() {
       
    }
}

Web层测试代码

java 复制代码
package org.example.controller;

import org.example.pojo.User;
import org.example.service.UserService;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import javax.annotation.Resource;

import static org.junit.jupiter.api.Assertions.*;
@RunWith(SpringRunner.class)
@SpringBootTest
class UserControllerTest {
    @Resource
    private UserService userService;

    @Test
    void getUserById() {
        
    }
}

生成测试类文件

可以借助IDEA直接Go to生成业务代码的测试类

相关推荐
测试员周周15 小时前
【jev应用到测试】94 条 UI 报错交给 Jev,三档判对 85.1%,开单闸门定在 0.6
人工智能·python·测试工具·单元测试·测试用例
ebiobiz2 天前
STM32F4 Unity 单元测试与多次测试失败率统计详细步骤
stm32·unity·单元测试
Glitch4044 天前
LLM 数据管线缺陷实录:两个单元测试无法覆盖的运行时问题
单元测试
钱栈up4 天前
全量 21 个失败、单跑全绿:泄漏进连接池的 SQL 变量
sql·单元测试·测试
冬奇Lab4 天前
LLM 自动化测试系列(03):单元测试生成——TestGen-LLM 与 Qodo Cover
人工智能·单元测试·测试
慧都小项10 天前
Python 跨文件重构怎么验证?PyCharm 用法查找、重构预览与测试流程
python·重构·pycharm·单元测试
2302_8057710713 天前
Day13Jmeter数据驱动
功能测试·单元测试·测试用例·需求分析·测试
2302_8057710713 天前
Day14Jmeter+数据库的操作
功能测试·单元测试·测试用例·需求分析
清风~徐~来13 天前
【软件测试】allure 测试报告模块
单元测试
2302_8057710714 天前
Day18在接口自动化测试中引入pytest用例管理框架
功能测试·单元测试·测试用例·需求分析·测试