假如其他答案指出这样的测试用例很脆弱,并且测试用例不应该基于实现,并且应该依赖于行为,如果您仍然想要嘲笑它们,那么这里有一些方法:
PrivateMethodDemo tested = createPartialMock(PrivateMethodDemo.class,
"sayIt", String.class);
String expected = "Hello altered World";
expectPrivate(tested, "sayIt", "name").andReturn(expected);
replay(tested);
String actual = tested.say("name");
verify(tested);
assertEquals("Expected and actual did not match", expected, actual);
这是你如何使用PowerMock来做到这一点。
PowerMock的expectPrivate()做到这一点。
Test cases from PowerMock其测试私有方法嘲讽
UPDATE: Partial Mocking with PowerMock有一些免责条款,并抓住
class CustomerService {
public void add(Customer customer) {
if (someCondition) {
subscribeToNewsletter(customer);
}
}
void subscribeToNewsletter(Customer customer) {
// ...subscribing stuff
}
}
然后创建的CustomerService的部分模拟,让你想方法列表嘲笑。
CustomerService customerService = PowerMock.createPartialMock(CustomerService.class, "subscribeToNewsletter");
customerService.subscribeToNewsletter(anyObject(Customer.class));
replayAll();
customerService.add(createMock(Customer.class));
向客服模拟中那么add()
是要测试和subscribeToNewsletter()
你现在可以写一个期望像往常一样的方法,真实的东西。
你嘲笑私有方法,_returns_结果,而不是修改** **内部领域。 – Cherry
樱桃检查更新的答案。 –