How to make a "protected" method available for "partial" mocking using RhinoMocks

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: )/Rhino+Mocks+Partial+Mocks.ashx)

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;

3: Expect.Call(globalSearchServiceBase.GetRecord(1)).IgnoreArguments.Return(GetFakeData);

4: mocks.ReplayAll;

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

This article is part of the GWB Archives. Original Author: Matt Roberts

New on Geeks with Blogs

  • We Won The One Award I Actually Care About

    Full Scale made the Inc. 5000 for the fifth year straight, the 12th listing across my three companies. Here is why the one award you cannot buy is worth stopping for.

  • Your Customers Build the Features Now

    I let a tool I liked sit dead for a year rather than build the features I wanted. An MCP server meant I never had to, and your customers can do the same to your product.

  • Get the Size of a Directory in Linux the Easy Way

    du -sh for the quick answer, ncdu for the cleanup, df for the disk itself: every command for checking directory size in Linux, plus why du and df never agree.

  • Vim Search and Replace: The Ultimate Guide

    One :%s command replaces every match in a file before a find dialog would even open. The Vim substitute patterns worth the muscle memory: flags, ranges, capture groups, and multi-file edits.