informa
/
1 MIN READ
Blogs

Don’t Test Private Methods

I often get the question when teaching developers test driven development (TDD), “How do you test private method?” The short answer is you don’t, but there’s also a longer answer...

I often get the question when teaching developers test driven development (TDD), “How do you test private method?” The short answer is you don’t, but there’s also a longer answer that Michael Features gave in his book, *Working Effectively with Legacy Code.*

Certainly, you *could* test private methods, and I’ve seen developers do all sorts of tricks to make that happen—wrapping the private method in a public delegate or proxy or even accessing the private method through reflection—but perhaps having to resort to these tricks is a code smell that’s telling us something’s wrong.

Feathers points out that if you can test the private method through its public interface (the public method that calls the private method) then you can consider the private method tested and code coverage will show the private method was covered. This is why myself and others say that you don’t need to write tests for private methods when doing TDD.

But if you still feel uneasy about whether you have the behavior in the private method covered by tests then maybe something else is going on. Perhaps your private method has too much responsibility and should be broken out into its own testable class. Then the method can be declared public so it can be tested directly and the caller can hold a private reference to its class so the public method doesn’t bloat the caller’s interface.

Private methods are for hiding implementation and we don’t want to test implementation details when we do TDD, that’s better achieved as part of a QA effort, if needed.

Latest Jobs

Disbelief

Hybrid, Cambridge, MA or Chicago, IL
5.31.23
Quality Assurance Lead

Bladework games

Remote (United States)
5.18.23
Senior Gameplay Engineer

High Fidelity, Inc.

Remote
6.2.23
Game Interaction Designer

Fred Rogers Productions

Hybrid (424 South 27th Street, Pittsburgh, PA, USA
5.19.23
Producer - Games & Websites
More Jobs   

CONNECT WITH US

Explore the
Advertise with
Follow us

Game Developer Job Board

Game Developer

@gamedevdotcom

Explore the

Game Developer Job Board

Browse open positions across the game industry or recruit new talent for your studio

Browse
Advertise with

Game Developer

Engage game professionals and drive sales using an array of Game Developer media solutions to meet your objectives.

Learn More
Follow us

@gamedevdotcom

Follow us @gamedevdotcom to stay up-to-date with the latest news & insider information about events & more