嘲弄ChildProperty无法让它工作?

use*_*969 5 moq

我试图测试嵌套在子类中的属性.我总是得到一个错误.我错过了什么吗?是否可以在moq中测试子属性.

我有以下内容

     [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; }
    }
Run Code Online (Sandbox Code Playgroud)

Mar*_*ann 3

您无法模拟 CustomerInfo 的 OrderDataCollection 属性,因为它是具体类上的非虚拟属性。

解决此问题的最佳方法是从 CustomerInfo 中提取接口并让 IOrderView 返回该接口:

public interface IOrderView
{
    ICustomerInfo Customer { get; set; }
}
Run Code Online (Sandbox Code Playgroud)