Rhino Mocks V2: Some Progress Made
I made quite a progress, mostly thanks to this article. I'm totally and completely blown away by the capabilities of Castle.DynamicProxy, it open up a whole world of facinating possibilities.
For instance, I wanted to get rid of this type of code:
IView view = mockView.MockInstance as IView;
view.DoSomething();
mockView.ReturnsFor(3, someVal);
I wanted to be able to do something much simpler, like this:
IView view = mocks.CreateMock(typeof(IView));
view.DoSomething();
LastCall.On(view).Returns(someVal).Repeat(3);
It doesn't look like a great improvement, doesn't it? But this means that you no longer has to sync two objects for each mock. I thought a lot about how I would implement this in my code. LastCall is a static class, and has no information about the mocked instance beyond what I'm passing as an argument. I needed some way to get to the MockRepository from the mocked instance.
I though about using a static table, with all the mocked instances as keys, and the value being the MockRepository. But this has several disadvantages, chief among them are:
- It's ugly hack.
- It's a huge memory leak, those objects would never be released as long as the AppDomain is loaded.
What I really wanted was to do this:
public static IMethodOptions On(object mockedInstance)
{
IMockedObject mockedObj = mockedInstance as IMockedObject;
//error handling if mockedObj is null
return mockedObj.Repository.MethodOptions[mockedInstance];
}
Using Castle.DynamicProxy, it was as easy as modifying the types implemented by the mocked object, and handling the type with the interceptor. It took me some time to figure it out, but when I did, it was so easy that I couldn't believe. So the above code is not possible due to around three or four lines of code. And I'm very pleased to find a new tool.
Comments
Comment preview