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

时间:2016-11-29 22:29:07

标签: c# unit-testing mocking

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

int SomeMethod(List<Employee> employees)

以下是相关课程

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; }
}

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

2 个答案:

答案 0 :(得分:7)

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

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

EmployeeAddress是没有任何功能的模型,您不需要嘲笑它们!

以下是关于您案件的两点想法:

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

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

答案 1 :(得分:2)

如果没有Employee和mock对象之间的接口或公共基类,则除了Employee之外,不能传递任何对象。

如果您有能力,我建议为您的员工班级创建一个界面&amp;模拟类都实现。然后,您只需更改方法参数即可直接接受接口而不是Employee。

相关问题