Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How mock private method that modify private variables?

How mock private method that modify private variables?

class SomeClass{
    private int one;
    private int second;

    public SomeClass(){}

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

    private void complexInitialization(){
        one = ...
        second = ...
    }
}
like image 841
Cherry Avatar asked Dec 20 '22 00:12

Cherry


1 Answers

You don't, because your test will depend on implementation details of the class it is testing and will therefore be brittle. You could refactor your code such that the class you are currently testing depends on another object for doing this calculation. Then you can mock this dependency of the class under test. Or you leave the implementation details to the class itself and sufficiently test it's observable behavior.

The problem you could suffer from is that you are not exactly separating commands and queries to your class. calculateSomething looks more like a query, but complexInitialization is more of a command.

like image 173
SpaceTrucker Avatar answered Jan 06 '23 05:01

SpaceTrucker