模拟没有接口或虚方法的类

jim*_*own 3 c# unit-testing mocking

我想测试一个带有以下签名的方法.

int SomeMethod(List<Employee> employees)
Run Code Online (Sandbox Code Playgroud)

这是相关的课程

public class Employee
{
    public int CustomerID { get; set; }
    public string LastName { get; set; }
    public string FirstName { get; set; }
    public Address Address { get; set; }

}

public class Address
{
    public string StreetName { get; set; }
    public string CityName { get; set; }
    public string State { get; set; }
    public string Country { get; set; }
    public string ZipCode { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我如何模拟List<Employee>作为SomeMethod的输入?请注意,Employee和Address类没有接口或虚方法.

kat*_*330 7

如果你想用以下签名测试方法,int SomeMethod(List<Employee> employees)你不需要模拟Employee!

您需要创建List<Employee> employees = new List<Employee>(),传递给方法并验证结果!

Employee并且Address是没有任何功能的模型,你不需要嘲笑它们!

以下是关于您的案例的两个想法:

  1. 您可以合法地打电话new Employee()new Address()在您的方法中,因为该代码是可测试的!创建模型的新实例不会执行外部依赖.

  2. 呼叫new Employee()new Address()仅在具有功能时才会出现问题.在这种情况下,您将执行可能无法测试的真正依赖!例如,如果EmployeeAddress与数据库通信它是不可测试的,因为它将在执行测试时连接到真实数据库.比你需要创建模拟以避免数据库连接.