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 4 第十五篇:如何在测试方法运行前后做些事情?
junit·单元测试
金銀銅鐵1 天前
浅解 JUnit 4 第十四篇:如何实现一个 @After 注解的替代品?
junit·单元测试
金銀銅鐵1 天前
浅解 JUnit 4 第十三篇:如何实现一个 @Before 注解的替代品?(下)
junit·单元测试
金銀銅鐵4 天前
浅解 JUnit 4 第十二篇:如何生成 @Before 注解的替代品?(上)
junit·单元测试
Apifox5 天前
【测试套件】当用户说“我只想跑 P0 用例”时,我们到底在说什么
单元测试·测试·ab测试
金銀銅鐵8 天前
浅解 JUnit 4 第十一篇:@Before 注解和 @After 注解如何发挥作用?
junit·单元测试
金銀銅鐵9 天前
浅解 JUnit 4 第十篇:方法上的 @Ignore 注解
junit·单元测试
阿狸猿11 天前
单元测试中静态测试、动态测试及白盒测试、回归测试实践
单元测试·软考
Max_uuc11 天前
【工程心法】从“在板盲调”到“云端验证”:嵌入式单元测试与 TDD 的工程化革命
单元测试·tdd