user1960948 user1960948 - 10 months ago 57
C# Question

How can I create a mocked object inside a mocked object?

I've got these two lines on my code.

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

Now, I'm creating a unit test. Both Objects, customer and employee are protected so I need to mocked them.

I've successfully mocked the first one and created a mocked object 'customer' as its return for getting the 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;

As you can see, the 'employee' object is inside the mocked object 'customer' which means I also have to provide a mocked object inside my first mocked object (Customer). I'm expecting my code to be like this.

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

List<Employee> employees = new List<Employee>();

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

However, though I don't have any error on building my test. The customer.employee is ALWAYS NULL.

Answer Source

I would suggest you to try this code

Mock<Customer>() mockCustomer = new Mock<Customer>();
Employee employee = new Employee();
Customer customer = mockCustomer.Object;