# Friday, 22 July 2016

I started using Microsoft Fakes for some code I was not able to encapsulate and use Interfaces for (my preferred approach) . One of the issues I had was the documentation didn’t appear to be all that good compared to the wealth of information available for RhinoMocks and MOQ especially around Instance methods.

Here is my scenario. I was calling an external class from my code and wanted to test some code that handled an error if the code was called on the second attempt. In Rhino Mocks or MOQ this type of expectation was very easy to code but with Microsoft Fakes the majority of examples appeared to be around static methods.

I knew you could use the AllInstances method for all Instances however I was not clear how I could have an instance do something different when called the next time. My approach was to store the amount of times it was called in a variable and then do something based on that variable count.

Anyway to cut a long story short here is my approach.

    using (ShimsContext.Create())
    {
		int shimCalled =0;
		
		ShimExternalServiceHttpClientBase.AllInstances.GetTransactions =(x,y,z)
		=> 
		{
			shimCalled++;
		    if(shimCalled==1)
			{
				 return Task.FromResult(new List<TransItem>() {new TransItem() {Id = 99}, new TransItem() {Id = 33}});
			}
			
			return Task.FromException<List<TransItem>>(new TransException());
		}
		
		var transcalculator = new TransCalculator();
		
		var results = transcalculator.CalculateResultsForBatch(1);
		
		Assert.AreEqual(2,results.Count);
		
	}

This approach works well for me. Basically on the first call I want data to be returned and on the second call I want to raise an error to check that my code can handle this type of error correctly.  I must also point out that this method I am shimming uses async calls hence the Task.FromResult and Task.FromException being used.

I am not entirely sure if the above is the best approach to use however I was unable to find another way I could use an instance method in this way.



.
Tags: Shims | TDD | Visual Studio

Friday, 22 July 2016 17:09:08 (GMT Daylight Time, UTC+01:00)  #    Comments [0]