2016-11-23 204 views
0

我的代碼中有這兩行代碼。如何在模擬對象內創建一個模擬對象?

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

現在,我正在創建一個單元測試。客體和員工都受到保護,所以我需要嘲笑他們。

我已經成功地嘲笑第一個,並創建了一個模擬對象「客戶」作爲其獲得客戶的回報。

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 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。

回答

1

我建議你試試這個代碼

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

從Sethu巴拉的建議可能不會工作,因爲你不能設置非虛擬成員。

您可以通過調用構造函數,構建器或類似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); 
1

使用Linq to MocksMock.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; 

現在應該按預期執行單元測試。