净核心 ILogger 值不能为空

Net Core ILogger Value cannot be null

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

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();

N单元测试:

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

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

我建议传入模拟记录器,因为您正在进行单元测试并且可能不想测试记录器本身。所以使用 FakeItEasy 或其他一些 Mocking-Libary 并在 A.Fake<ILogger>()

上创建一个伪造的实例

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