单元测试以检查未使用的属性

时间:2019-06-18 12:07:07

标签: c# regex unit-testing reflection nunit

我有一个贯穿类属性的函数,该函数用模板中的相同名称替换两个美元符号之间的关键字。

一个类的例子:

public class FeedMessageData : IMailObject
{
    public string Username { get; private set;}
    public string SubscriptionID { get; private set; }
    public string MessageTime { get; private set; }
    public string Subject { get; private set; }

    public FeedMessageData(string username, string subscriptionID, DateTime messageTime)
    {
        this.Username = username;
        this.SubscriptionID = subscriptionID;
        this.MessageTime = messageTime.ToShortDateString();

        this.Subject = "Feed " + DateTime.Now + " - SubscriptionID: " + this.SubscriptionID;
    }
}

这是用属性替换模板的功能:

private string mergeTemplate(string template, IMailObject mailObject)
{
    Regex parser = new Regex(@"\$(?:(?<operation>[\w\-\,\.]+) ){0,1}(?<value>[\w\-\,\.]+)\$", RegexOptions.Compiled);

    var matches = parser.Matches(template).Cast<Match>().Reverse();
    foreach (var match in matches)
    {
        string operation = match.Groups["operation"].Value;
        string value = match.Groups["value"].Value;

        var propertyInfo = mailObject.GetType().GetProperty(value);
        if (propertyInfo == null)
            throw new TillitException(String.Format("Could not find '{0}' in object of type '{1}'.", value, mailObject));

        object dataValue = propertyInfo.GetValue(mailObject, null);

        template = template.Remove(match.Index, match.Length).Insert(match.Index, dataValue.ToString());
    }
    return template;
}

我正在寻找创建一个写入控制台的单元测试,这些可能未在模板中使用的属性。例如,如果模板中没有$ SubscriptionID $。我尝试使用PropertyInfo,它为我提供了类的属性,但是如何使用此信息来检查模板中是否已使用它们?

1 个答案:

答案 0 :(得分:1)

Moq(https://github.com/moq/moq4/wiki)提供了验证属性/方法访问的方法。 有关更多详细信息,请遵循this link上的教程。要验证模板中是否使用了您的属性,可以使用VerifyGet方法,如下例:

[Fact]
public void VerifyAllPropertiesHaveBeenConsumedInTemplate()
{
    var mockMailObject = new Mock<IMailObject>();
    var template = "yourTemplateOrMethodThatReturnsYourTemplate";

    var result = mergeTemplate(template, mockMailObject.Object);

    mockMailObject.VerifyGet(m => m.Username, Times.Once);
    mockMailObject.VerifyGet(m => m.SubscriptionID, Times.Once);
    mockMailObject.VerifyGet(m => m.MessageTime, Times.Once);
    mockMailObject.VerifyGet(m => m.Subject, Times.Once);
}