【发布时间】:2019-11-08 02:05:30
【问题描述】:
我自己和我的大学已经构建了一个数据访问模块,它对 ElasticeSearch(6.2.0) NoSQL 数据库执行 CRUD 和搜索操作。我们正在使用 NEST(6.2.0),一个高级客户端映射到 Elasticsearch 查询 DSL。该模块已使用 C# 编码,位于目标框架 .NET Standard 2.0 的类库中。
在某些方法中,需要检索存储在 ElasticSearch 中的索引的索引映射,以便使用字段类型和文本属性等字段信息来构建对 Elasticsearch 数据库的搜索查询。我们可以通过使用 Nest 的 GetMapping 方法(返回 Nest.IGetMappingResponse)来做到这一点。
我们在执行代码时没有问题。一切正常。但是,当我们为使用 GetMapping 方法的方法构建单元测试时,我们无法模拟它返回的响应 (IGetMappingResponse)。我最初是用 FakeItEasy 来伪造的,然后在对象中插入了一些我需要的数据。但是,为了更好地解释我的问题,我创建了一个实现 IGetMappingResponse 的类来模拟我的响应。当我尝试为 IndexMapping 的 Mapping 属性创建一个 TypeMappings 的实例时,问题就来了(作为回报是模拟的属性索引)。我收到一条错误消息,提示 “'TypMappings' 不包含采用 0 个参数的构造函数。
public class MockedGetMappingResponse : IGetMappingResponse
{
public IReadOnlyDictionary<IndexName, IndexMappings> Indices
{
get
{
return new ReadOnlyDictionary<Nest.IndexName, Nest.IndexMappings>(new Dictionary<Nest.IndexName, Nest.IndexMappings>
{
["statuses"] = new IndexMappings
{
Mappings = new TypeMappings() //Error happens here!!
}
});
}
set { }
}
public IReadOnlyDictionary<IndexName, IndexMappings> Mappings
{
get { return null; }
set { }
}
public void Accept(IMappingVisitor visitor)
{
// Just a test
}
public bool IsValid
{
get { return true; }
}
public ServerError ServerError
{
get { return null; }
}
public Exception OriginalException
{
get { return null; }
}
public string DebugInformation
{
get { return ""; }
}
public IApiCallDetails ApiCall
{
get { return null; }
set { //do nothing }
}
public bool TryGetServerErrorReason(out string reason)
{
reason = "";
return false;
}
}
当我查看 Nest 类型 TypeMappings 的定义时,我没有看到构建的构造函数。因此,我假设它应该使用默认值,即没有参数的构造函数。但显然不是。我需要知道如何在 IGetMappingResponse 中模拟 TypeMappings。如果无法创建 TypeMappings 的实例,我需要知道如何为我的预期响应创建一个模拟的 IGetMappingResponse,以便我可以测试我的代码。
【问题讨论】:
-
查看
TypeMappings的定义以查看其构造函数。这应该为您提供所需的线索。 -
According to source code 它的构造函数是内部的。
-
另请注意
[Obsolete("Renamed to Indices, will be deleted from NEST 7.x")] IReadOnlyDictionary<IndexName, IndexMappings> Mappings { get; } -
您应该能够为您的模拟响应的
Indices属性模拟IReadOnlyDictionary<IndexName, IndexMappings> -
感谢 Nkosi,在您告诉我构造函数是内部的之后,我能够使用反射创建 TypeMappings 的实例。然后我可以模拟 IGetMappingResponse。完成后,我将稍后用代码回答这个问题。再次感谢! :)
标签: c# unit-testing elasticsearch nest