Can I unit test private methods?

I’ve heard a variation of this question over and over: “Can I unit test private methods?”

It comes in other forms, too, like “how do I verify that one method in a class called another method in the same class?”

The answer is: you don’t. You don’t verify that one method in a class called another method in that class. And while you can test a private method by changing it to public, you shouldn’t.

Private methods are great for breaking logic into smaller parts. If a method gets too big, you should refactor it and break it down into private methods so it’s easier to read. But you don’t need to test those private methods individually.

To test private methods, you just need to test the public methods that call them. Call your public method and make assertions about the result or the state of the object. If the tests pass, you know your private methods are working correctly.

Whatever you do, don’t change private methods to public just so you can test them. Test your public methods and verify that they work, and your private methods will be covered, too.

How should you start unit testing your app?

Unit testing for iOS can be lonely — most iOS developers don't seem to be doing it. Should you be writing unit tests? What are the benefits of unit testing, anyway? And if it is worth the effort, how do you get started? Enter your name and email in the boxes to get answers to your questions.

We won't send you spam. Unsubscribe at any time. Powered by ConvertKit