【问题标题】:How to Mock Elasticsearch NEST's IGetMappingResponse for Unit Testing如何模拟 Elasticsearch NEST GetMapping 响应以进行单元测试
【发布时间】: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&lt;IndexName, IndexMappings&gt; Mappings { get; }
  • 您应该能够为您的模拟响应的Indices 属性模拟IReadOnlyDictionary&lt;IndexName, IndexMappings&gt;
  • 感谢 Nkosi,在您告诉我构造函数是内部的之后,我能够使用反射创建 TypeMappings 的实例。然后我可以模拟 IGetMappingResponse。完成后,我将稍后用代码回答这个问题。再次感谢! :)

标签: c# unit-testing elasticsearch nest


【解决方案1】:

在 Nkosi 的帮助下,我发现 TypeMappings 有一个内部构造函数。知道这一点后,我使用反射创建了一个 TypeMappings 实例。这是我用来创建对象的代码。

IReadOnlyDictionary<TypeName, TypeMapping> backingDictionary = new ReadOnlyDictionary<TypeName, TypeMapping>(new Dictionary<TypeName, TypeMapping>
        {
            [typeName.Name] = typeMapping

        });           

        Type[] typeMappingsArgs = new Type[] { typeof(IConnectionConfigurationValues), typeof(IReadOnlyDictionary<TypeName, TypeMapping>) };
        object[] typeMappingsInputParams = new object[] { elasticClient.ConnectionSettings, backingDictionary };
        TypeMappings typeMappings = (TypeMappings)typeof(TypeMappings).GetConstructor(
              BindingFlags.NonPublic | BindingFlags.Instance,
              null, typeMappingsArgs, null).Invoke(typeMappingsInputParams);

这是用于创建我的模拟 IGetMappingResponse 的代码。我使用 FakeItEasy 插入一些信息。

private Nest.IGetMappingResponse GetFakeMappingResponse(Nest.IElasticClient elasticClient)
    {
        var fieldName = "fieldName";
        var indexName = "indexName";
        var documentTypeName = "documentTypeName";

        var typeMapping = new TypeMapping();
        var properties = new Properties();
        typeMapping.Properties = properties;

        var property = new TextProperty();
        property.Name = fieldName;            

        PropertyName propertyName = new PropertyName(fieldName);

        typeMapping.Properties.Add(propertyName, property);

        Type[] typeNameArgs = new Type[] { typeof(string) };
        object[] typeNameInputParams = new object[] { documentTypeName };
        TypeName typeName = (TypeName)typeof(TypeName).GetConstructor(
              BindingFlags.NonPublic | BindingFlags.Instance,
              null, typeNameArgs, null).Invoke(typeNameInputParams);


        IReadOnlyDictionary<TypeName, TypeMapping> backingDictionary = new ReadOnlyDictionary<TypeName, TypeMapping>(new Dictionary<TypeName, TypeMapping>
        {
            [typeName.Name] = typeMapping

        });           

        Type[] typeMappingsArgs = new Type[] { typeof(IConnectionConfigurationValues), typeof(IReadOnlyDictionary<TypeName, TypeMapping>) };
        object[] typeMappingsInputParams = new object[] { elasticClient.ConnectionSettings, backingDictionary };
        TypeMappings typeMappings = (TypeMappings)typeof(TypeMappings).GetConstructor(
              BindingFlags.NonPublic | BindingFlags.Instance,
              null, typeMappingsArgs, null).Invoke(typeMappingsInputParams);

        IndexMappings indexMappings = new IndexMappings();
        typeof(IndexMappings).GetProperty("Mappings", BindingFlags.Public | BindingFlags.Instance).SetValue(indexMappings, typeMappings);

        ReadOnlyDictionary<Nest.IndexName, Nest.IndexMappings> indices = new ReadOnlyDictionary<Nest.IndexName, Nest.IndexMappings>(new Dictionary<Nest.IndexName, Nest.IndexMappings>
        {
            [indexName] = indexMappings

        });

        var fakeMappingResponse = A.Fake<IGetMappingResponse>();
        A.CallTo(() => fakeMappingResponse.ServerError).Returns(null);
        A.CallTo(() => fakeMappingResponse.IsValid).Returns(true);
        A.CallTo(() => fakeMappingResponse.Indices).Returns(indices);

        return fakeMappingResponse;
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-06-29
    • 2013-11-18
    • 2018-04-04
    • 2021-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多