mardi 18 juin 2019

Unit test for email generation function

I have a function that runs through the properties of a class and replaces the keyword between two dollar signs with the same name from a template.

An example of a class:

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;
    }
}

And this is the function to replace the template with the properties:

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;
}

I'm looking to create a unit test that writes to the console, possible properties that aren't utilized in the template. An example would be if there wasn't a $SubscriptionID$ in the template.





Aucun commentaire:

Enregistrer un commentaire