Ran*_*age 5 c# logging unit-testing .net-core
我试图将一些简单的控制台日志记录添加到ASP.NET Core 2.2中的单元测试中,并且由于日志记录配置发生更改而遇到了麻烦。
我目前有以下代码,该代码为我的课程“ DataTests”创建了一个记录器:
// create logger for our unit tests
var serviceProvider = new ServiceCollection()
.AddLogging()
.BuildServiceProvider();
var factory = serviceProvider.GetService<ILoggerFactory>();
var logger = factory.CreateLogger<DataTests>();
Run Code Online (Sandbox Code Playgroud)
但是它不会登录到调试窗口,因此我无法对其进行配置。我想做类似的事情
factory.AddDebug();
Run Code Online (Sandbox Code Playgroud)
但是该扩展名已过时,不再可用。它由ILoggingBuilder上的扩展而不是ILoggerFactory代替。这就是在program.cs中使用的方式
public static void Main(string[] args)
{
var webHost = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.ConfigureAppConfiguration((hostingContext, config) =>
{
var env = hostingContext.HostingEnvironment;
config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json",
optional: true, reloadOnChange: true);
config.AddEnvironmentVariables();
})
.ConfigureLogging((hostingContext, logging) =>
{
// Requires `using Microsoft.Extensions.Logging;`
logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
logging.AddConsole();
logging.AddDebug();
logging.AddEventSourceLogger();
})
.UseStartup<Startup>()
.Build();
webHost.Run();
}
Run Code Online (Sandbox Code Playgroud)
我的问题是我不知道如何从单元测试类中获取ILoggingBuilder。有人知道怎么做吗?可耻的是,将简单的记录器添加到简单的单元测试类太复杂了-我认为默认情况下应内置此记录器。
由于您使用的是 .NET Core,我假设您也在使用xUnit。
xUnit 使用特定的接口来登录控制台,ITestOutputHelper该接口由 xUnit 本身注入到测试装置构造函数中。
有一个 NuGet 包https://www.nuget.org/packages/Divergic.Logging.Xunit,它可以创建一个ILogger<T>包装器ITextOutputHelper,以便能够将它们传递到需要该ILogger接口的系统。
我的 xUnit 测试没有使用依赖注入框架,最终我自己用模拟版本将它们连接起来,所以这就是我所做的。
using Xunit;
using Xunit.Abstractions;
public sealed class MyTestFixture
{
private readonly ILogger<MyClass> _logger;
public MyTestFixture(ITestOutputHelper helper)
{
_logger = helper.BuildLoggerFor<MyClass>();
}
[Fact]
public void FooBar()
{
var myClass = new MyClass(_logger);
myClass.WizzBang();
}
}
Run Code Online (Sandbox Code Playgroud)
根据Matthew 的回答,根据Capturing Output中的 xUnit 文档,按照其站点中的示例将控制台日志记录添加到任何单元测试非常简单:
using Xunit;
using Xunit.Abstractions;
public class MyTestClass
{
private readonly ITestOutputHelper output;
public MyTestClass(ITestOutputHelper output)
{
this.output = output;
}
[Fact]
public void MyTest()
{
var temp = "my class!";
output.WriteLine("This is output from {0}", temp);
}
}
Run Code Online (Sandbox Code Playgroud)
使用AddLogging(IServiceCollection, Action<ILoggingBuilder>)重载:
var serviceProvider = new ServiceCollection()
.AddLogging(builder => {
builder.AddDebug(); //<--
//...add other logging configuration as needed
})
.BuildServiceProvider();
//...
Run Code Online (Sandbox Code Playgroud)
它允许通过配置委托访问构建器。