【问题标题】:Why am I getting this error from NLog during integration testing: LayoutRenderer cannot be found为什么在集成测试期间我从 NLog 收到此错误:找不到 LayoutRenderer
【发布时间】:2020-04-09 00:36:41
【问题描述】:

我在我的 NLog 配置中添加了一些 aspnet 布局渲染器,我的网站一切正常,但是当我尝试运行我的集成测试时,它们失败并显示以下错误消息:

NLog.NLogConfigurationException:在 NLog.Targets.DatabaseParameterInfo 上设置属性“布局”时出错 ----> System.ArgumentException:找不到 LayoutRenderer:'aspnet-request-cookie'。不包括 NLog.Web 吗?

我最初的直觉是听从他们的建议,将 NLog.Web.AspNetCore 包添加到我的集成测试项目中。那没有任何作用。

这是我的集成测试设置的样子:

[OneTimeSetUp]
public static void BaseOneTimeSetUp()
{
    var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Development";
    Assume.That(environment, Is.AnyOf("Development", "CI"), "Integration tests can only run in one of those environments");

    var serviceCollection = new ServiceCollection();
    serviceCollection.AddSingleton<IHostingEnvironment>(p =>
    {
        var mock = new Mock<IHostingEnvironment>();
        mock.SetupGet(m => m.ContentRootPath).Returns(TestContext.CurrentContext.TestDirectory);
        mock.SetupGet(m => m.EnvironmentName).Returns(environment);
        return mock.Object;
    });

    Startup.AddConfiguration(serviceCollection);  //throws NLogConfigurationException
}

这是我对 Startup AddConfiguration 方法的实现:

public static void AddConfiguration(IServiceCollection services)
{
    services.AddSingleton<IConfiguration>(s =>
    {
        var env = s.GetService<IHostingEnvironment>();

        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", false, true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
            .AddEnvironmentVariables();

        var config = builder.Build();

        // This next line throws the NLogConfigurationException
        LogManager.Configuration = new NLogLoggingConfiguration(config.GetSection("NLog"));

        return config;
    });
}

【问题讨论】:

    标签: asp.net-core integration-testing moq nlog


    【解决方案1】:

    集成测试没有调用asp.net WebHost的UseNLog方法,如他们的example code

    WebHost.CreateDefaultBuilder(args)
        .UseStartup<Startup>()
        .ConfigureLogging(logging =>
        {
            logging.ClearProviders();
            logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace);
        })
        .UseNLog();  // NLog: setup NLog for Dependency injection
    

    如果您不想为测试设置 WebHost,可以使用Mock&lt;IWebHostBuilder&gt;

    您需要做的就是在配置 NLog 之前将此添加到您的测试设置中:

    var mockHostBuilder = new Mock<IWebHostBuilder>();
    mockHostBuilder.Object.UseNLog();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-20
      • 1970-01-01
      • 2020-04-10
      • 2017-03-28
      • 1970-01-01
      • 2021-11-28
      • 1970-01-01
      • 2022-08-21
      相关资源
      最近更新 更多