C# – Need help understanding Mocks and Stubs

cunit testing

I'm new to use mocking frameworks and I have a few questions on the things that I am not clear on. I'm using Rhinomocks to generate mock objects in my unit tests. I understand that mocks can be created to verify interactions between methods and they record the interactions etc and stubs allow you to setup data and entities required by the test but you do not verify expectations on stubs.

Looking at the recent unit tests I have created, I appear to be creating mocks literally for the purpose of stubbing and allowing for data to be setup. Is this a correct usage of mocks or is it incorrect if you're not actually calling verify on them?

For example:

user = MockRepository.GenerateMock<User>();
        user.Stub(x => x.Id = Guid.NewGuid());
        user.Stub(x => x.Name = "User1");

In the above code I generate a new user mock object, but I use a mock so I can stub the properties of the user because in some cases if the properties do not have a setter and I need to set them it seems the only way is to stub the property values. Is this a correct usage of stubbing and mocking?

Also, I am not completely clear on what the difference between the following lines is:

user.Stub(x => x.Id).Return(new Guid());

user.Stub(x => x.Id = Guid.NewGuid());

Best Answer

Mocks and stubs are abstract concepts. Looking at the docs you can find a way to create a Stub:

MockRepository.GenerateStub<...>

But it seems that they also decided to make it convenient to stub a method of a Mock, like you're doing.

Greg Moeck made a great presentation about the use of mocks: http://www.youtube.com/watch?v=R9FOchgTtLM

Related Topic