【问题标题】:Net Core ILogger Value cannot be nullNet Core ILogger 值不能为空
【发布时间】:2018-11-12 06:59:34
【问题描述】:

我正在接收 Logger 值不能为空。我正在尝试解决这个问题,也许是依赖注入。在单元测试和程序中的其他任何地方都会收到错误。我进行依赖注入是否正确?

Expected: <System.ArgumentException>
But was:  <System.ArgumentNullException: Value cannot be null.
  Parameter name: logger
  at Microsoft.Extensions.Logging.LoggerExtensions.Log(ILogger logger,
                     LogLevel logLevel, EventId eventId, Exception exception,
                     String message, Object[] args)   

我的代码如下:

using System;
using ElectronicsStore.Models;
using Microsoft.Extensions.Logging;

namespace ElectronicsStore.Service
{
    public class ParseVendorSupply
    {
        private readonly ILogger _logger;

        public ParseVendorSupply(ILogger logger)
        {
            _logger = logger;
        }

        public VendorSupply FromCsv(string csvLine)
        {
            VendorSupply vendorsupply = new VendorSupply();

            try
            {
                string[] values = csvLine.Split(',');
                if (values.Length > 3)
                {
                    throw new System.ArgumentException("Too much data");
                }

                vendorsupply.VendorId = Convert.ToInt16(values[0]);
                vendorsupply.ProductId = Convert.ToInt16(values[1]);
                vendorsupply.Quantity = Convert.ToInt16(values[2]);
            }
            catch (Exception)
            {
                _logger.LogInformation("An exception was thrown attempting");
            }
            return vendorsupply;
        }       
    }
}

public Startup(IConfiguration configuration, ILogger<Startup> logger)
{
    Configuration = configuration;
    _logger = logger;
 }

public void ConfigureServices(IServiceCollection services)
{
     services.AddSingleton(new LoggerFactory().AddConsole().AddDebug());
     services.AddLogging();

NUnit 测试:

public class ParseVendorSupplyNunit
{

    ILogger logger;

    //conducting this gives me an error, since cannot create instance of abstract class, not sure what alternative is
    //ILogger logger = new ILogger();

    [Test]
    public void FromCsv_ParseCorrectly_Extradata()
    {
        string csvLineTest = "5,8,3,9,5";
        ParseVendorSupply parseVendorSupplytest = new ParseVendorSupply(logger);
        //VendorSupply vendorsupply = parseVendorSupplytest.FromCsv(csvLineTest);
        Assert.That(() => parseVendorSupplytest.FromCsv(csvLineTest), Throws.ArgumentException);
    }

【问题讨论】:

  • 你在单元测试类中没有初始化你的logger实例。
  • 你需要在单元测试类的某处初始化你的logger实例
  • 你必须构造一个具体类型的对象,而不是接口,要么选择实现接口的具体类型之一,要么实现一个虚拟记录器以进行测试。您还可以使用模拟工具(例如 Rhinomocks 或 NSubstitute)来提供实现。

标签: c# logging asp.net-core nunit


【解决方案1】:

您必须使用 ILogger 的实现来初始化 logger 变量,例如 ConsoleLogger 或类似的东西。目前,您没有为您的测试 logger 变量分配任何值。

我建议传入一个模拟记录器,因为您正在进行单元测试并且可能不想测试记录器本身。所以使用FakeItEasy 或其他一些模拟库并在A.Fake&lt;ILogger&gt;() 上创建一个伪造的实例

【讨论】:

    【解决方案2】:

    您应该在此处遵循空对象模式。允许ILogger 参数为空,但如果参数为空,则默认字段为NullLogger.Instance。这意味着您可以在任何情况下安全地使用依赖项,但它不会强制任何人传入实例。阅读更多关于此here 的信息。

    【讨论】:

      猜你喜欢
      • 2019-11-01
      • 2018-03-13
      • 2020-04-21
      • 2021-07-09
      • 2020-09-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多