c# - 在集成测试中实现完整日志记录

标签 c# .net .net-core integration-testing .net-core-logging

我正在 .Net Core 3.1 中创建一个新应用。

我已经创建了数据库,现在我正在处理服务集合中的业务逻辑。在我开始创建 API 或 UI(即:任何 Web 应用程序类型的项目)之前,我希望 100% 让所有数据访问和服务首先按预期工作......包括日志记录。为确保一切正常,我想创建一些集成测试。

我遇到的问题是我真的在为如何让日志记录工作而苦苦挣扎。我能找到的每个教程、文档和所有示例都假设您有一个 Program.csStartup.cs

注意 1: 我希望日志记录能够像在生产环境中一样工作,这意味着一直到 SQL。没有 mock 。没有替代品。没有更换。

注意 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);
        }
    }
}

由于 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.
        }
}

测试通过,账户在数据库中正确创建。然而,据我所知,这一行没有做任何事情:

_logger.Log(LogLevel.Information, "An account was created.");

我明白为什么。 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>();
    }
}

这将为 ILogger<> 添加工厂并打开通用以便它们可以在需要的地方注入(inject)。

根据需要为信息的去向配置日志记录。

built-in providers ASP.NET Core 作为共享框架的一部分包含在内,但由于这是一个独立的测试,您必须根据需要添加所需的提供程序。

例如

//...

services.AddLogging(builder => builder.AddConsole().AddDebug());

//...

Console

The Console provider logs output to the console.

Debug

The Debug provider writes log output by using the System.Diagnostics.Debug class. Calls to System.Diagnostics.Debug.WriteLine write to the Debug provider.

Logging output from dotnet run and Visual Studio

Logs created with the default logging providers are displayed:

  • In Visual Studio
    • In the Debug output window when debugging.
    • In the ASP.NET Core Web Server window.
  • In the console window when the app is run with dotnet run.

Logs that begin with "Microsoft" categories are from ASP.NET Core framework code. ASP.NET Core and application code use the same logging API and providers.

引用:Logging in .NET Core and ASP.NET Core

关于c# - 在集成测试中实现完整日志记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65691041/

相关文章:

c# - 如何将图像作为资源包含在我的项目中?

c# - 如何将工具提示添加到数据网格单元格

c# - 将属性添加到关联

c# - 如何使用 Mongo 命令对 DocumentDB 中的文档执行 "patch"操作

.net - 从.Net Core api返回html文件

c# - 如何删除文件、主文件夹和子文件夹

c# - 为什么未分配的局部变量不自动初始化?

c# - 如何从 ASP.NET MVC 中的 404 Not Found 错误中删除查询字符串

c# - 获取第二个不同类型列表中缺少的元素

c# - 对于使用 .NET Core Version 2+ 创建的软件,需要转到 “live” ,是否有任何理由在目标 “live” 操作系统上安装 .NET Core 运行时?