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

使用PowerMock模拟异常抛出与对象创建失效的问题排查

问题解决:PowerMock模拟Random对象创建未生效的问题

你的测试代码里,PowerMock没能拦截ExceptionClass中new Random()的操作,导致实际创建了真实的Random实例,所以nextInt()返回随机值,没触发catch块返回111,断言失败。

核心原因

PowerMock要拦截某个类内部的对象创建操作,必须通过@PrepareForTest注解指定包含该new操作的类(也就是ExceptionClass),否则它无法识别并替换这个对象创建过程。

修复步骤

  • 在测试类MockThrowExceptionTest上添加@PrepareForTest(ExceptionClass.class)注解
  • 确保测试类已经正确使用@RunWith(PowerMockRunner.class)(你已经完成这一步)

修改后的完整代码

package com.example;

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

import static org.powermock.api.mockito.PowerMockito.*;

import java.util.Random;

class ExceptionClass {
    public int getRandom() {
        try {
            Random random = new Random();
            return random.nextInt();
        } catch (Exception e) {
            return 111;
        }
    }
}

@RunWith(PowerMockRunner.class)
@PrepareForTest(ExceptionClass.class) // 新增的关键注解
public class MockThrowExceptionTest {
    @InjectMocks
    ExceptionClass obj;

    @Test
    public void testGetRandom() throws Exception {
        Random rand = mock(Random.class);
        whenNew(Random.class).withNoArguments().thenReturn(rand);
        when(rand.nextInt()).thenThrow(new IllegalStateException());

        Assert.assertTrue(obj.getRandom() == 111);
    }
}

修改后,PowerMock会正确拦截ExceptionClass内部的new Random()操作,替换成你mock的实例。调用nextInt()时会抛出IllegalStateException,触发catch块返回111,断言就能通过了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 01:53:18