1

I am using FakeItEasy to check that a call to the public setter method of a property has been called.

The property is called Description, and at the moment I am testing it like this:

A.CallTo(model)
    .Where(x => x.Method.Name.Equals("set_Description"))
    .WithAnyArguments()
    .MustHaveHappened();

This works functionally, however the downside of using a magic string for the method name is that if I refactor the name of the property, the test will fail and I will have to manually change the strings in all of the tests.

Ideally, I would like to know of a way to do it like in this piece of pseudocode:

var setterName = model.GetType()
                         .SelectProperty(x => x.Description)
                         .GetSetterName();

A.CallTo(model)
    .Where(x => x.Method.Name.Equals(setterName))
    .WithAnyArguments()
    .MustHaveHappened();

This way, if I right-click refactor the Description property, the tests won't need to be updated. How can I do this?

James Monger
  • 10,181
  • 7
  • 62
  • 98

3 Answers3

3

Your pseudocode was on the right track.

var setterName = model.GetType()
                     .GetProperty(nameof(Description))
                     .GetSetMethod();

Note that nameof is only available in C# 6.

Dennis_E
  • 8,751
  • 23
  • 29
  • Thanks for the help, @Dennis_E. I chose Terje's answer as it is a bit more concise, however I appreciate you taking the time to answer. I also appreciate that yours is a bit more robust as it does not even include the `set_` string. Thanks again! – James Monger Feb 24 '16 at 11:30
2

I think you can do this with the nameof keyword: https://msdn.microsoft.com/en-us/library/dn986596.aspx

So I guess it would be something like

.Where(x => x.Method.Name.Equals("set_" + nameof(x.Description))
Terje Kolderup
  • 367
  • 3
  • 12
1

Note that as of FakeItEasy 2.0.0, if the setter has a getter as well, you can use the new A.CallToSet method:

A.CallToSet(() => model.Description).MustHaveHappened();
Blair Conrad
  • 233,004
  • 25
  • 132
  • 111