【问题标题】:Mocked private method is called instead of being mocked模拟私有方法被调用而不是被模拟
【发布时间】:2016-02-29 13:57:58
【问题描述】:

我正在使用 PowerMockito 来模拟私有方法。但相反被嘲笑它被称为。我需要测试调用privateMethod()的strangeMethod()。

这是我的测试类:

public class ExampleService {
    public String strangeMethod() {
        privateMethod();
        return "Done!";
    }

    private String privateMethod() {
        throw new UnsupportedOperationException();
    }
}

我的测试方法:

@Test
public void strangeMethodTest() throws Exception {
    ExampleService exampleService = PowerMockito.spy(new ExampleService());
    PowerMockito.when(exampleService, "privateMethod").thenReturn("");
    exampleService.strangeMethod();
}

作为测试的结果,我得到了 UnsupportedOperationException。这意味着,privateMethod() 被调用。

【问题讨论】:

  • 你确定你首先需要这个吗?这看起来很脏,一个方法是私有的是有原因的。
  • 尝试使用 @PrepareForTest({ExampleService .class})@RunWith(PowerMockRunner.class) 注释您的测试类

标签: java unit-testing junit mockito powermock


【解决方案1】:

当您使用PowerMockito.spy(new ExampleService()); 时,所有方法调用首先将委托给真实类的实例。是什么原因让您在线路上收到UnsupportedOperationException

PowerMockito.when(exampleService, "privateMethod").thenReturn("");

如果你想避免调用真正的方法,那么使用PowerMockito.mock( ExampleService.class);doCallRealMethod/thenCallRealMethod 作为不应被模拟的方法。

这个例子表明私有方法被模拟了:

类:

public class ExampleService {
    public String strangeMethod() {

        return privateMethod();
    }

    private String privateMethod() {
        return "b";
    }
}

测试:

@PrepareForTest(ExampleService.class)
@RunWith(PowerMockRunner.class)
public class TestPrivate {

    @Test
    public void strangeMethodTest() throws Exception {
        ExampleService exampleService = PowerMockito.spy(new ExampleService());
        PowerMockito.when(exampleService, "privateMethod").thenReturn("a");
        String actual = exampleService.strangeMethod();

        assertEquals("a",actual);
    }

}

【讨论】:

  • 我的示例仍然使用“间谍”。所以真正的方法仍然被调用一次,当它被嘲笑时。正如我上面提到的,你需要使用'PowerMockito.mock'来避免真正的方法调用。
  • 但是如果我模拟我的 exampleService 对象,我如何测试该方法返回“完成!”?
  • 对“strangeMethod”使用 doCallRealMethod 或 thenCallRealMethod。示例:'PowerMockito.when(exampleService.strangeMethod()).thenCallRealMethod()'。抱歉,我是手机端的,所以方法名称可能有点不正确或有错别字。
  • 但我必须知道,这是一个非常肮脏的解决方案,应该谨慎使用以覆盖旧的遗留代码。但它永远不应该用于测试/编写新代码。
猜你喜欢
  • 1970-01-01
  • 2016-03-31
  • 2014-08-17
  • 1970-01-01
  • 2015-02-20
  • 2017-06-20
  • 2018-11-30
  • 1970-01-01
相关资源
最近更新 更多