Functional test based on nlog output

I got some tests that depend on the output from Nlog. I managed to redirect the output to a variable so I can dive into the string to see if everything is okay. There must be a better way to do this, but I couldn't find anything.

Here's the test and the class under test:

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

}

      

Class with an exit:

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

      

0


source to share


1 answer


As an alternative to MethodCall target, suggested by Jeff Bridgman , you can specify NLog Memory-target and check the output in target.Logs



 MemoryTarget target = new MemoryTarget();
    target.Layout = "${message}";

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

    Logger logger = LogManager.GetLogger("Example");
    logger.Debug("log message");

    foreach (string s in target.Logs)
    {
        Console.Write("logged: {0}", s);
    }

      

+2


source







All Articles