You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用JUnit为Java阶乘程序编写异常测试用例

阶乘程序负数输入异常校验实现方案

必须修改业务源码,原有实现用返回-1标识负数输入的逻辑属于错误的魔法值返回,既不符合阶乘的数学定义,也无法通过异常机制明确标识非法入参,无法支撑异常场景的测试校验。

核心修改规则

  • 业务层移除负数输入返回-1的逻辑,改为抛出标准非法参数异常,明确返回错误提示
  • 主入口方法增加异常捕获,给交互用户输出友好提示,同时清理冗余导入、未关闭的IO资源问题
  • 测试层拆分合法用例与异常用例:合法入参保留参数化遍历断言,负数入参单独做异常抛出校验,删除原有适配错误逻辑的{-3,-1}测试条目

修改后的完整业务代码

package BasicTesting;

import java.util.Scanner;

public class Factorial_of_number {
    /**
     * 计算非负整数的阶乘
     * @param n 待计算阶乘的非负整数
     * @return n的阶乘结果
     * @throws IllegalArgumentException 当传入参数为负数时抛出
     */
    public static int factorial(int n) {
        if (n < 0) {
            throw new IllegalArgumentException("无法为负数计算阶乘,输入值必须为非负整数");
        }
        if (n == 0) {
            return 1;
        }
        return n * factorial(n - 1);
    }

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("Enter number to factorize ");
        int n = input.nextInt();
        try {
            System.out.println(factorial(n));
        } catch (IllegalArgumentException e) {
            System.out.println(e.getMessage());
        } finally {
            input.close();
        }
    }
}

修改后的完整JUnit测试代码

基于JUnit4的参数化运行器实现,合法场景自动遍历断言,异常场景单独校验抛出逻辑:如果业务代码未对负数做异常抛出,对应测试用例会直接失败,符合校验要求。

package BasicTesting;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import static org.junit.Assert.assertEquals;
import java.util.Arrays;

@RunWith(Parameterized.class)
public class FactorialTest {
    private int input;
    private int expected;

    // 注入异常校验规则,可同时校验异常类型和提示信息
    @Rule
    public ExpectedException thrown = ExpectedException.none();

    // 构造方法仅加载合法测试用例参数
    public FactorialTest(int input, int expected) {
        this.input = input;
        this.expected = expected;
    }

    // 合法入参测试数据集:仅包含非负整数及对应正确阶乘结果
    @Parameterized.Parameters
    public static Iterable<Object[]> legalTestConditions() {
        return Arrays.asList(new Object[][]{
                {0, 1},
                {1, 1},
                {5, 120},
                {10, 3628800},
                {12, 479001600}
        });
    }

    // 合法场景测试:遍历所有合法入参断言返回值正确
    @Test
    public void testLegalInputFactorial() {
        assertEquals(expected, Factorial_of_number.factorial(input));
    }

    // 异常场景测试:校验负数输入抛出指定异常、提示信息准确
    @Test
    public void testNegativeInputThrowException() {
        thrown.expect(IllegalArgumentException.class);
        thrown.expectMessage("无法为负数计算阶乘,输入值必须为非负整数");
        Factorial_of_number.factorial(-3);
    }
}

测试逻辑说明

  • 运行测试时,所有合法非负整数入参会自动遍历,逐一断言返回结果和预期值一致
  • 负数入参测试会校验方法是否抛出指定类型的异常、异常提示信息是否符合要求:如果业务代码没有做异常校验(比如保留原来返回-1的逻辑),该测试用例会直接判定失败,满足校验需求

内容的提问来源于stack exchange,提问作者Julie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.27 20:27:20