My apologies if this a duplicate. I have been given the task to add some coverage for the method and been told to mock the private List<string> property. My question is: Is there a way to test private fields?
The solution I found is adding new constructor just to inject this private list. I am not sure whether this is the right way, so any help will be highly appreciated.
public class Class1
{
public Class1(List<string> list)//This is just for Unit Testing
{
list1 = list;
}
private readonly InjectRepository _repository;
//
public Class1(InjectRepository repository)//This is the actual constructor
{
_repository = repository;
}
private List<string> list1 = new List<string>();
public void Do_Complex_Logic()
{
//list1 will be set with items in it
//Now list1 is passed to some other instance
}
}
The private logic of a class should be visible in the public expression of its behavior. In other words, the theory goes, there should be no need to test private fields at all.
There is no way to directly test private fields; they are private after all. If you really think that testing a private field is required, then I would suggest making it internal instead, and exposing it to your unit testing assemblies via the [InternalsVisibleTo] attribute.
That being said, there are frameworks that allow such things, such as TypeMock.