java | junit | 基本+技巧

1.参考链接

1.1 单测概念

https://medium.com/@lathasreeseeni/junit-2d9857773e8

1.2 高级技巧

https://symflower.com/en/company/blog/2023/how-to-write-junit-test-cases-advanced-techniques/

  • assertThrows:
    有时候,我们的方法,需要抛出错误。例如,deleTask(id) 中,id不存在的时候,需要抛错。那么在单测中,就可以用assertThrows。
  • @ParameterizedTest:
    场景:多个不同输入对应的结果
java 复制代码
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import static org.junit.jupiter.api.Assertions.assertEquals;

public class CalculatorTest {
    
    @ParameterizedTest
    @CsvSource({
        "1, 2, 3",
        "0, 0, 0",
        "-1, 1, 0",
        "100, -100, 0"
    })
    void testAdd(int a, int b, int expected) {
        Calculator calculator = new Calculator();
        int result = calculator.add(a, b);
        assertEquals(expected, result);
    }
}
  • assumeTrue(condition)
    condition正确再执行下面的语句

-assumeFalse

condition错误再执行下面的语句,也就是说,condition为true则不会执行下面的语句。

java 复制代码
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assume.assumeTrue;

public class MyTest {
    
    @Test
    public void testAdd() {
        assumeTrue(2 + 2 == 4);
        // ↑2+2=4这个假设是正确的,执行↓ 
        assertEquals(4, Calculator.add(2, 2));
    }
    
}
  • @Parameterized.Parameters
    构造多个参数,可以是对象的参数
java 复制代码
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

import java.util.Arrays;
import java.util.Collection;

import static org.junit.Assert.assertEquals;


@RunWith(Parameterized.class)
public class CalculatorTest {

    private int a, b, expected;

    public CalculatorTest(int a, int b, int expected) {
        this.a = a;
        this.b = b;
        this.expected = expected;
    }

    @Parameterized.Parameters
    public static Collection<Object[]> data() {
        return Arrays.asList(new Object[][]{
                {1, 1, 2},
                {2, 3, 5},
                {5, 5, 10},
                {10, 0, 10},
                {-5, 5, 0}
        });
    }

    @Test
    public void testAdd() {
        Calculator calculator = new Calculator();
        int result = calculator.add(a, b);
        assertEquals(expected, result);
    }
}
相关推荐
考虑考虑几秒前
JDK9中的takeWhile
java·后端·java ee
我科绝伦(Huanhuan Zhou)1 分钟前
MOP数据库备份脚本生成工具
前端·css·数据库
步行cgn4 分钟前
MySQL 中 DISTINCT 去重的核心注意事项详解
数据库·mysql
boy快快长大8 分钟前
【CompletableFuture】常用方法(三)
java
南棱笑笑生15 分钟前
20250617在ubuntu20.04.6下编译飞凌OK3576-C_Linux6.1.75_用户资料_R1(更新日期_20241014)
数据库
thinking-fish37 分钟前
详解JVM
java·jvm·gc
晴空月明1 小时前
Java 并发工具类核心使用场景深度解析
java
程序员岳焱1 小时前
Spring 开发中的十大常见坑及解决方案
java·后端·spring
花开月满西楼1 小时前
Android实例项目【智能家居系统】实现数据库登录注册+动画效果+网页跳转+短信发送!!!
android·数据库·智能家居
洗发水很好用1 小时前
制造部门的转型目标与场景痛点
大数据·数据库·制造