Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unit test private methods in BDD / TDD?

I am trying to program according to Behavior Driven Development, which states that no line of code should be written without writing failing unit test first.

My questions:

  • how to use BDD with private methods, and
  • how can I unit test private methods?

Is there better solution than:

  • making private methods public first and then making them private when I write public method that uses those private methods;
    or
  • in C# making all private methods internal and using InternalsVisibleTo attribute.

like image 452
robert_d Avatar asked Oct 17 '09 22:10

robert_d


People also ask

How do you test private methods in TDD?

When doing TDD, the private methods emerge from your code. And because you test-drive your development, no functionality is added without a test. So, for code fully developed by following TDD you won't have to test the private method separately: Private methods are already being tested by previously written tests.

Can we test private methods in unit testing?

Unit Tests Should Only Test Public Methods The short answer is that you shouldn't test private methods directly, but only their effects on the public methods that call them. Unit tests are clients of the object under test, much like the other classes in the code that are dependent on the object.

Can we use BDD for unit testing?

In this article, we'll see how Behavior Driven Development / Acceptance Test Driven Development (BDD/ATDD) can apply all the way from the Customer / User Tests to Unit Tests. These are the tests in the left column of the matrix. To illustrate this process, I'll use the example of an on-line ordering system.

How do you cover a private method in a test class?

Use the TestVisible annotation to allow test methods to access private or protected members of another class outside the test class. These members include methods, member variables, and inner classes. This annotation enables a more permissive access level for running tests only.


1 Answers

When you write code test-first, you write against the public interface. There are no private methods at this point.

Then you write the code to pass the test. If any of that code gets factored into a private method, that's not important -- it should still be there only because it is used by the public interface.

If the code isn't written test first, then -- in .net, anyway -- reflection can be used to directly prod private methods; though this is a technique of last resort.

like image 155
Steve Gilham Avatar answered Sep 21 '22 18:09

Steve Gilham