lundi 23 mai 2016

Tracking Nlog output to validate functional test

I got some tests which relies on the output from Nlog. I've managed to redirect the output to a variable so I can dive into the string to figured out if all went ok. There must be a better way of doing this but I couldn't manage to find anything.

Here's the test and the class being tested:

[TestFixture]
public class ProcessMessagesFromQueues
{
    private static string StuffLogged;

    [SetUp]
    public void Init()
    {
        StuffLogged = string.Empty;
        RedirectNLog();
    }

    private static void RedirectNLog()
    {
        MethodCallTarget target = new MethodCallTarget();
        target.ClassName = typeof(ProcessMessagesFromQueues).AssemblyQualifiedName;
        target.MethodName = "LogMethod";
        target.Parameters.Add(new MethodCallParameter("${message}"));

        NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Debug);
    }

    [Test]
    public void GetNewSmsMessageWhenPublished()
    {
        // Subscribe
        var sqs = FluentNotificationStack.Register(configuration =>
        {
            configuration.Component = "privateapnworker";
            configuration.Environment = "qa28";
            configuration.Tenant = "uk";
        });

        sqs
        .WithSqsTopicSubscriber()
        .IntoQueue("")
        .WithMessageHandler(new ConfigurationSmsHandler())
        .StartListening();

        // Publish
        sqs.WithSnsMessagePublisher<ConfigurationSmsSent>();

        string fakeImei = DateTime.Now.ToLongTimeString();
        string expected = $"Configuration SMS captured! Imei: {fakeImei} status StatusOk{Environment.NewLine}";

        sqs.Publish(new ConfigurationSmsSent(fakeImei, "StatusOk"));

        // Wait for it
        Thread.Sleep(1000);

        // 4. Compare the messages
        StringAssert.Contains(expected, StuffLogged);
    }

    public static void LogMethod(string message)
    {
        StuffLogged += message + Environment.NewLine;
    }

}

The class with the output:

public class ConfigurationSmsHandler : IHandler<ConfigurationSmsSent>
{
    private static readonly Logger Logger = LogManager.GetCurrentClassLogger();

    public bool Handle(ConfigurationSmsSent message)
    {
        Logger.Info($"Configuration SMS captured! Imei: {message.Imei} status {message.Status}");
        return true;
    }
}

Aucun commentaire:

Enregistrer un commentaire