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

如何将PowerMockito whenNew thenThrow迁移至Mockito Inline MockedConstruction

用Mockito Inline模拟构造器抛出异常(替代PowerMock的whenNew)

原PowerMock代码

whenNew(MyClass.class).withAnyArguments().thenThrow(new MyException("fail"));

对应的Mockito Inline正确实现

要让MyClass的所有构造调用都抛出异常,直接在mockConstruction的构造逻辑中抛出异常即可:

try (MockedConstruction<MyClass> ignored = Mockito.mockConstruction(MyClass.class, 
    invocation -> {
        throw new MyException("fail");
    })) {
    stuffToTest();
}

如果需要针对特定参数的构造器抛出异常,可以通过获取构造参数做判断:

try (MockedConstruction<MyClass> ignored = Mockito.mockConstruction(MyClass.class, 
    (mock, context) -> {
        Object[] constructorArgs = context.arguments();
        // 比如判断第一个参数是否为特定值时抛出异常
        if (constructorArgs != null && constructorArgs.length > 0 
            && "targetArg".equals(constructorArgs[0])) {
            throw new MyException("fail for target argument");
        }
        // 其他情况可以正常生成mock实例,或执行其他逻辑
    })) {
    stuffToTest();
}

你之前代码的问题

你错误地沿用了PowerMock的思维,在mockConstruction的回调里尝试用when(new MyClass(any()))来定义构造行为——这在Mockito Inline里是不生效的。mockConstruction的回调是用来配置生成的mock实例的行为,而非拦截构造器调用本身。要触发构造时的异常,必须直接在构造逻辑的lambda/Answer中抛出异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 14:05:23