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

如何为十进制转十六进制Java代码编写JUnit测试?

搞定十进制转十六进制的JUnit测试

没问题,我帮你一步步把这个JUnit测试写出来。首先得说,你现在的代码把转换逻辑嵌在main方法里,直接测试main会很麻烦——因为它要读控制台输入,还输出结果,没法直接断言对错。所以第一步我们先重构代码,把核心的转换逻辑抽成一个独立的可调用方法,这样JUnit就能轻松测试它了。

第一步:重构你的DecToHexa类

先补全并重构你的代码,把转换逻辑抽成静态方法:

import java.util.Scanner;

public class DecToHexa {
    // 抽出来的转换方法,专门做十进制转十六进制,方便测试
    public static String convertDecimalToHex(int decimal) {
        // 处理0的特殊情况:原逻辑里decimal为0时循环不执行,会返回空字符串,这不符合预期
        if (decimal == 0) {
            return "0";
        }
        
        String hex = "";
        int tempDecimal = decimal; // 用临时变量,避免修改原参数
        
        while (tempDecimal != 0) {
            int hexValue = tempDecimal % 16;
            char hexDigit;
            
            // 把余数转成对应的十六进制字符
            if (hexValue < 10) {
                hexDigit = (char) ('0' + hexValue);
            } else {
                hexDigit = (char) ('A' + hexValue - 10);
            }
            
            // 注意要把当前字符加到字符串前面,因为取余得到的是低位到高位
            hex = hexDigit + hex;
            tempDecimal = tempDecimal / 16;
        }
        
        return hex;
    }

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.println("Enter a decimal number: ");
        int decimal = input.nextInt();
        String hex = convertDecimalToHex(decimal);
        System.out.println("Hexadecimal equivalent: " + hex);
        input.close();
    }
}

第二步:编写JUnit 5测试用例

假设你用的是目前主流的JUnit 5,先确保你的IDE(比如IntelliJ IDEA/Eclipse)已经配置好了JUnit 5的依赖。然后创建测试类DecToHexaTest:

import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;

public class DecToHexaTest {

    // 测试常规正数转换
    @Test
    void testPositiveNumberConversions() {
        assertEquals("A", DecToHexa.convertDecimalToHex(10));
        assertEquals("10", DecToHexa.convertDecimalToHex(16));
        assertEquals("FF", DecToHexa.convertDecimalToHex(255));
        assertEquals("1A3", DecToHexa.convertDecimalToHex(419));
    }

    // 测试0的特殊情况
    @Test
    void testZeroConversion() {
        assertEquals("0", DecToHexa.convertDecimalToHex(0));
    }

    // 测试边界值,确保极端情况也能正确转换
    @Test
    void testBoundaryValues() {
        assertEquals("F", DecToHexa.convertDecimalToHex(15)); // 十六进制单字符最大值
        assertEquals("7FFF", DecToHexa.convertDecimalToHex(32767)); // 最大short值
        assertEquals("7FFFFFFF", DecToHexa.convertDecimalToHex(2147483647)); // 最大int值
    }
}

为什么要这么做?

  • 重构的意义:把转换逻辑和输入输出逻辑分离,让核心功能独立出来,既方便测试,也让代码更易维护。
  • 测试用例覆盖:我们覆盖了常规数值、特殊值0、边界值,确保你的转换方法在各种场景下都能正确工作。
  • 断言的作用:assertEquals用来对比方法返回的结果和我们预期的十六进制字符串,一旦不匹配,JUnit就会标记测试失败,帮你快速定位问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:20:54