我正试图对我的处理程序数据库进行单元测试,但当我调用我的方法时,我得到了一个nullReferenceException。
这是我的处理器构造函数
public SignalsHandler(IConfiguration configuration, IDbConnection connection)
{
_dbConnection = connection;
_settings = configuration.GetSection("SigSettings").Get<SigSettings>();
if (_settings == null)
_settings = new SigSettings();
}
我要做的是在我的测试类中用这个来模拟它:
private Mock<IConfigurationSection> _configSectionMock = new Mock<IConfigurationSection>();
private Mock<IConfiguration> _configMock = new Mock<IConfiguration>();
private Mock<IDbConnection> _connection = new Mock<IDbConnection>();
private readonly SignalsHandler _handler;
public SignalsTest()
{
_configMock.Setup(x => x.GetSection(It.IsAny<string>())).Returns(_configSectionMock.Object);
_handler = new SignalsHandler(_configMock.Object, _connection.Object);
}
到目前为止还好,但当我试图实现一些测试它不工作。例如,一个简单的测试:
public void CanGetAllSignals()
{
var result = _handler.GetSignals();
Assert.IsNotNull(result);
}
我用Mock处理程序调用我的.GetSignals()
方法。这是代码:
public async Task<List<SignalsDTO>> GetSignals()
{
var res = new List<SignalsDTO>();
var sigList = await _dbConnection.QueryAsync<SigSignal>(_settings.Signals);
foreach (var s in sigList)
res.Add(new SignalsDTO()
{
IDTag = s.IDTag,
Name = s.Name
});
return res;
}
但是当我调试我的测试方法时,我得到:NullReferenceException:'Object reference not set to an instance of an object.'
在这行:
var sigList = await _dbConnection.QueryAsync<SigSignal>(_settings.Signals);
我想这是一个错误与我的模拟配置在我的测试构造函数,但我不确定我怎么能解决这个问题。
您忘记设置模拟的返回对象了。您应该这样定义它:
var connectionMock = new Mock<IDbConnection>();
conectionMock
.Setup(x => x.QueryAsync<It.IsAnyType>(
It.IsAny<string>(),
It.IsAny<object>(),
It.IsAny<IDbTransaction>(),
It.IsAny<int?>(),
It.IsAny<CommandType?>()
))
.ReturnsAsync(new List<SignalsDTO>());
注意:你使用的类型和位置并不清楚,所以请调整,但思想是在这里。