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);
    }
相关推荐
边吃番茄边敲代码1 天前
从本地工具到 MCP:给 Agent 接入独立工具服务,并补齐自动化测试
人工智能·python·功能测试·ai·单元测试·pytest
__zRainy__1 天前
Node系列 · ORM:log4js 日志记录
node.js·log4j
李昊哲小课1 天前
Spring Boot 4 旅游主题实战教程 阶段四:缓存与底层进阶
spring boot·redis·缓存·性能优化·log4j·旅游·性能
qq_452396231 天前
第十三篇:《测试策略:单元测试、组件测试、E2E 测试的落地实践》
单元测试
李昊哲小课2 天前
SpringBoot4 云端咖啡站 阶段五:交付与进阶
人工智能·spring boot·大模型·log4j·智能体
码匠许师傅2 天前
【设计模式精讲】2. 设计原则基石:SOLID 与几条关键原则
java·设计模式·log4j
帅哥的AI自修课2 天前
LangGraph Send:你还在循环里硬调节点?Send 焊死「动态并发路由」,从单播广播到 Map-Reduce 一篇打通
log4j
ly76892 天前
前端测试完整指南:从单元测试、组件测试到端到端测试与 CI/CD
前端·ci/cd·单元测试
咖啡星人k2 天前
2026 AI 自动化测试:让 AI 帮你写用例、跑测试、修 Bug(MonkeyCode 云端实战)
人工智能·功能测试·单元测试·测试用例·bug·集成测试