Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking ChildProperty cannot get it to work?

Tags:

I am trying to test a property that is nested in a child class. I always get an error. Am I missing something? Is it possible to test a child property in moq.

I have the following

     [Test]
public void Should_be_able_to_test_orderCollection()
    {
        var orderViewMock = new Mock<IOrderView>();
        orderViewMock.SetupGet(o => o.Customer.OrderDataCollection.Count).Returns(2);          

        orderViewMock.SetupSet(o => o.Customer.OrderDataCollection[1].OrderId = 1);

        orderViewMock.VerifySet(o => o.Customer.OrderDataCollection[1].OrderId=1);
    }

    public class CustomerTestHelper
    {
        public static CustomerInfo GetCustomer()
        {
            return new CustomerInfo
           {
               OrderDataCollection = new OrderCollection
                 {
                     new Order {OrderId = 1},
                     new Order {OrderId = 2}
                 }
           };

        }
    }
    public class CustomerInfo
    {
        public OrderCollection OrderDataCollection { get; set; }
    }

    public class OrderCollection:List<Order>
    {
    }

    public class Order
    {
        public int OrderId { get; set; }
    }
    public interface  IOrderView
    {
        CustomerInfo Customer { get; set; }
    }
like image 756
user9969 Avatar asked Feb 05 '10 18:02

user9969


2 Answers

You can't mock the OrderDataCollection property of CustomerInfo because it's a non-virtual property on a concrete class.

The best way to fix this would be to extract an interface from CustomerInfo and let IOrderView return that instead:

public interface IOrderView
{
    ICustomerInfo Customer { get; set; }
}
like image 98
Mark Seemann Avatar answered Nov 15 '22 05:11

Mark Seemann


It is definitely possible if you have the right abstractions. You need to mock your Customer and its children too, for your example to work, like:

var customerMock = new Mock<ICustomer>();
orderViewMock.SetupGet(o => o.Customer).Returns(customerMock.Object);

etc. for the entire hierarchy of child objects you want to control with mocks. Hope it makes sense.

/Klaus

like image 36
Klaus Byskov Pedersen Avatar answered Nov 15 '22 04:11

Klaus Byskov Pedersen