Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where do you put unit tests for private methods?

Where do you put unit tests for private functions in C# classes?

An article in Wikipedia suggests:

  • Putting tests in the same class as the members they're testing
  • Using partial classes

Personally, neither of these methods seem appropriate, and I much prefer to have unit tests located in a separate project altogether.

Any thoughts on this?

(I know there's a fair amount of debate on whether private methods should be tested at all. I'd like to hear both sides of the argument.)

like image 919
Jonathan Avatar asked Nov 26 '22 23:11

Jonathan


2 Answers

Private methods do not necessarily need to be tested directly. You can determine their validity based on tests of public methods that utilize those private methods.

However, you should take care to ensure that your public methods can easily inject mock dependencies into your private methods to facilitate testing and simulate all reasonable scenarios.

Edit: As for where your other tests should be located, I suggest a separate subdirectory within your project to handle your tests. When writing tests for PHP applications, I have a tests directory in the root of my project whose directory structure is identical to that of my real application directory structure. In it, I have a test class for each real class.

Just don't compile your test classes with the rest of your project when releasing to production (or in the case of an interpretted language like PHP, don't deploy the test classes to the production webserver).

like image 121
Michael Moussa Avatar answered Dec 24 '22 15:12

Michael Moussa


Do not unit test private methods. Unit tests are for testing the visible (so public and protected) interface of a class. The private methods are implementation details and writing unit tests for them is unnecessary (their behavior should be implicitly tested by the tests on the visible methods), leads to brittle tests (as the implementation details could change) and is a barrier to refactoring.

If you have a private method that you feel you need to unit test, that is a big hint that maybe it should be factored out into a public method on another class.

Where do you put unit tests for private functions in C# classes?

Nowhere. They don't exist.

In general, my unit tests are in separate projects.

like image 35
jason Avatar answered Dec 24 '22 14:12

jason