我正在用C#,NUnit和Rhino Mocks编写单元测试.以下是我正在测试的类的相关部分:
public class ClassToBeTested
{
private IList<object> insertItems = new List<object>();
public bool OnSave(object entity, object id)
{
var auditable = entity as IAuditable;
if (auditable != null) insertItems.Add(entity);
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
我想在调用OnSave后测试insertItems中的值:
[Test]
public void OnSave_Adds_Object_To_InsertItems_Array()
{
Setup();
myClassToBeTested.OnSave(auditableObject, null);
// Check auditableObject has been added to insertItems array
}
Run Code Online (Sandbox Code Playgroud)
这是什么最好的做法?我曾考虑将insertItems作为一个带有公共get的Property添加,或者将List注入ClassToBeTested,但不确定我是否应该修改代码以进行测试.
我已经阅读了许多关于测试私有方法和重构的帖子,但这是一个非常简单的类,我想知道什么是最好的选择.
如果这是重复的,我很抱歉。我被赋予了为该方法添加一些覆盖范围的任务,并被告知要模拟私有List<string>财产。我的问题是:有没有办法测试私有字段?
我找到的解决方案是添加新的构造函数只是为了注入这个私有列表。我不确定这是否是正确的方法,所以任何帮助将不胜感激。
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
}
}
Run Code Online (Sandbox Code Playgroud)