在C#中测试/注入私有字段有什么好的做法 [英] What are the good practice to test/inject private field in C#
问题描述
如果这是重复的话,我表示歉意。我被赋予为该方法添加一些覆盖率的任务,并被告知模拟私有 List< string>
属性。我的问题是:有没有一种方法可以测试私有字段?
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
}
}
推荐答案
a的私有逻辑该类应该在其行为的公开表达中可见。换句话说,从理论上讲,根本不需要测试私有字段。
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.
无法直接测试私有字段;他们毕竟是私人的。如果您真的认为需要测试一个私有字段,那么我建议您将其设置为内部字段,然后通过 [InternalsVisibleTo] 属性。
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.
可以这么说,有些框架可以允许这样的东西,例如 TypeMock 。
That being said, there are frameworks that allow such things, such as TypeMock.
这篇关于在C#中测试/注入私有字段有什么好的做法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!