Faking Getters and Setters of Properties

By | May 19, 2016

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


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?


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

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

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.
Faking Properties

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.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.