Can anyone guide me with a suggested means of testing a private field in a class that is modifed via a public method. I've read a lot of comments from people suggesting that testing private members is not advised as they are internal to the implementation, however this scenario seems to be different from most other answers.
I was thinking about making the private field protected and creating a test subclass that exposes the field but what if I couldn't modify the internals of the class?
In the sample code below the private member to test would be _values which is a write only collection receiving new values via AddValue().
public class Sample
{
private Dictionary<string, string> _values;
private DateTime _created;
public Sample()
{
_values = new Dictionary<string, string>();
_created = DateTime.Now;
}
public void AddValue(string key, string value)
{
_values.Add(key, value);
}
}
The best way to test a private method is via another public method. If this cannot be done, then one of the following conditions is true: The private method is dead code. There is a design smell near the class that you are testing.
Approach 3: Use a Nested Test Class A third approach to testing private methods is to nest a static test class inside the production class being tested. Given that a nested class has access to the private members of its enclosing class, it would be able to invoke the private methods directly.
The answer is: you don't. You don't verify that one method in a class called another method in that class. And while you can test a private method by changing it to public, you shouldn't.
Why We Shouldn't Test Private Methods. As a rule, the unit tests we write should only check our public methods contracts. Private methods are implementation details that the callers of our public methods are not aware of. Furthermore, changing our implementation details should not lead us to change our tests.
You still don't need to test your private variables. You test your interfaces. In this case, I would probably add a Count
property and use that for some tests (or something along those lines)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With