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

相关推荐
一个快乐的小测试1 天前
JUnit-自动化测试框架
java·junit·单元测试·自动化
长路 ㅤ   2 天前
Java单元测试JUnit
junit·单元测试·springboot·注解·断言
chao_7892 天前
pytest 实战演练【pytest】
自动化测试·单元测试·自动化·pytest
你的人类朋友4 天前
【✈️速通】什么是SIT,什么是UAT?
后端·单元测试·测试
嵌入式-老费4 天前
LVGL应用和部署(用lua做测试)
单元测试
甜鲸鱼4 天前
在Maven多模块项目中进行跨模块的SpringBoot单元测试
spring boot·单元测试·maven
车载测试工程师5 天前
汽车功能安全-软件单元验证 (Software Unit Verification)【用例导出方法、输出物】8
网络·功能测试·安全·车载系统·单元测试·汽车
测试老哥6 天前
软件测试之单元测试
自动化测试·软件测试·python·测试工具·职场和发展·单元测试·测试用例
秋千码途7 天前
小架构step系列11:单元测试引入
单元测试
新world12 天前
mybatis-plus从入门到入土(二):单元测试
单元测试·log4j·mybatis