final字段单元测试

背景

通常在配置线程池时,需要获取当前JVM的CPU数量,并和用户的配置(如10)取最小值,作为核心线程数,即用如下的方法:

java 复制代码
    // 获取虚拟机(JVM)运行时环境下的可用 CPU 核心数量
    private static final int CPU_CORE_COUNT = Runtime.getRuntime().availableProcessors();


    /**
     * 计算核心线程数
     *
     * @return core pool count
     */
    public static int calculateCorePoolCount() {
        return Math.min(CPU_CORE_COUNT, 10);
    }

这种情况下,用于CPU_CORE_COUNT是在final字段定义的,所以无法进行mock,所以需要通过设置final字段的值来进行单元测试。

解决方法

在单元测试方法中修改final字段的值(即用来mock不同的数据),达到单元测试的效果。参考代码如下:

java 复制代码
    @Test
    public void testCalculateCorePoolCount_whenCpuCoreCountIsLessThan10() throws Exception {
        setCpuCoreCount(4);
        int result = ThreadPoolConfig.calculateCorePoolCount();
        assertEquals(4, result);
    }

    @Test
    public void testCalculateCorePoolCount_whenCpuCoreCountIsGreaterThan10() throws Exception {
        setCpuCoreCount(16);
        int result = ThreadPoolConfig.calculateCorePoolCount();
        assertEquals(10, result);
    }

    @Test
    public void testCalculateCorePoolCount_whenCpuCoreCountIs10() throws Exception {
        setCpuCoreCount(10);
        int result = ThreadPoolConfig.calculateCorePoolCount();
        assertEquals(10, result);
    }


    /**
     * 通过反射设置final字段的值
     *
     * @param value 待设置的值
     * @throws Exception 异常
     */
    private void setCpuCoreCount(int value) throws Exception {
        Field field = ThreadPoolConfig.class.getDeclaredField("CPU_CORE_COUNT");
        field.setAccessible(true);

        // 移除final修饰符
        Field modifiersField = Field.class.getDeclaredField("modifiers");
        modifiersField.setAccessible(true);
        modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);

        field.set(null, value);
    }
相关推荐
j7~1 小时前
【C++ 标准项目】发布订阅消息队列 (篇七):项目创建与基础工具模块搭建
开发语言·c++·log4j·uuid·protobuf·helper工具·消息定义类型和交换机类型定义
楚楚25121 小时前
2026最新6款Cursor平替AI编程工具深度实测对比
log4j
回眸&啤酒鸭2 天前
【回眸】自动化白盒测试落地实战指南
运维·自动化·log4j
网络毒刘2 天前
端到端:用 Cursor Agent 完成「小功能 + 单测 + PR 描述」并附人工验收清单
单元测试·agent·ai编程·cursor·工具实践
mont evergreen2 天前
RTMP 连接单元测试之旅
单元测试·音视频·源码解读
我就是不信3 天前
CuTest:轻量级 C 语言单元测试框架实战指南
c语言·单元测试·log4j
虫无涯7 天前
Coverity 如何结合 GJB8114-2013使用?
git·单元测试·嵌入式测试·coverity·静态扫描
zlpzlpzyd8 天前
log4j2各个标签以及属性的含义
log4j
茉莉玫瑰花茶9 天前
GO [ 单元测试 ]
golang·单元测试·log4j
李游Leo10 天前
HarmonyOS 7 + ArkUI-Hvigor:动态字体与色彩对比上架预检【鸿蒙心迹】
华为·log4j·harmonyos