views:

29

answers:

1

I'm familiar with unit testing, but am still learning about mocks and mocking frameworks. I get the ideas (I think), but the syntax still seems a little foreign. I'm considering creating some T4 templates that automatically generate mock implementations of interfaces and classes. Using a combination of generics and extension methods, this would let me do things like this:

var service = new MockCustomerService(); //code-generated and implements ICustomerService, has a method named 'Insert'
var target = new CustomerController(service);
var item = new Customer();
target.Insert(item);
service.InsertMethod.Assert.WasLastCalledWith(item);

or:

var service = new MockCustomerService(); //code-generated and implements ICustomerService, has a method named 'GetById'
var target = new CustomerController(service);
var item = new Customer();
target.GetByIdMethod.ShouldReturn(item);
var actual = target.Edit(1);
service.GetByIdMethod.Assert.WasLastCalledWith(1);
Assert.AreEqual(actual.ViewData.Model, item);

First, is this even really "mocking", or am I missing something fundamental. Second, does this seem like it would be a sound approach, or are there reasons for using a framework beyond not having to manually create similar classes? Third, is there anything else out there that does similar? I've looked around and haven't found much...

A: 

First, is this even really "mocking", or am I missing something fundamental.

The second example you show, there is a mocking that happens at this line:

target.GetByIdMethod.ShouldReturn(item);

This enables you to return a fake value for target.GetByIdMethod (item), without actually calling the target.GetByIdMethod.

Second, does this seem like it would be a sound approach, or are there reasons for using a framework beyond not having to manually create similar classes?

The reason why we use mocking framework, is that we want to return fake values for certain methods so that we can easily control what we want to test. Also, by using a mocking framework, we can also assert that the correct method was called, and/or with correct parameters.

Third, is there anything else out there that does similar?

What do you mean? Are you saying that are there any mocking framework that does the similar thing? Or that is there any unit test code template generation engine out there? There are a lot of mocking frameworks out there. As to whether there are any unit test code template generation engine, well, I am not sure about that.

Ngu Soon Hui
Thanks for the answer. To be clear, I'm talking about code gen to generate actual concrete mock objects, not to generate unit tests. In other words, I'm thinking that T4-generating a MockCustomerService might be better than using something like RhinoMocks, Moq, etc. to generate it at runtime.
Daniel