Mocking Caliburn Micro's IoC.Get<T>

Caliburn Micro has made a name for itself as one of the easiest to use MVVM Frameworks around. Caliburn Micro comes in with its own built-in service locator, under the IoC class. This class primarly consists of two static methods, IoC.Get<T> and IoC.GetInstance, which allows you to access IoC container from anywhere in code as follows.
  1. var instance = IoC.Get<LogService>();  
  2. var instance = IoC.GetInstance(typeof(LogService),null);  
As one can observe from the code above, these two methods come across as extremely handy for the developer.
Having said so, one of the questions that frequently arises is how do you test a method which consists of either of the above two method calls? To explain the scenario better, let us write a sample method, for which we would write our unit tests.
  1. public class SampleClass  
  2. {  
  3.     public double GetResult(IEnumerable<double> data)  
  4.     {  
  5.         var sampleService = IoC.Get<SampleService>();  
  6.         var result = sampleService.ProcessResult(data);  
  7.         // Do further processing  
  8.         return finalResult;  
  9.     }  
  10. }  
The best way to proceed with writing Unit Test would be to let the IoC create an instance of SampleService via Dependency Injection. However, for the sake of example, let us assume we do not have the luxury of making changes to GetResult code. Our sample Unit Test would look as follows:
  1. [Test]  
  2. public void GetResultRandomInput()  
  3. {  
  4.     var expectedResult = 25;  
  5.     var sampleClass = new SampleClass();  
  6.     var actualResult = sampleClass.GetResult(Enumerable.Range(1,10));  
  7.     Assert.AreEqual(expectedResult,actualResult);  
  8. }  
With the restriction in hand, we now have to figure out a way to mock the IoC.Get<T> method. Let us examine the IoC.Get<T> source code first.
  1. public static T Get<T>(string key = null)  
  2. {  
  3.     return (T)GetInstance(typeof(T), key);  
  4. }  
As you can observe, the IoC.Get<T> method internally calls the IoC.GetInstance method. We will advance to observe the IoC.GetInstance method now. Let us begin by looking at the signature.
  1. public static Func<Type, stringobject> GetInstance;  
GetInstance is Func of type Func<Type,string,object> and the trick to mock the IoC.Get<T> would be to override the IoC.GetInstance in the Unit Tests. For Example
  1. Caliburn.Micro.IoC.GetInstance = (type, _) =>  
  2. {  
  3.     if (type == typeof(SampleService))  
  4.     {  
  5.         return SampleService  
  6.         {  
  7.             // Initialize properties if needed  
  8.         };  
  9.     }  
  11.     return new Exception("Type not registered with IoC");  
  12. };  
That's all you need to mock the IoC.Get and IoC.GetInstance methods.