Freigeben über


Evolution of a hand rolled fake - part 2

In a recent discussion at work I realized that the main reason I started with the constructor based fakes descried here was not to clutter the object with properties called SomethingHandler. By having my fake implement the interface explicitly I could create a fake like this:

  1: public class FakeTheInterface : ITheInterface
 2: {
 3:     public Action<int> DoSomething { get; set; }
 4:  
 5:     public Func<int, int, int> ComputeSomething { get; set; } 
 6:  
 7:     void ITheInterface.DoSomething(int x)
 8:     {
 9:         Assert.IsNotNull(this.DoSomething, "Unexpected call to DoSomething");
 10:         this.DoSomething(x);
 11:     }
 12:  
 13:     int ITheInterface.ComputeSomething(int a, int b)
 14:     {
 15:         Assert.IsNotNull(this.ComputeSomething, "Unexpected call to ComputeSomething");
 16:         return this.ComputeSomething(a, b);
 17:     }
 18: }

And this way I can write a test like this:

  19: [TestMethod]
 20: public void UsingFake()
 21: {
 22:     var fakeThing = new FakeTheInterface
 23:                     {
 24:                         ComputeSomething = (a, b) => 42
 25:                     };
 26:     ITheInterface thing = fakeThing;
 27:     Assert.AreEqual(42, thing.ComputeSomething(0, 0));
 28: }

Please disregard the "cast" to the interface in this test. It's because it's a stupid test. Any real test would take this fake object as a dependency somewhere so it would be used in the context of the interface. But the real beauty is that when working with the fake and setting it up you do not get intelli-sense cluttered with the methods and properties of the interface itself, just the things you need to setup the fake.