PowerMockito在Springboot中模拟私有方法

时间:2019-04-16 11:29:58

标签: spring-boot junit mockito powermock powermockito

我正在尝试在测试的类中模拟一个私有方法,如下所示。

public String processPayment(...) {
    //some lines
    privateMethod(...);
    return "";
}

private Object privateMethod(...) {
    //some lines
    return someObject;
}

现在我需要测试processPayment方法并模拟privateMethod

我尝试创建上述类的间谍,但在下面进行操作时会调用该方法

final DeviceCheckoutServiceImpl spyDeviceCheckoutService = spy(injectedMockBeanOfAboveClass); //@InjectMock in test class
PowerMockito.doReturn(null).when(spyDeviceCheckoutService, "privateMethod", ArgumentMatchers.anyMap()); //method gets called here
spyDeviceCheckoutService.processPayment(...); //private method isn't mocked somehow, and gets called here too

privateMethod在第二行本身被调用。 另外,the privateMethod也不会被嘲笑。

也许我以错误的方式创建了间谍对象?无法完成spy(new DeviceCheckoutServiceImpl());,因为它需要bean实例化。

Powermockito版本:

compile group: 'org.powermock', name: 'powermock-module-junit4', version: '2.0.0'
compile group: 'org.powermock', name: 'powermock-api-mockito2', version: '2.0.0'

让我知道我在这里做错了。

3 个答案:

答案 0 :(得分:1)

在测试类中,我们将通过将引用传递给需要测试的类来调用org.powermock.api.mockito.PowerMockito的spy()方法:

MockPrivateMethodExample spy = PowerMockito.spy(mockPrivateMethodExample);

然后,我们定义当调用此特定私有方法时要执行的操作。

PowerMockito.doReturn("Test").when(spy, {$methodName});

MockPrivateMethodExample.java

public class MockPrivateMethodExample {

  public String getDetails() {
    return "Mock private method example: " + iAmPrivate();
  }

  private String iAmPrivate() {
    return new Date().toString();
  }
}

MockPrivateMethodTest.java

@RunWith(PowerMockRunner.class)
@PrepareForTest(MockPrivateMethodExample.class)
public class MockPrivateMethodTest {

  private MockPrivateMethodExample mockPrivateMethodExample;

  // This is the name of the private method which we want to mock
  private static final String METHOD = "iAmPrivate";

  @Test
  public void testPrivateMethod() throws Exception {
    mockPrivateMethodExample = new MockPrivateMethodExample();

    MockPrivateMethodExample spy = PowerMockito.spy(mockPrivateMethodExample);
    PowerMockito.doReturn("Test").when(spy, METHOD);
    String value = spy.getDetails();

    Assert.assertEquals(value, "Mock private method example: Test");
    PowerMockito.verifyPrivate(spy, Mockito.times(1)).invoke(METHOD);
  }
}

此处有更多详细信息:https://examples.javacodegeeks.com/core-java/mockito/mockito-mock-private-method-example-with-powermock/

答案 1 :(得分:0)

Mockito引入了AdditionalAnswers.delegatesTo以支持监视Spring代理和其他类似事情:

查看此问题:https://github.com/mockito/mockito/issues/529#issuecomment-239494581

  

因此,请使用spy(proxy)而不是mock(TestSubject.class, delegatesTo(springProxy))

     

但是,如果需要阅读注释,那么您将需要模拟2   Beta。因为嘲笑1.x使用CGLIB不会复制注释   在模仿子类上。 Mockito 2使用了出色的字节预算。

答案 2 :(得分:0)

问题解决了! 忘记在测试类上添加import apples apples.foo()