Using Rhino Mocks to test private methods on an abstract class

Firstly it is arguable that you should not be trying to directly test a private method on an abstract class, as tests should focus on the public methods, it should be upto the class where it uses private methods. However, if you do want to do this there is a way. In my case I was trying to use Test Driven Development to modify an existing code base without unit tests. Rather than retro-fit them to the rest of the code I wanted to minimise the code I was testing by directly testing a private method (which happened to be on an abstract class).

The method I chose used two sub-methods, one for testing abstract classes and one for testing private methods, and they actually fitted together really easily.

  1. Use Rhino Mocks test the abstract class – Rhino Mocks allows for testing of abstract classes using the ‘partial mock‘ concept.
  2. Use visual studio private accessors to access the private methods – If you have a version of Visual Studio that supports MS Test you can simply right click on a private method and choose ‘Create Private Accessor’. The accessor that is created accepts an instance of the class as a constructor, so when you pass in the Partial Mock created previously you end up with a class exposing the private methods as public that can be directly called… awesum!
Advertisements

About Alex McMahon

I am a software developer, interested in .net, agile, alt.net. I've previously specialised with .net 3.0 technologies like WCF, whereas now I am trying to specialise in agile development and best practice and patterns. I am obsessed with looking at the latest technologies, tools, and methods, and trying them out. I am currently employed by Rockwell Collins in the UK.
This entry was posted in development, mocks, TDD, testing. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s