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

2

7

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
});
Gley answered 8/7, 2016 at 21:22 Comment(0)
R
7

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.

Raycher answered 8/7, 2016 at 22:23 Comment(1)
I agree with your assessment of a write only property as well. In this case, it really should be a method, but I cannot change it.Gley
A
4

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
});
Aftermost answered 7/7, 2020 at 10:26 Comment(1)
I don't think this works; a get-less property just won't convert to Expression<Func<T>>.Purport

© 2022 - 2024 — McMap. All rights reserved.