Peter
Peter

Reputation: 14108

Is there an equivalent of the Rhino Mocks .Do() method in Moq?

Is there an equivalent of the Rhino Mocks .Do() method in Moq? I am converting my Rhino Mocks code to Moq, and am stuck on the following:

mockedObject
    .Expect(x => x.GetSomething())
    .Do((Func<SomeClass>)(() => new SomeClass());

This is not the same as (in Moq, similar in Rhino Mocks):

mockedObject
    .Setup(x => x.GetSomething())
    .Return(new SomeClass());

When GetSomething() is called multiple times in your unit test, the first piece of code will always return a new instance. The second piece will always return the same instance.

What I want is for my mocked object (with Moq) to always return a new instance. So I actually want to provide an implementation of the GetSomething() method to my mocked object.

Using sequences won't do the trick, because I don't know how many times GetSomething() will be called, nor am I interested in this.

Upvotes: 1

Views: 755

Answers (1)

Andrew Whitaker
Andrew Whitaker

Reputation: 126052

You should be able to pass .Returns a Func<SomeClass> just like you're doing with Rhino mocks:

mockedObject
    .Setup(x => x.GetSomething())
    .Returns(() => new SomeClass());

Upvotes: 3

Related Questions