PowerMockito使用whenNew无法创建Mock对象,调用A构造器仍实例化真实B类
解决PowerMock mock构造方法失效问题
常见失效原因及修复方案
- 缺少@Test注解
你提供的测试用例方法未添加@org.junit.Test注解,JUnit无法识别该方法为测试用例执行,先补上注解。 - 导包错误
必须导入PowerMock对应工具类,确认你项目中导入的包如下:import org.powermock.api.mockito.PowerMockito; import static org.mockito.Mockito.mock; import org.junit.Test; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; - 版本不兼容
PowerMock和Mockito版本需要严格匹配,常见兼容组合:- Mockito 2.8.x~2.28.x:搭配PowerMock 2.0.0~2.0.9
- Mockito 3.x:搭配PowerMock 2.1.0+
- B类存在final修饰
如果B类被final修饰、或者B的构造方法被final修饰,需要将B类也加入@PrepareForTest注解:@PrepareForTest({A.class, B.class}) - 构造方法匹配规则不精准
可以将withAnyArguments()替换为精准参数匹配规则,避免匹配失效:PowerMockito.whenNew(B.class) .withParameterTypes(Config.class) .withArguments(Mockito.any(Config.class)) .thenReturn(b);
修复后可运行完整代码
// 业务类 class Config {} class B { public B(Config config) { // 测试时如果mock生效,该行不会打印 System.out.println("B类真实构造方法执行"); } } class A { public A() { B b = new B(new Config()); } } // 测试类 @RunWith(PowerMockRunner.class) @PrepareForTest(A.class) class ATest { @Test public void testAConstructor() { B mockB = mock(B.class); PowerMockito.whenNew(B.class).withAnyArguments().thenReturn(mockB); // 实例化A时不会触发B的真实构造 A a = new A(); } }
内容的提问来源于stack exchange,提问作者Mehul Kumar
相关产品推荐
相关产品推荐

