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:
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 ):
or to mock out all of the properties use personMock.StubAll():
As you can see – if no expectation is needed stubbing properties is quite simple in Moq.
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.
By: Stonie on November 26, 2010
at 6:00 am
I think the assertion against the mock object was merely for the purposes of demonstration of the functionality written about in the article
By: John on March 28, 2011
at 7:26 am
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”);
By: Tim Long on September 22, 2011
at 12:11 pm