Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it ok to change method visibility for the sake of unit testing?

Many times I find myself torn between making a method private to prevent someone from calling it in a context that doesn't make sense (or would screw up the internal state of the object involved), or making the method public (or typically internal) in order to expose it to the unit test assembly. I was just wondering what the Stack Overflow community thought of this dilemma?

So I guess the question truly is, is it better to focus on testability or on maintaining proper encapsulation?

Lately I've been leaning towards testability, as most of the code is only going to be leveraged by a small group of developers, but I thought I would see what everyone else thought?

like image 264
Eric Avatar asked Feb 25 '10 00:02

Eric


People also ask

Should unit test methods be public?

Unit Tests Should Only Test Public Methods In fact, if you are practicing test-driven development (TDD), the unit test is your first client of the object. The test should only be accessing the class' public interface.

Is it good practice to make all methods public?

Yes it is very bad practice - you're letting your tools make design decisions for you. I think the main problem here is that you're trying to treat each individual method as a unit. This is generally the cause of all unit test woes.


1 Answers

Its NOT ok to change method visibility on methods that the customers or users can see. Doing this is ugly, a hack, exposes methods that any dumb user could try to use and explode your app... its a liability you do not need.

You are using C# yes? Check out the internals visible to attribute class. You can declare your testable methods as internal, and allow your unit testing assembly access to your internals.

like image 57
Charles Avatar answered Sep 21 '22 01:09

Charles