Mocking ChildProperty can't make it work?

I am trying to check a property nested in a child class. I always get an error message. Am I missing something? Is it possible to check the 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; }
    }
+5
source share
3 answers

You cannot make fun of the OrderDataCollection CustomerInfo property because it is not a virtual property in a particular class.

The best way to fix this is to retrieve the interface from CustomerInfo and return an IOrderView instead:

public interface IOrderView
{
    ICustomerInfo Customer { get; set; }
}
+3
source

This is possible if you have the right abstractions. You must make fun of Customeryours and his children so that your example works, for example:

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

... , mocks. , .

/

+1

, :

System.ArgumentException: Invalid setup on a non-overridable member:
o => o.Customer.OrderDataCollection.Count
at Moq.Mock.ThrowIfCantOverride(Expression setup, MethodInfo methodInfo)

IOrderView CustomerInfo, , CustomerInfo OrderCollection. , /. mocking/, Typemock ().

, - .

0

All Articles