简体   繁体   English

在C#中获取属性设置器的方法名称

[英]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. 我正在使用FakeItEasy来检查是否已调用对属性的公共setter方法的调用。

The property is called Description , and at the moment I am testing it like this: 该属性称为Description ,目前我正在像这样测试它:

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. 这样,如果我右键单击重构Description属性,则不需要更新测试。 How can I do this? 我怎样才能做到这一点?

Your pseudocode was on the right track. 您的伪代码在正确的轨道上。

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

Note that nameof is only available in C# 6. 请注意, nameof仅在C#6中可用。

I think you can do this with the nameof keyword: https://msdn.microsoft.com/en-us/library/dn986596.aspx 我认为您可以使用nameof关键字来做到这一点: https : nameof

So I guess it would be something like 所以我想那会是

.Where(x => x.Method.Name.Equals("set_" + nameof(x.Description))

请注意,从FakeItEasy 2.0.0开始,如果setter也具有getter,则可以使用新的A.CallToSet方法

A.CallToSet(() => model.Description).MustHaveHappened();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM