当我尝试将db调用单元测试到使用ProjectionDefinition的mongo数据库时,我得到以下异常:“Value不能为null。\ r \ nParameter name:projection”。这是因为在为MongoDb C#驱动程序ProjectionDefinition类分配期间,存在一个抛出此异常的空检查。以下是异常的调用堆栈:
{System.ArgumentNullException: Value cannot be null.
Parameter name: projection
at MongoDB.Driver.Core.Misc.Ensure.IsNotNull[T](T value, String paramName)
at MongoDB.Driver.KnownResultTypeProjectionDefinitionAdapter`2..ctor(ProjectionDefinition`1 projection, IBsonSerializer`1 projectionSerializer)
at MongoDB.Driver.ProjectionDefinition`2.op_Implicit(ProjectionDefinition`1 projection)
at DataCollection.Data.Mongo.Test.Collection.ComponentRecordCollectionTest.LogsExceptionWhenOnGetRecordUserViews() in C:\Repositories\Folio\folio-data-collection-api\src\DataCollection.Data.Mongo.Test\Collection\ComponentRecordCollectionTest.cs:line 447}
我正在使用NSubstitute Arg.Is测试我的函数中的投影值。
var expectedProjection = Arg.Is<ProjectionDefinition<ComponentRecordDataModel>>(
x => x.ToJson().Equals(projection.ToJson()));
我注意到这会导致expectedProjection为null,从而触发异常。我不确定这是如何工作的,但我在测试FilterDefinition时做的完全相同,它没有任何问题。我甚至使用NSubstitue文档中的示例进行了测试,即使Arg.Is返回null,参数匹配工作也是如此。
以下是我要测试的功能:
public ComponentRecordDataModel GetRecordUserViews(string id)
{
var filter = Builders<ComponentRecordDataModel>.Filter.Eq(x => x.Id, id);
var projection = Builders<ComponentRecordDataModel>.Projection.Include(x => x.UserViews);
var result = MongoContext.Find(filter, projection).FirstOrDefault();
return result;
}
这是测试:
[Fact]
public void LogsExceptionWhenOnGetRecordUserViews()
{
var filter = Builders<ComponentRecordDataModel>.Filter.Eq(x => x.Id, _recordModel.Id);
var projection = Builders<ComponentRecordDataModel>.Projection.Include(x => x.UserViews);
var expectedFilter = Arg.Is<FilterDefinition<ComponentRecordDataModel>>(
x => x.ToJson().Equals(filter.ToJson()));
var expectedProjection = Arg.Is<ProjectionDefinition<ComponentRecordDataModel>>(
x => x.ToJson().Equals(projection.ToJson()));
_mongoContext.Find(expectedFilter, expectedProjection).Throws(_exception);
Assert.Throws(typeof(DataAccessException), () => _collection.GetRecordUserViews(_recordModel.Id));
_logger.CheckReceivedLog(LogLevel.Error, LoggingEvents.GeneralException, _exception.Message);
}
我想知道我在这里做错了什么,或者有人有另外一种方法来测试这段代码。提前致谢!