When to unit test private methods

Last week, we talked about why you shouldn’t unit test private methods. Today we’ll talk about why you should.

Wait, what? I just told you that unit testing private methods was unnecessary because you can just test the public methods that call them.

However, I was making a big assumption when I said that. I was assuming your public methods are testable. But what if they’re not? What if they’re all 500 lines long and call 27 private methods, changing the values of 16 properties?

If your public methods are too hard to test, break the rule and test your private methods.

This is a great way to get started, especially if you can find a small, simple method to test. Look for a method that takes one parameter and returns a value. Or look for a method that only changes the value of one property.

After last week’s article, Adam Wolf wrote in to describe how breaking the don’t-test-private-methods rule helped him:

By violating this rule and calling a private method with my test data I was able to write my first test. Without this I’m not sure how I would have finished the app.

He goes on to explain how his production code was the problem, and how he’s making it better now that he has tests:

If you are thinking the problem was my design you’re right! But I was able to ship my features and now I’m all in on TDD. I’m refactoring as I go to make the design testable.

If you’re working on a project that doesn’t have any unit tests, the production code is probably going to be hard to test. Feel free to break the no-testing-private-methods rule. Do whatever it takes to write your first tests. Just make sure to do what Adam’s doing: refactor as you go to make your code more testable.

I still think it’s best to test only public methods. But if your public methods can’t be tested, go ahead and test your private methods. Your new tests will make you more confident that your code does what it’s supposed to. And they’ll enable you to refactor your code knowing that it’ll still work.

Starting is the hard part. Figuring out what to test and how to write tests can feel overwhelming. With Unit Testing in Swift, you’ll write your first tests quickly and easily. It’ll help you free yourself of the burden of manually testing everything. Get it today for 15% off before the launch sale ends.

Keep testing.