Mocking Extension Methods

With Orcas and TypeMock 4.1 you can now mock Extension methods, easily.

Suppose we added a new method to int that return the Roman Number equivalent of that number:

public static class Extend { public static string RomanNumber(this int number) { // do complex logic return romanString; } }


Now we use this method in our code

string romanNumber = 2010.RomanNumber();

Here is how we mock this.

Reflective Mocks (Community Edition)

We mock that actual static extension method

Mock extentionMethodMock = MockManager.Mock(typeof(Extend)); extentionMethodMock.ExpectAndReturn("RomanNumber","MCMLIX");

Natural Mocks (Professional Edition)

We just call the extension method

using (RecordExpectations rec = new RecordExpectations()) { rec.ExpectAndReturn( 2010.RomanNumber(), "MCMLIX"); }

Checking Arguments

Care should be taken when Checking Arguments as the first argument is the instance of the type we are extending, suppose the extension method takes another argument

public static class Extend { public static string RomanNumber(this int number, bool upperCase) { // do complex logic return romanString; } }
 

Here is how we validate the arguments.

Reflective Mocks (Community Edition)

We have to implicitly ignore the first argument

// first arg is instance, second must be false Mock extentionMethodMock = MockManager.Mock(typeof(Extend)); extentionMethodMock.ExpectAndReturn("RomanNumber","MCMLIX"). Args(Check.IsAny(),false);

Natural Mocks (Professional Edition)

TypeMock automatically handles the first argument

using (RecordExpectations rec = new RecordExpectations()) { // TypeMock knows that this is an extension method and ignores first argument automatically rec.ExpectAndReturn( 2010.RomanNumber(false), "MCMLIX") .CheckArguments(false); }
 

Bookmark at:
Add 'Mocking Extension Methods' to Del.icio.us Add 'Mocking Extension Methods' to digg Add 'Mocking Extension Methods' to reddit Add 'Mocking Extension Methods' to Feed Me Links! Add 'Mocking Extension Methods' to Technorati Add 'Mocking Extension Methods' to Yahoo My Web Add 'Mocking Extension Methods' to Newsvine Add 'Mocking Extension Methods' to FURL Add 'Mocking Extension Methods' to blinklist Add 'Mocking Extension Methods' to My-Tuts 

12 October 2007 | TDD, Product | Comments | Print This Post

Leave a Reply

  1.  
  2.  
  3.  
Search Eli Lopian’s Blog (TypeMock)

Navigation

Recent Posts

Categories

Archives

Managment