Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test private fields that are modified via public methods

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);
    }
}
like image 413
William Avatar asked Jul 30 '10 23:07

William


People also ask

Is there any direct way to test private method?

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.

How do I test a private function or a class that has private methods fields or inner classes?

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.

Can we test private methods in Junit?

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.

Can we test private methods in unit testing?

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.


1 Answers

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)

like image 57
µBio Avatar answered Oct 25 '22 06:10

µBio