基于nlog输出的功能测试

时间:2016-05-23 13:04:08

标签: c# testing nlog

我得到了一些依赖于Nlog输出的测试。我已经managed to redirect the output到一个变量,所以我可以深入到字符串中找出是否一切正常。必须有更好的方法来做到这一点,但我无法找到任何东西。

以下是测试和正在测试的课程:

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

}

带有输出的类:

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

1 个答案:

答案 0 :(得分:3)

作为MethodCall目标的替代方案suggested Jeff Bridgman, 你可以指定NLog Memory-target 并验证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);
    }