Search code examples
unit-testingtddbdd

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.


Solution

  • 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.