3

I have a class with a method called DataIn(int InputID, string CSVValue), this is the main entry point to it.

This method based on the InputID stores the CSV Value parameter into relevant List<string>'s. When the InputID is the same as a property called NoOfRows it then creates one List<string> made up of all the others. It then checks the validity of this final List<string>, if all is ok then it adds the results to a HashSet<int> as a quick way of checking for duplicates.

I have broken this logic into 3 methods so DataIn calls StoreData, when the InputID in DataIn = NoOfRows it calls MergeData which calls ValidateData.

My question is should I make these methods public to test them separately or should I keep them private and pass in data to DataIn and the do asserts on the merged data List<string> and the HashSet<int>. DataIn will be the method that is called from outside the class, making the other methods public would only be for unit testing.

My concern is that if I make the other methods public and test they are ok I am then not testing DataIn works as expected or if I do both I end up with duplicate tests.

What's your advice?

Jon
  • 38,814
  • 81
  • 233
  • 382

2 Answers2

1

Always stick to the principle of least privilege. Exposing private methods as public just to make them unit testable is not a good design. Instead, stick to testing the public interfaces only. If a method behaves in multiple ways with different inputs, make sure that you write a test per behavior expected and you should a neat and clean design, while still being well tested.

Teoman Soygul
  • 25,584
  • 6
  • 69
  • 80
  • What if I have 2 public methods with similar logic http://stackoverflow.com/questions/29354729/how-to-test-2-methods-with-common-logic by doing that I'd have to test the same logic twice. What should I do in this case? – Rodrigo Ruiz Mar 30 '15 at 21:55
1

There are two competing schools of thought on the need to test private methods - one says that you should not test them, because they are an implementation detail; the other says that you should test them, because you need to test everything.

Without getting in the middle of the argument between the two, I should mention that both sides have valid points going for their approach. However, one thing you should definitely avoid is making your would-be private methods public for the sole purpose of testing them. If you decide to go with the "test private methods" approach, you should make these methods internal, not public, and let the testing assembly see the internal methods using the InternalsVisibleTo attribute in your target assembly.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523