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生成业务代码的测试类

相关推荐
CeshirenTester4 小时前
Playwright元素定位详解:8种定位策略实战指南
人工智能·功能测试·程序人生·单元测试·自动化
行走的陀螺仪17 小时前
Vue3 项目单元测试全指南:价值、Vitest 落地与提效方案
开发语言·前端·单元测试·html5·vitest
fzm52981 天前
C语言单元测试在嵌入式软件开发中的作用及专业工具的应用
自动化测试·单元测试·汽车·嵌入式·白盒测试
川石课堂软件测试1 天前
Mysql中触发器使用详详详详详解~
数据库·redis·功能测试·mysql·oracle·单元测试·自动化
程序员汤圆1 天前
软件测试面试题总结【含答案】
测试工具·单元测试·测试用例
卓码软件测评2 天前
第三方软件CMA/CNAS测评机构:【Apifox的自定义加密和签名的安全测试技巧】
测试工具·ci/cd·单元测试·测试用例·压力测试
IMPYLH2 天前
Lua 的 Debug(调试) 模块
开发语言·笔记·python·单元测试·lua·fastapi
测试开发Kevin2 天前
超级实用!汇总pytest中那些常用的参数
单元测试·pytest
charlie1145141912 天前
编写INI Parser 测试完整指南 - 从零开始
开发语言·c++·笔记·学习·算法·单元测试·测试
路修远i3 天前
前端单元测试
前端·单元测试