我在.NET Core中有一个带有单元测试的C#项目。为了在测试期间更好地检查代码流,我真的希望看到内置在代码库中的NLog消息的输出。
我正在使用XUnit,我知道由于并行测试执行,XUnit已经远离Console消息。对于我想要使用ITestOutputHelper
想要完成的事情,我们会非常乐于助人。
有没有办法让NLog日志记录包含在测试输出中?
答案 0 :(得分:2)
我使用这样的东西:
namespace Tests.Builders
{
internal static class Logging
{
public static ILogger DefaultLogger()
{
return NullLogger();
}
public static ILogger NullLogger()
{
return Substitute.For<ILogger>();
}
public static ILogger XUnitLogger(ITestOutputHelper testOutputHelper)
{
// Step 1. Create configuration object
var config = new LoggingConfiguration();
// Step 2. Create targets and add them to the configuration
var consoleTarget = new XUnitTarget(testOutputHelper);
config.AddTarget("xunit", consoleTarget);
// Step 3. Set target properties
consoleTarget.Layout = @"${date:format=HH\:mm\:ss} ${logger} ${message}";
// Step 4. Define rules
var rule1 = new LoggingRule("*", LogLevel.Trace, consoleTarget);
config.LoggingRules.Add(rule1);
// Step 5. Activate the configuration
LogManager.Configuration = config;
return LogManager.GetLogger("");
}
}
[Target("XUnit")]
public sealed class XUnitTarget : TargetWithLayout
{
private readonly ITestOutputHelper _output;
public XUnitTarget(ITestOutputHelper testOutputHelper)
{
_output = testOutputHelper;
}
protected override void Write(LogEventInfo logEvent)
{
string logMessage = this.Layout.Render(logEvent);
_output.WriteLine(logMessage);
}
}
}
public class SomeTests
{
private readonly ITestOutputHelper _output;
public SomeTests(ITestOutputHelper output)
{
_output = output;
}
[Fact]
public void Lets_see_some_output()
{
var foo = new Foo(Logging.XUnitLogger(_output));
var result = foo.ExecuteSomething();
Assert.Equal(true, result);
}
}