一种可能的解决方案是使用提取和覆盖模式从被测类派生一个可测试的类并覆盖该private
方法(这应该是private
您的示例之外的其他方法,因为private
方法不能virtual
- 也许您的意思是protected
?)以允许您覆盖方法。
public class Employee
{
public virtual string GetFullName(string firstName, string lastName)
{
string middleName = GetMiddleName();
return string.Format("{0} {2} {1}", firstName, lastName,middleName );
}
protected virtual string GetMiddleName()
{
// Some call to Service
return "George";
}
}
///<summary>
///Testable Employee class
///</summary>
public class TestableEmployee : Employee
{
public string MiddleName;
public virtual string GetFullName(string firstName, string lastName)
{
string middleName = GetMiddleName();
return string.Format("{0} {2} {1}", firstName, lastName,middleName );
}
protected override string GetMiddleName()
{
// provide own implementation to return
// property that we can set in the test method
return MiddleName;
}
}
测试方法
[TestMethod]
public GetFullName_ReturnsSetName()
{
var testEmployee = new TestableEmployee();
string firstName = "first";
string middleName = "middle";
string lastName = "last";
TestableEmployee.MiddleName = middleName;
string fullName = GetFullName(firstName, lastName);
Assert.AreEqual(string.Format("{0} {2} {1}",
firstName, lastName, middleName ),
fullName
);
}
如果GetMiddleName()
是服务调用的包装器,那么将服务接口作为Employee
类的属性可能是一种更可测试的设计。这样,您可以使用提取和覆盖模式或使用控制反转 (IoC) 容器(如Unity或Castle Windsor )来模拟服务类型。