【发布时间】: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