如何在模拟对象中创建模拟对象?

时间:2016-11-23 10:27:39

标签: c# unit-testing mocking moq moq-3

我的代码上有这两行。

Customer customer = Repository.Customer.GetById(customerId);
Employee employee = customer.Employees.Single(e => e.IsPrimaryContact);

现在,我正在创建一个单元测试。对象,客户和员工都受到保护,所以我需要嘲笑它们。

我成功地模拟了第一个并创建了一个模拟对象'customer'作为获得客户By Id的回报。

Customer customer = new Mock<Customer>().Object;
/* code ... code*/

var mockCustomerRepository = new Mock<ICustomerRepository>();
mockCustomerRepository.Setup(p => p.GetById(It.IsAny<Guid>())).Returns(customer);
Repository.Customer = mockCustomerRepository.Object;

正如您所看到的,'employee'对象位于模拟对象'customer'中,这意味着我还必须在我的第一个模拟对象(Customer)中提供一个模拟对象。我期待我的代码就像这样。

Employee employee = new Mock<Employee>().Object;
employee.IsPrimaryContact = true;

List<Employee> employees = new List<Employee>();
employees.Add(employee);

customer.Employees = employees;
/* code ... code*/

但是,虽然我在构建测试时没有任何错误。 customer.employee始终为NULL。

3 个答案:

答案 0 :(得分:1)

我建议你试试这段代码

Mock<Customer>() mockCustomer = new Mock<Customer>();
Employee employee = new Employee();
mockCustomer.Setup(x=>x.Employees).Returns(employee);
Customer customer = mockCustomer.Object;

答案 1 :(得分:1)

Sethu Bala的建议可能无法正常工作,因为您无法设置非虚拟成员。

您可以通过调用构造函数,构建器或AutoFixure之类的工具来创建Customer和Employee吗?然后设置您的存储库以返回这些对象。

var customer = CustomerBulder
    .WithEmployees(*list of employees*)
    .Build();
var mockCustomerRepository = new Mock<ICustomerRepository>();
mockCustomerRepository
    .Setup(p => p.GetById(It.IsAny<Guid>()))
    .Returns(customer);

答案 2 :(得分:1)

如果不需要复杂的设置,请使用Linq to Mocks Mock.Of<T>获取模拟对象。它将允许分配财产价值。

Employee employee = Mock.Of<Employee>();
employee.IsPrimaryContact = true;

List<Employee> employees = new List<Employee>();
employees.Add(employee);

Customer customer = Mock.Of<Customer>();
customer.Employees = employees;

var mockCustomerRepository = new Mock<ICustomerRepository>();
mockCustomerRepository.Setup(p => p.GetById(It.IsAny<Guid>())).Returns(customer);
Repository.Customer = mockCustomerRepository.Object;

现在应按预期进行单元测试。