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

如何用Mockito或PowerMock拦截static方法nextInt指定返回值测试MyClass?

Mockito/PowerMock 拦截静态方法测试MyClass.myMethod

你的测试代码存在关键问题:你用Mockito.mock(MyClass.class)创建了MyClass的Mock对象,而非真实实例。Mock对象的myMethod不会执行真实逻辑,只会返回int类型的默认值0,导致断言必然失败。


Mockito 解决方案

使用真实的MyClass实例,同时通过MockedStatic拦截RandomUtils的静态方法调用,建议用try-with-resources自动管理静态Mock的生命周期,避免资源泄漏:

import org.apache.commons.lang3.RandomUtils;
import org.junit.jupiter.api.Test;
import org.mockito.MockedStatic;
import org.mockito.Mockito;
import tech.delvi.recipeBusinessLogic.MyClass;

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

public class MyClassTest {

    @Test
    public void testMyMethod() {
        try (MockedStatic<RandomUtils> mockedRandom = Mockito.mockStatic(RandomUtils.class)) {
            // 指定调用RandomUtils.nextInt()时返回1
            mockedRandom.when(RandomUtils::nextInt).thenReturn(1);
            
            // 创建真实的MyClass实例
            MyClass myClass = new MyClass();
            // 验证返回值符合预期
            assertEquals(1, myClass.myMethod());
        }
    }
}

PowerMock 解决方案(适用于JUnit4)

若需使用PowerMock,需先引入PowerMock核心、Mockito整合及JUnit4规则依赖,再编写测试:

import org.apache.commons.lang3.RandomUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import tech.delvi.recipeBusinessLogic.MyClass;

import static org.junit.Assert.assertEquals;

@RunWith(PowerMockRunner.class)
// 告知PowerMock需要处理RandomUtils静态类
@PrepareForTest(RandomUtils.class)
public class MyClassPowerMockTest {

    @Test
    public void testMyMethod() {
        // 拦截RandomUtils.nextInt()并指定返回值
        PowerMockito.mockStatic(RandomUtils.class);
        PowerMockito.when(RandomUtils.nextInt()).thenReturn(1);
        
        // 创建真实实例
        MyClass myClass = new MyClass();
        assertEquals(1, myClass.myMethod());
        
        // 可选:验证静态方法是否被调用
        PowerMockito.verifyStatic(RandomUtils.class);
        RandomUtils.nextInt();
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 19:47:30