本文介绍了基于nlog输出的功能测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我进行了一些测试,这些测试依赖于Nlog的输出.我已经设法将输出重定向到一个变量中,这样我就可以深入研究一下字符串以弄清楚是否一切正常.一定有更好的方法可以做到这一点,但我什么也找不到.
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;
}
}
带有输出的类:
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;
}
}
推荐答案
作为MethodCall目标的替代方法,建议通过 Jeff Bridgman ,您可以指定NLog 内存目标并验证target.Logs中的输出
As an alternative to the MethodCall target, suggested by Jeff Bridgman,you can specify NLog Memory-targetand verify 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);
}
这篇关于基于nlog输出的功能测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!