Posted by: ronniebarker | March 24, 2009

Stubs in Moq

I had a discussion today regarding Moq and how to make a quick stub of a property so that a mock object could be thrown into somewhere and have the properties work as simple properties. The simple answer weas to use an expectation:

image

But that felt ugly – and not as useful as it could be.

After playing around for a while I found the Moq.Stub namespace. After placing a using to this namespace at the top you can do something along the lines of personMock.Stub( p => p.Name ):

image

or to mock out all of the properties use personMock.StubAll():

image

As you can see – if no expectation is needed stubbing properties is quite simple in Moq.


Responses

  1. Why are you asserting against the mock? I can’t see where you are testing anything concrete? (the SUT) isn’t the point of the mock is that you use it to test against some real code?

    Maybe that is your intent? But it might be clearer if you include the SUT in your example?

    Regards,
    Stonie.

  2. I think the assertion against the mock object was merely for the purposes of demonstration of the functionality written about in the article

  3. There’s no need to use teh Stub namespace. The same result is achieved with:

    // start “tracking” sets/gets to this property
    mock.SetupProperty(f => f.Name);

    // alternatively, provide a default value for the stubbed property mock.SetupProperty(f => f.Name, “foo”);


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Categories

Follow

Get every new post delivered to your Inbox.