I do not test private methods. But what about internal state of the object?
I am working on a game. My object has public update method. When this method is called, then it calls several private methods. For example move method which should change position based on speed, heading and so.
Anyway coordinates are part of internal state.
On one hand, internal state probably should be not tested. On the other hand there are some calculations which I would like to have tested, but I do not not how (because it is done in private methods…).
Do you have any advice for me? Should I change my OO design somehow?
This is driving me crazy. I would like to write some code, but I am struggling with this…
It may be your private methods are telling you they want to get promoted to public, maybe even into their own class where they can be more easily tested and organized.
Looking forward to reading other answers to this, as well.
If you find yourself wishing you could test your private methods, you should promote those methods into their own object with public methods and test that.
Why don’t you give that a try and see how it feels?
I gotta admit, @benorenstein, @pedromoreira… I’m still having a problem here, even after having read the references you provided.
Let’s say I have TDD’d my project down to the point where I know I need, say, a get_column_word method, and at this point, I also know that this really is an internal utility (i.e., private) method that should never be seen externally.
What I keep wanting to do is to write simple unit tests to drive out the code for that method, rather than having to keep testing the higher-level (caller) method and hoping that I’ve got that private method correct. Seems like I’m forced to work on the ‘outside’ without being allowed to go ‘inside’.
@JESii, it seems that that method is really telling you it wants to be part of your public API.
You describe going along a route where you discover this method and find that you want to talk to it:
promote and see how that feels.
Also, I wouldn’t get very bogged down with it being hidden. Marking a method as private doesn’t mean it can’t get called, it just signals that it shouldn’t.
Hope this helps
PS:
To balance my previous Sandi Metz reference, here’s another: “Marking a method as private doesn’t stop me from calling it. It is just a matter of how difficult you want to make it for me”.
Tnx, @pedromoreira . I know about ‘private’ being just a guideline. I have been trying to better organize my code and kept running into this problem. I can leave them all as public methods and test them… Just wasn’t sure that was the “best” approach.
As I recall, I’ve gotten feedback about needing to make more of my methods private. And it’s still a general question: given that Metz and others say: “don’t test private methods”, how do you TDD that potentially large section of code?