2013-08-29 62 views
3

如何模拟修改私有变量的私有方法?如何模拟修改私有变量的私有方法?

class SomeClass{ 
    private int one; 
    private int second; 

    public SomeClass(){} 

    public int calculateSomething(){ 
     complexInitialization(); 
     return this.one + this.second; 
    } 

    private void complexInitialization(){ 
     one = ... 
     second = ... 
    } 
} 

回答

0

功率模拟可能会帮助你在这里。但通常我会使该方法受到保护,并重写以前私有的方法来完成我想要的操作。

2

假如其他答案指出这样的测试用例很脆弱,并且测试用例不应该基于实现,并且应该依赖于行为,如果您仍然想要嘲笑它们,那么这里有一些方法:

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()你现在可以写一个期望像往常一样的方法,真实的东西。

+0

你嘲笑私有方法,_returns_结果,而不是修改** **内部领域。 – Cherry

+0

樱桃检查更新的答案。 –

8

您不需要,因为您的测试将取决于正在测试的类的实现细节,因此会变得很脆弱。你可以重构你的代码,使得你当前正在测试的类依赖另一个对象来完成这个计算。然后你可以嘲笑这个被测试类的依赖。或者你将实现细节留给类本身,并充分测试它的可观察行为。

你可以从遭受的问题是,你是不是完全分离的命令和查询类。 calculateSomething看起来更像是一个查询,但complexInitialization更像是一个命令。

+0

第一段的最后一句是正确的答案。测试需要基于_behaviour_,而不是围绕实施。看看各种答案(包括我的)到非常类似的问题,在http://stackoverflow.com/questions/18435092/how-to-unit-test-a-private-variable/18435828#18435828 –