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);
    }
}
相关推荐
AA-代码批发V哥37 分钟前
Java五种方法批量处理List元素全解
java·list
程序员Bears3 小时前
SSM整合:Spring+SpringMVC+MyBatis完美融合实战指南
java·spring·mybatis
Channing Lewis4 小时前
SQL Server 简介和与其它数据库对比
数据库
阿文弟5 小时前
浅谈Mysql的MVCC机制(RC与RR隔离级别)
数据库·mysql
liuyang-neu5 小时前
黑马点评双拦截器和Threadlocal实现原理
java
小小数媒成员5 小时前
Unity—lua基础语法
unity·junit·lua
要睡觉_ysj5 小时前
MySQL锁机制与MVCC深度解析
数据库·mysql
csdn_aspnet5 小时前
Java 程序求圆弧段的面积(Program to find area of a Circular Segment)
java·开发语言
看到千里之外的云6 小时前
用service 和 SCAN实现sqlplus/jdbc连接Oracle 11g RAC时负载均衡
数据库·oracle·负载均衡
野犬寒鸦6 小时前
Redis核心数据结构操作指南:字符串、哈希、列表详解
数据结构·数据库·redis·后端·缓存·哈希算法