如何模拟ReadOnlyCollection< T>使用最小起订量的属性 [英] How to mock a ReadOnlyCollection<T> property using moq

查看:86
本文介绍了如何模拟ReadOnlyCollection< T>使用最小起订量的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试模拟此ReadOnlyCollection属性:

I'm trying to mock this ReadOnlyCollection property:

private readonly IList<MyClass> myList = new List<MyClass>();
public virtual ReadOnlyCollection<MyClass> MyList
{
   get
   {
       return new ReadOnlyCollectionBuilder<MyClass>(this.myList).ToReadOnlyCollection();
   }
}

使用此模拟程序(如此处所示):

using this mock (as seen here):

IList<MyClass> mockList = GetElements();
mockObj.SetupGet<IEnumerable<MyClass>>(o => o.myList).Returns(mockList);

但是在运行时,我会收到InvalidCastException:

However at runtime I get an InvalidCastException:

Unable to cast object of type 'System.Collections.Generic.List`1[MyClass]' to
type 'System.Collections.ObjectModel.ReadOnlyCollection`1[MyClass]'.

我在做什么错了?

推荐答案

假设您的代码看起来真的很像(否则它将无法编译):

Suppose your code really looks like (otherwise it will not compile):

// Arrange
IList<MyClass> stakeHoldersList= GetElements();
mockObj.SetupGet<IEnumerable<MyClass>>(o => o.MyList).Returns(stakeHoldersList);
// Act on SUT which uses mockObj

您具有类型为ReadOnlyCollection<MyClass>的MyList属性,但是您正在尝试返回IEnumerable<MyClass>.这就是为什么您会收到该错误的原因.因此,请更改:

You have property MyList of type ReadOnlyCollection<MyClass> but you are trying to return IEnumerable<MyClass>. Thats why you get that error. So, change:

ReadOnlyCollection<MyClass> stakeHoldersList = new ReadOnlyCollection<MyClass>(GetElements());
mockObj.SetupGet<ReadOnlyCollection<MyClass>>(o => o.MyList).Returns(stakeHoldersList);

为避免此类运行时错误,请不要指定SetupGet方法的类型.在这种情况下,将从属性类型推断出返回值类型,并且您将立即得到错误(如果返回值类型与属性类型不匹配,则代码将无法编译):

To avoid such runtime errors, do not specify type of SetupGet method. In this case return value type will inferred from property type and you will get error immediately (code won't compile if return value type does not match property type):

mockObj.SetupGet(o => o.MyList).Returns(stakeHoldersList);

这篇关于如何模拟ReadOnlyCollection&lt; T&gt;使用最小起订量的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆