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

弃用PowerMock后,如何用JUnit/Mockito调用私有构造方法?

不用PowerMock,测试私有构造方法的方案

Mockito的核心能力是模拟对象行为,并不提供调用私有构造方法的功能,但你完全可以用Java原生反射API来实现这个测试,不需要依赖额外框架。

针对你的Foo类,以下是两种常见JUnit版本的实现:

JUnit 4 实现

@Test(expected = UnsupportedOperationException.class)
public void testFooConstructorThrowsException() throws Exception {
    // 获取私有构造方法
    Constructor<Foo> constructor = Foo.class.getDeclaredConstructor();
    // 允许访问私有成员
    constructor.setAccessible(true);
    // 调用构造方法
    constructor.newInstance();
}

JUnit 5 实现(更推荐)

JUnit5的assertThrows可以更精准地验证异常信息,避免expected注解的局限性:

@Test
void testFooConstructorThrowsException() throws Exception {
    Constructor<Foo> constructor = Foo.class.getDeclaredConstructor();
    constructor.setAccessible(true);
    
    // 验证调用构造方法时抛出指定异常,并获取异常实例
    UnsupportedOperationException exception = assertThrows(
        UnsupportedOperationException.class,
        constructor::newInstance
    );
    
    // 可选:验证异常消息是否符合预期
    assertEquals("Constructor should not be invoked.", exception.getMessage());
}

这种方式完全替代了PowerMock Whitebox的invokeConstructor功能,而且不引入额外依赖,符合你弃用PowerMock的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 05:15:00