I'm using rhino mock in my unit tests and I'm trying to create a mock using the following code:

var userDetails = MockRepository.GenerateMock<ReadOnlyCollection<UserDetails>>();

But when I run the unit test I get the following error:

Can not instantiate proxy of class: 
System.Collections.ObjectModel.ReadOnlyCollection`
1[[SolutionName.FolderName,]].
Could not find a parameterless constructor.

I have searched on the net and found similar questions and solutions, one for moq using the SetupGet() method but I don't know what the equivalent of this is in rhino mocks. (The UserDetails class does have a parameterless constructor) How do I create a stub/mock for the ReadOnlyCollection?

有帮助吗?

解决方案

You can pass any constructor arguments to GenerateMock:

var inner = new List<UserDetails>();
var userDetails = MockRepository.GenerateMock<ReadOnlyCollection<UserDetails>>(inner);

You may want to consider creating an instance of ReadOnlyCollection in your test and returning it from some other method call, which will be much simpler than mocking the appropriate methods.

其他提示

Not sure you can do this with Rhino Mock. The issue is that ReadOnlyCollection is not an interface, nor does it contain virtual methods, which open source mocking frameworks can work with.

Since ReadOnlyCollection implements IList you could try the suggested method found in this SO question

How to mock a private readonly IList<T> property using moq

Basically use an IList collection as a public property, but make the underlying list private, so you still get that read-only experience. Thus in your tests, you can use:

var userDetails = MockRepository.GenerateMock<IList<UserDetails>>();

If you really want to mock a ReadOnlyCollection, the you will need to buy either TypeMock or JustMock. Alternatively, get Visual Studio 2012 Premium with Update 2, where you can use the MS Fakes mocking framework.

EDIT: Lee's answer is much more efficient then mine :) I would suggest that one instead.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top