Share via


Evolution of a hand rolled fake - part 3

So how do I fake an interface with properties?

  1: interface IAnotherInterface
 2: {
 3:     int SomeProperty { get; }
 4:     int SomeOtherProperty { get; set; }
 5: }

Most of the time I just let my fake have the property implemented. This works most of the time but only really well if the interface properties are truly just data carriers. If there is a chance the properties can throw exceptions or if a property needs to be initialized specifically for each test I might go with the property method approach. Here is an example of both:

  6: public class FakeAnotherInterface : IAnotherInterface
 7: {
 8:     public int SomeProperty { get; set; }
 9:  
 10:     public Func<int> SomeOtherProperty_Get { get; set; }
 11:  
 12:     public Action<int> SomeOtherProperty_Set { get; set; }
 13:  
 14:     int IAnotherInterface.SomeOtherProperty
 15:     {
 16:         get
 17:         {
 18:             Assert.IsNotNull(
 19:                 this.SomeOtherProperty_Get, 
 20:                 "Unexpected call getting SomeOtherProperty");
 21:             return this.SomeOtherProperty_Get();
 22:         }
 23:  
 24:         set
 25:         {
 26:             Assert.IsNotNull(
 27:                 this.SomeOtherProperty_Set, 
 28:                 "Unexpected call setting SomeOtherProperty {0}", value);
 29:             this.SomeOtherProperty_Set(value);
 30:         }
 31:     }
 32: }