English 中文(简体)
• 如何利用分子对私人阅读的IList<T>财产进行模拟
原标题:How to mock a private readonly IList<T> property using moq

我试图篡改这个名单:

private readonly IList<MyClass> myList = new List<MyClass>();

(见here):

IList<MyClass> mockList = Builder<MyClass>.CreateListOfSize(5).Build();
mockObj.SetupGet<IEnumerable<MyClass>>(o => o.myList).Returns(stakeHoldersList);

然而,在业时间 我收到了一个因瓦利德·卡斯特韦采:

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

我做了什么错误?

最佳回答

Well, I think it s odd and frankly wrong to mock a private implementation detail. Your tests shouldn t depend on private implementation details.

但是,如果我是你的话,我这样做的方式是增加一个构造者:

public Foo {
    private readonly IList<MyClass> myList;
    public Foo(IList<MyClass> myList) { this.myList = myList; }
}

然后,利用Moq模拟一个实例:IList<MyClass>并通过施工商通过。

如果你不喜欢这一建议,或者说是虚拟财产:

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

然后利用Moq来推翻该财产。

www.un.org/spanish/ecosoc 但是,你回过错。

问题回答

你有了一个领域,但试图建造一个财产。

改变我的手法为财产could 工作(这里不是分子专家):

private readonly IList<MyClass> myListFiled = new List<MyClass>();
private IList<MyClass> myList {
  get 
   {return myListFiled;}
}




相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签