James Monger
James Monger

Reputation: 10685

Get method name of property setter in c#

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?

Upvotes: 1

Views: 1476

Answers (3)

Blair Conrad
Blair Conrad

Reputation: 242060

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();

Upvotes: 1

Dennis_E
Dennis_E

Reputation: 8904

Your pseudocode was on the right track.

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

Note that nameof is only available in C# 6.

Upvotes: 3

Terje Kolderup
Terje Kolderup

Reputation: 387

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))

Upvotes: 2

Related Questions