使用C#Moq模拟ElasticSearch客户端
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了使用C#Moq模拟ElasticSearch客户端,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1895字,纯文字阅读大概需要3分钟。
内容图文
![使用C#Moq模拟ElasticSearch客户端](/upload/InfoBanner/zyjiaocheng/824/cf7da20c19114dda84e9ef081f994e82.jpg)
我正在测试我的类ElasticUtility,它需要一个ElasticClient实例才能正常工作,所以我嘲笑这个类并将它注入ElasticUtility实例(实用程序)
private ElasticUtility utility;
private Mock<IElasticClient> elasticClientMock;
private string elasticSearchIndexName;
elasticClientMock = new Mock<IElasticClient>();
utility = new UhhElasticUtility(elasticClientMock.Object);
这是实际的测试代码:
[Test]
public void GetGetPvDataClientReturnNull()
{
// arrange
var groupId = "groupid";
var startTime = new DateTime(2015, 08, 17, 13, 30, 00);
var endTime = new DateTime(2015, 08, 17, 13, 40, 00);
// act
utility.GetPvData(groupId, startTime, endTime);
// assert
elasticClientMock.Verify(ec => ec.Search<SegmentRecord>(It.IsAny<Nest.ISearchRequest>()), Times.Once());
}
当Moq库在模拟的ElastiClient中调用.Search()方法时,我得到一个Null引用异常.
编辑:
ElasticUtility的构造函数:
protected ElasticUtility(IElasticClient elasticClient, string elasticIndexName)
{
this.ElasticClient = elasticClient;
this.ElasticIndexName = elasticIndexName;
}
编辑:GetPvData()方法:
public IEnumerable<dynamic> GetPvData(string groupId, DateTime startTime, DateTime endTime)
{
var res = ElasticClient.Search<SegmentRecord>(s => s
.Index(ElasticIndexName)
.Filter(f =>
f.Term(t => t.HistoryId, groupId) &&
f.Range(i =>
i.OnField(a => a.DateTime).LowerOrEquals(startTime))).SortAscending(p => p.DateTime).Size(1)).Documents.ToList();
return res.ToArray();
}
解决了:
var segResp = new SearchResponse<SegmentRecord>();
elasticClientMock.Setup(ec => ec.Search(
It.IsAny<Func<SearchDescriptor<SegmentRecord>,
SearchDescriptor<SegmentRecord>>>()))
.Returns(segResp);
解决方法:
由于您未在搜索方法上指定行为,因此发生NullReferenceException.您的搜索方法返回null,然后在null上调用.Document.
指定行为的方式如下:
elasticClientMock.Setup(x => x.Search<SegmentRecord>(
It.IsAny</* put here the right Func */>))
.Returns( /* put here the instance you want to return */);
你必须用正确的类型替换我的评论.
内容总结
以上是互联网集市为您收集整理的使用C#Moq模拟ElasticSearch客户端全部内容,希望文章能够帮你解决使用C#Moq模拟ElasticSearch客户端所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。