【问题标题】:Why Powermockito invokes my mocked method?为什么 Powermock 调用我的模拟方法?
【发布时间】:2017-11-02 14:28:06
【问题描述】:

我想模拟从我的测试方法调用的私有方法,但不是模拟,而是 PowerMockito 调用 toMockMethod,我得到了 NPE。 toMockMethod 属于同一类。

@RunWith(PowerMockRunner.class)
public class PaymentServiceImplTest {

    private IPaymentService paymentService;

    @Before
    public void init() {
        paymentService = PowerMockito.spy(Whitebox.newInstance
                (PaymentServiceImpl.class));
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void test() throws Exception {
        ...
        PowerMockito.doReturn(mockedReturn)
                .when(paymentService,
                      "toMockMethod",
                      arg1, arg2);
    }
}

这是正常情况吗?如果方法已被调用,那么模拟方法有什么意义?

【问题讨论】:

  • 当您想要测试服务时,通常会模拟其与私有方法交互的依赖项,而不是模拟私有方法。
  • @Compass 我测试了一个公共方法,它调用了同一个类的私有方法

标签: java junit4 powermockito


【解决方案1】:

要使用 PowerMock 为类启用静态或非公共模拟,应将该类添加到注解 @PrepareForTest。在你的情况下,它应该是:

@RunWith(PowerMockRunner.class)
@PrepareForTest(PaymentServiceImpl.class)
public class PaymentServiceImplTest {

    private IPaymentService paymentService;

    @Before
    public void init() {
        paymentService = PowerMockito.spy(Whitebox.newInstance
                (PaymentServiceImpl.class));
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void test() throws Exception {
        ...
        PowerMockito.doReturn(mockedReturn)
                .when(paymentService,
                      "toMockMethod",
                      arg1, arg2);
    }
}

【讨论】:

    【解决方案2】:

    我要在这里为我未来的自己留下第二个答案。这里有一个替代问题。如果您调用的是 Static.method,请确保“方法”实际上是在 Static 中定义的,而不是在层次结构中。

    在我的例子中,代码叫做 Static.method,但 Static 是从 StaticParent 扩展而来的,而“方法”实际上是在 StaticParent 中定义的。

    @RunWith(PowerMockRunner.class)
    @PrepareForTest(StaticParent.class)
    public class YourTestClass {
    
        @Before
        public init() {
            PowerMockito.mockStatic(StaticParent.class);
            when(StaticParent.method("")).thenReturn(yourReturnValue);
        }
    }
    
    public class ClassYoureTesting {
    
        public someMethod() {
            Static.method(""); // This returns yourReturnValue
        }
    

    【讨论】:

      猜你喜欢
      • 2015-11-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多