PowerMockito whenNew 对多层传递依赖类打桩不生效问题排查
多层类调用业务场景
Class A { someMethod() { B b = new B(); b.someMethod(); } } Class B { String someMethod() { C c = new C(); return c.someMethod(); } } Class C { String someMethod() { D d = new D(); return d.getId() } } Class D { getId() { return "id123"; } }
打桩失效的测试实现
对应测试代码如下:
@RunWith(PowerMockRunner.class) @PrepareForTest({A.class, B.class, C.class}) MyTest { public void basicTest() { D mockDClass = mock(D.class); when(mockDClass.getId()).thenReturn("mockedId"); PowerMockito.whenNew(D.class).withAnyArguments().thenReturn(mockClass); } }
- 测试预期:执行后返回打桩的
"mockedId" - 实际结果:程序走入D的真实方法,打桩完全没有生效
疑问点:
whenNew是不是仅对被测类自身内部new的对象生效,无法覆盖多层传递调用链中其他类内部new的对象?
最小复现验证
为定位问题,编写了和上述业务逻辑完全一致的最小复现模块开展测试:
复现模块业务实现代码
public class A { public String someMethod() { B b = new B(); return b.someMethod(); } } public class B { public String someMethod() { C c = new C(); return c.someMethod(); } } public class C { public String someMethod() { D d = new D(); return d.getId(); } } public class D { public String getId() { return "id123"; } }
复现模块测试代码
import junit.framework.TestCase; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import static org.mockito.Mockito.*; import static org.mockito.Mockito.mock; @RunWith(PowerMockRunner.class) @PrepareForTest({A.class, B.class, C.class}) public class ATest extends TestCase { @Test public void mockTest() { D mockD = mock(D.class); when(mockD.getId()).thenReturn("this is from mock"); PowerMockito.whenNew(D.class).withAnyArguments().thenReturn(mockD); A a = new A(); System.out.println(a.someMethod()); } }
复现结果
运行上述最小测试模块时,打桩逻辑却能正常生效,测试输出结果如下:
该结果说明正式业务测试用例存在配置问题,但暂时无法定位具体故障点。
内容的提问来源于stack exchange,提问作者Mohammed
相关产品推荐
相关产品推荐

