ElasticSearch NEST 5.6.1查询单元测试 [英] ElasticSearch NEST 5.6.1 Query for unit test

查看:119
本文介绍了ElasticSearch NEST 5.6.1查询单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一堆查询来进行弹性搜索,我想为它们编写一个单元测试.使用这篇文章通过弹性连接我能够进行预成型一般的嘲笑.但是,当我尝试查看由查询生成的Json时,我没有设法以任何方式获取它. 我试图按照这篇文章 elsatic query moq 进行操作,但这仅与Nest的旧版本有关,因为方法ConnectionStatusRequestInformation不再可用于ISearchResponse对象.

I wrote a bunch of queries to elastic search and I wanted to write a unit test for them. using this post moq an elastic connection I was able to preform a general mocking. But When I tried to view the Json which is being generated from my query I didn't manage to get it in any way. I tried to follow this post elsatic query moq, but it is relevant only to older versions of Nest because the method ConnectionStatus and RequestInformation is no longer available for an ISearchResponse object.

我的测试如下:

[TestMethod]
 public void VerifyElasticFuncJson()
{
//Arrange
var elasticService = new Mock<IElasticService>();
var elasticClient = new Mock<IElasticClient>();
var clinet = new ElasticClient();
var searchResponse = new Mock<ISearchResponse<ElasticLog>>();
elasticService.Setup(es => es.GetConnection())
    .Returns(elasticClient.Object);

elasticClient.Setup(ec => ec.Search(It.IsAny<Func<SearchDescriptor<ElasticLog>, 
                          ISearchRequest>>())).
                          Returns(searchResponse.Object);

//Act
var service = new ElasticCusipInfoQuery(elasticService.Object);
var FindFunc = service.MatchCusip("CusipA", HostName.GSMSIMPAPPR01, 
                                        LogType.Serilog);
var con = GetConnection();
var search =  con.Search<ElasticLog>(sd => sd
             .Type(LogType.Serilog)
             .Index("logstash-*")
             .Query(q => q
             .Bool(b => b
                    .Must(FindFunc)
                    )
               )     
             );
 **HERE I want to get the JSON** and assert it look as expected**
}

还有其他方法可以实现我的要求吗?

Is there any other way to achieve what I ask?

推荐答案

执行此操作的最佳方法是使用InMemoryConnection捕获请求字节并将其与期望的JSON比较.这就是单元测试NEST要做的.像

The best way to do this would be to use the InMemoryConnection to capture the request bytes and compare this to the expected JSON. This is what the unit tests for NEST do. Something like

private static void Main()
{
    var pool = new SingleNodeConnectionPool(new Uri("http://localhost:9200"));
    var connectionSettings = new ConnectionSettings(pool, new InMemoryConnection())
        .DefaultIndex("default")
        .DisableDirectStreaming();

    var client = new ElasticClient(connectionSettings);

    // Act
    var searchResponse = client.Search<Question>(s => s
       .Query(q => (q
         .Match(m => m
               .Field(f => f.Title)
               .Query("Kibana")
         ) || q
         .Match(m => m
               .Field(f => f.Title)
               .Query("Elasticsearch")
               .Boost(2)
         )) && +q
         .Range(t => t
               .Field(f => f.Score)
               .GreaterThan(0)
         )
       )
    );

    var actual = searchResponse.RequestJson();

    var expected = new 
    {
        query = new {
            @bool = new {
                must = new object[] {
                    new {
                        @bool = new {
                            should = new object[] {
                                new {
                                    match = new {
                                        title = new {
                                            query = "Kibana"
                                        }
                                    }
                                },
                                new {
                                    match = new {
                                        title = new {
                                            query = "Elasticsearch",
                                            boost = 2d
                                        }
                                    }
                                }
                            },
                        }
                    },
                    new {
                        @bool = new {
                            filter = new [] {
                                new {
                                    range = new {
                                        score = new {
                                            gt = 0d
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    };

    // Assert
    Console.WriteLine(JObject.DeepEquals(JToken.FromObject(expected), JToken.Parse(actual)));
}

public static class Extensions
{
    public static string RequestJson(this IResponse response) =>
        Encoding.UTF8.GetString(response.ApiCall.RequestBodyInBytes);
}

我为预期的JSON使用了匿名类型,因为它比转义的JSON字符串更易于使用.

I've used an anonymous type for the expected JSON as it's easier to work with than an escaped JSON string.

要注意的一件事是,即使JSON对象中存在重复的对象键(只要最后一个键/值匹配),Json.NET的JObject.DeepEquals(...)都将返回true.如果仅序列化NEST搜索,您不太可能遇到这种情况,但是需要注意.

One thing to note is that Json.NET's JObject.DeepEquals(...) will return true even when there are repeated object keys in a JSON object (so long as the last key/value matches). It's not likely something you'll encounter if you're only serializing NEST searches though, but something to be aware of.

如果您要进行很多测试来检查序列化,则需要创建一个ConnectionSettings实例并与所有人共享,以便您可以利用其中的内部缓存来运行测试比在每个测试中实例化一个新实例要快.

If you're going to have many tests checking serialization, you'll want to create a single instance of ConnectionSettings and share with all, so that you can take advantage of the internal caches within it and your tests will run quicker than instantiating a new instance in each test.

这篇关于ElasticSearch NEST 5.6.1查询单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆