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

相关推荐
阿狸猿18 小时前
单元测试中静态测试、动态测试及白盒测试、回归测试实践
单元测试·软考
Max_uuc18 小时前
【工程心法】从“在板盲调”到“云端验证”:嵌入式单元测试与 TDD 的工程化革命
单元测试·tdd
feathered-feathered2 天前
测试实战【用例设计】自己写的项目+功能测试(1)
java·服务器·后端·功能测试·jmeter·单元测试·压力测试
测试渣2 天前
持续集成中的自动化测试框架优化实战指南
python·ci/cd·单元测试·自动化·pytest
minh_coo2 天前
Spring单元测试之反射利器:ReflectionTestUtils
java·后端·spring·单元测试·intellij-idea
金銀銅鐵3 天前
浅解 JUnit 4 第九篇:JUnitCore (下)
junit·单元测试
A懿轩A3 天前
【Maven 构建工具】Maven + JUnit5 单元测试实战:测试级别、注解、断言与 Maven test 阶段
java·单元测试·maven
金銀銅鐵4 天前
浅解 JUnit 4 第八篇:JUnitCore (上)
junit·单元测试
派大星-?4 天前
自动化测试五模块一框架(上)
开发语言·python·测试工具·单元测试·可用性测试