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

如何使用JUnit实现long、short、byte、float等数据类型的单元测试

你无法完成float、short、byte、long类型测试的核心原因有两个:

  1. Java基本类型包装类的字面量默认规则问题:你直接写的数字字面量默认类型不符合预期:
    • 小数字面量默认是Double类型,不加后缀不会被识别为Float
    • 整数字面量默认是Integer类型,不加标识不会被识别为Short、Byte、Long
  2. 你当前代码逻辑存在不一致:asShort、asLong方法调用了cast()方法,类型不匹配时直接抛出SQLException,而asFloat、asByte和其他类型转换方法是instanceof判断不匹配时返回空Optional,两种行为不统一容易踩坑。

解决方案

第一步:补全对应的单元测试用例

注意构造CellImpl实例时,要显式指定对应类型的字面量:

@Test
void asFloat() {
    // 小数加f后缀显式声明为float类型
    CellImpl teste = new CellImpl(null, null, 3.2f);
    assertEquals(3.2f, teste.notNull().asFloat());
}

@Test
void asShort() {
    // 整数强转为short类型
    CellImpl teste = new CellImpl(null, null, (short) 10);
    assertEquals((short)10, teste.notNull().asShort());
}

@Test
void asByte() {
    // 整数强转为byte类型
    CellImpl teste = new CellImpl(null, null, (byte) 2);
    assertEquals((byte)2, teste.notNull().asByte());
}

@Test
void asLong() {
    // 整数加L后缀显式声明为long类型
    CellImpl teste = new CellImpl(null, null, 100L);
    assertEquals(100L, teste.notNull().asLong());
}

第二步(可选):统一类型转换逻辑

当前asShort、asLong的逻辑和其他方法不一致,建议调整为和其他方法相同的instanceof判断逻辑,避免调用方需要处理两种不同的异常/返回情况:

@Override
public Optional<Short> asShort() {
    if (value instanceof Short) {
        return Optional.ofNullable((Short)value);
    }
    return Optional.empty();
}

@Override
public Optional<Long> asLong() {
    if (value instanceof Long) {
        return Optional.ofNullable((Long)value);
    }
    return Optional.empty();
}

另外你现有代码里的return Optional.ofNullable(null);可以直接替换成Optional.empty(),写法更规范。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 23:54:03