Mocking static methods with Typemock

There are mocking tools like Rhino Mock, Moq, NMock, Typemock and many more. Recently, I was kinda evaluating mocking tools to mock out REST calls in Linq.Flickr. Almost all of the mock tools requires some sort of interface reference to work on. While, to mock out methods like XElement.Load or File.Open is impossible with most of the tools, Typemock is one step ahead of others as it supports mocking of static methods.

Since, all the queries in Linq.Flickr goes through REST and all is tied with somehow with XElement.Load for getting the response in a LINQToXml fashion (I have mentioned already in my earlier posts, how :-)). I wanted to fake out the HTTP layer completely so that sitting in an airplane and with no Internet it is possible to test the product.

Before going to any downloads , lets see how easy is Typemock in this regard.

Now, all starts with a NUnit test class, where I have referenced the Typemock lib and during initialization of the test I faked out XElement.Load method for particular URL request to Flickr. Fragments of the code looks like:

[SetUp]
public void Initialize()
{
   ...
   ...
   // initialize mock 
    MockManager.Init();

    string frobUrl = "http://api.flickr.com/services/rest/?       
    method=flickr.auth.getFrob&api_key=xxxx
    &api_sig=cdeb9a73a771d5ea374d014680b33a0e";
    // custom method to get element locally
    XElement element1 = MockElement(frobUrl, "LinqToFlickrTest.GetFrob.xml"); 
    // create the mock object.
    Mock mock1 = MockManager.Mock(typeof(XElement));
    mock1.ExpectAndReturn("Load", element1).When(frobUrl);
   ...
   ...
}

So, I created a mock object of Type XElement and set it up for an URL so that when request comes in, it will return my response instead of looking into the sky for it. Finally, its all plain old test class, with no suspicious code :-)

[Test]
public void Test()
{
    var query = from photo in _context.Photos
                where photo.SearchMode == SearchMode.TagsOnly 
                && photo.SearchText == "microsoft"
                select photo; 

    int count = query.Count(); 
   ...
   ...
}

Additionally, its nice to check if all the mock worked out fine in TearDown by MockManager.Verify

[TearDown]
public void Verify()
{
    MockManager.Verify();
}

That's it , you can download a working sample right here. If you have Typemock and NUnit installed, I have provided a .BAT for running NUnit through TMockRunner, change the paths accordingly to have it work for you.

In the end, it is worth mentioning that currently Mock.When is only supported in Typemock enterprise edition.Therefore, I will also wrap the dateaccess layer of Linq.Flickr with interfaces so that it is possible to mock with others free tools as well and I will keep the code updated with latest changes so that you can play around it.

kick it on DotNetKicks.com

No Comments