Matt Roberts

Rails and .NET

  Home  |   Contact  |   Syndication    |   Login
  37 Posts | 0 Stories | 34 Comments | 35 Trackbacks





Tuesday, December 16, 2008 #

There are 2 cool things I want to share here...

Partial Mocking

This is a very cool and useful feature of RhinoMocks, which allows you to test part of a class, but have some of it act normally. Its explained very well here:

Making "protected" methods available for mocking.

Partial mocks are great, but what do you do when you need to "mock" out a method that isn't visible to your test class - i.e. its private or protected. Well, it turns out you can use a nifty little attribute called InternalsVisibleTo to make any internal methods visible to other assemblies (i.e. your testing assembly). So, in my code, I had a method called GetRecord, which was protected. I changed this to make it protected internal virtual, and added this to my AssemblyInfo.cs file:

   1: [assembly: InternalsVisibleTo("NUnitTests")] 
   2: [assembly: InternalsVisibleTo(RhinoMocks.NormalName)] 
   3: [assembly: InternalsVisibleTo(RhinoMocks.StrongName)] 

NUnitTests is the name of my assembly that contains the tests for my project. Once this is done and compiled, intellisense lets me mock that protected method. Just for completeness, here is the code that sets up my partial mock:

   1: var mocks = new MockRepository(); 
   2: var globalSearchServiceBase = mocks.PartialMock<ClassToMock>(); 
   3: Expect.Call(globalSearchServiceBase.GetRecord(1)).IgnoreArguments().Return(GetFakeData()); 
   4: mocks.ReplayAll(); 

Thats it. Hope that was at least marginally useful to someone :)