use*_*704 5 .net c# integration-testing .net-core .net-core-logging
我正在 .Net Core 3.1 中创建一个新应用程序。
我已经创建了数据库,现在正在处理业务逻辑,它位于服务集合中。在开始创建 API 或 UI(即:任何 Web 应用程序类型项目)之前,我希望首先 100% 让所有数据访问和服务按预期工作...包括日志记录。为了确保这一切都能正常工作,我想创建一些集成测试。
我遇到的问题是我真的很苦恼如何让日志记录工作。我能找到的每个教程、文档和所有示例都假设您有一个Program.cs
和Startup.cs
。
注意 1:我希望日志记录像在生产中一样工作,这意味着一直到 SQL。没有嘲笑。没有替代品。无需更换。
注 2:我不太关心测试中的日志记录。我想在服务中进行日志记录。
这是我迄今为止拥有的集成测试 (xUnit) 类的示例。它正在工作,但没有日志记录。
namespace MyApp.Test
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<IAccountService, AccountService>();
services.AddTransient<IAppSettings, AppSettings>();
}
}
public class AccountServiceTests
{
private readonly IAccountService _account;
private readonly IAppSettings _settings;
public AccountServiceTests(IAccountService account, IAppSettings settings)
{
_account = account;
_settings = settings;
}
[Fact]
public async Task AccountService_CreateAccount()
{
Account account = new Account( {...} );
bool result = _account.CreateAccount(account);
Assert.True(result);
}
}
}
Run Code Online (Sandbox Code Playgroud)
由于 NuGet Xunit.DependencyInjection ,DI 正在工作。
然后在服务中...
public class AccountService : ServiceBase, IAccountService
{
protected readonly ILogger _logger;
protected readonly IAppSettings _settings;
public AccountService(ILogger<AccountService> logger, IAppSettings settings)
{
_logger = logger;
_settings = settings;
}
public bool CreateAccount()
{
// do stuff
_logger.Log(LogLevel.Information, "An account was created."); // I WANT THIS TO END UP IN SQL, EVEN FROM THE TEST.
}
}
Run Code Online (Sandbox Code Playgroud)
测试通过,并且帐户已在数据库中正确创建。然而,据我所知,这一行没有做任何事情:
_logger.Log(LogLevel.Information, "An account was created.");
Run Code Online (Sandbox Code Playgroud)
我明白为什么。Microsoft.Extensions.Logging
只是一个抽象,我需要实现一些具体的日志记录(使用 SeriLog 或 Log4Net 等)
这让我回到了最初的问题:在我的一生中,我找不到关于如何使其中之一(SeriLog 或 Log4Net)在集成测试(特别是 xUnit)中工作的工作教程。
任何帮助,或指向正确的方向,或教程的链接都会很棒。谢谢。
使用以下命令将日志记录添加到服务集合中LoggingServiceCollectionExtensions.AddLogging
public class Startup {
public void ConfigureServices(IServiceCollection services) {
services.AddLogging(builder =>
builder.ClearProviders()
.Add{ProverNameHere}()
// ... other logging configuration
);
services.AddTransient<IAccountService, AccountService>();
services.AddTransient<IAppSettings, AppSettings>();
}
}
Run Code Online (Sandbox Code Playgroud)
这将添加工厂并开放通用,ILogger<>
以便可以在需要的地方注入它们。
根据需要配置日志记录以了解该信息应存放的位置。
ASP.NET Core 包含一些内置提供程序作为共享框架的一部分,但由于这是一个独立的测试,您必须根据需要添加所需的提供程序。
例如
//...
services.AddLogging(builder => builder.AddConsole().AddDebug());
//...
Run Code Online (Sandbox Code Playgroud)
安慰
控制台提供程序将输出记录到控制台。
调试
提供
Debug
者使用该类写入日志输出System.Diagnostics.Debug
。调用写信System.Diagnostics.Debug.WriteLine
给Debug
提供者。
记录 dotnet run 和 Visual Studio 的输出
显示使用默认日志记录提供程序创建的日志:
- 在视觉工作室中
- 调试时在Debug输出窗口中。
- 在 ASP.NET Core Web 服务器窗口中。
- 当应用程序通过 dotnet run 运行时,在控制台窗口中。
以“Microsoft”类别开头的日志来自 ASP.NET Core 框架代码。ASP.NET Core 和应用程序代码使用相同的日志记录 API 和提供程序。
归档时间: |
|
查看次数: |
7034 次 |
最近记录: |