Faking Getters and Setters of Properties

This post on Faking Getters and Setters of Properties using FakeItEasy will help you to configure the behavior of the properties of the objects you fake. This is not as apparent as the various techniques on configuring the behavior of the methods of the faked objects. Getters and Setters are as configurable as regular methods of faked objects when it comes to FakeItEasy

WHY

FakeItEasy gives good support on configuring the behavior of faked object’s methods. What about Properties? They have only Get and Set methods on them. How to go about faking getters and setters of properties of the faked objects? The end user does not invoke them explicitly. We just get the property value (which invokes Get internally) or assign some value to the property (which invokes Set internally). So how to configure their behaviour?

HOW

In short if you prefix your property name with “get_” or “set_” then FakeItEasy allows you to configure the behaviour of Getters and Setters of the properties.

I know. Time for code. We will have a property. We want it to throw an exception when someone sets it to the value of say 40.

Here are the usual suspects. First the interface IDemoInterface.cs

C#

1

2

3

4

5

6

7

namespacePropertyFakingDemo

{

publicinterfaceIDemoInterface

{

intUnderTest{get;set;}

}

}

We will create a fake implementing this interface.
So here is the test class Testing.cs

C#

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

usingFakeItEasy;

usingFakeItEasy;

usingSystem;

usingXunit;

namespacePropertyFakingDemo

{

publicclassTesting

{

[Fact]

publicvoidFaking_property_setter()

{

varsut=A.Fake();

A.CallTo(sut).Where(x=>x.Method.Name.Equals("set_UnderTest"))

.WhenArgumentsMatch(x=>x.Get(0).Equals(40))

.Throws();

Assert.Throws(()=>sut.UnderTest=40);

}

[Fact]

publicvoidFaking_property_getter()

{

varsut=A.Fake();

A.CallTo(()=>sut.UnderTest).Throws();

Assert.Throws(()=>sut.UnderTest);

}

}

}

Important line has been highlighted. See how we are configuring a method of name “set_UnderTest“. There is no such method in the interface. It is FakeItEasy way of allowing you access to the setter of the property and configuring it to your liking. Here we tell FakeItEasy that when the property is set to the value 40, please throw an Argument exception. And as expected, the test passes. Indeed the Argument exception was thrown.

As some readers pointed out, the example is not complete as I did not show how to fake the getters of the property. I have updated the sample. It is actually delightfully simple to fake the getters. The highlighted line shows how to do it. And it is self explanatory.

With this knowledge you can now put all the method configuring techniques you know in FakeItEasy on the Properties of the faked objects as well. Happy Faking.