Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using FakeItEasy, is there a way to fake the setter of a write only property?

Tags:

c#

fakeiteasy

Using FakeItEasy, is there a way to fake the setter of a write only property?

The interface I have to work with looks something like:

Interface IMyInterface
{
   String Foo { set; }
}

I have tried the following but the syntax doesn't work.

IMyInterface _myObject = A.Fake<IMyInterface>();
A.CallTo(() => _myObject.Foo).Invokes((String foo) => {
   //save off foo
});

I have also tried this, but syntax error.

IMyInterface _myObject = A.Fake<IMyInterface>();
A.CallTo(() => _myObject.set_Foo).Invokes((String foo) => {
   //save off foo
});
like image 961
Kevin Westwood Avatar asked Jul 08 '16 21:07

Kevin Westwood


2 Answers

You can do it, but it's not very straightforward, due to a limitation of expression trees (you can't write an assignment in an expression). The workaround is to use the "advanced" call configuration syntax (described in the docs):

A.CallTo(_myObject)
 .Where(call => call.Method.Name == "set_Foo")
 .Invokes((String foo) => {
   //save off foo
 });

That being said, having a write-only property is probably not a very good idea; if you can set it, you should be able to get it too. If you really want it to be write-only, consider using a method rather than a property.

like image 186
Thomas Levesque Avatar answered Sep 22 '22 06:09

Thomas Levesque


FakeItEasy added a method to handle this case, A.CallToSet

IMyInterface _myObject = A.Fake<IMyInterface>();

// Variant 1
A.CallToSet(() => _myObject.Foo).Invokes(call => {
   var foo = call.GetArgument<string>(0);
   // save off foo
});

// Variant 2
A.CallToSet(() => _myObject.Foo).Invokes((string foo) => {
   // save off foo
});
like image 39
Daniel Rose Avatar answered Sep 21 '22 06:09

Daniel Rose