我有一个非常简单的类,它使用Elasticsearch.net通过简单查询访问端点。类和方法工作正常,我得到了预期的结果。但我在UnitTesting这门课上没有成功。 这是我尝试使用UnitTest的课程:
namespace X
{
public class YLookup : IYLookup
{
private readonly IElasticLowLevelClient _lowLevelClient;
public YLookup()
{
}
public YLookup(IElasticLowLevelClient lowLevelClient)
{
_lowLevelClient = lowLevelClient;
}
public string Lookup(string Z)
{
if (string.IsNullOrEmpty(Z))
{
return string.Empty;
}
var searchResponse = _lowLevelClient.Search<StringResponse>(
"person",
"company",
"My elastic search query");
if (searchResponse.Success)
{
// success! Parse searchResponse.Body;
}
else
{
// Failure :(
}
}
}
}
界面:
namespace X
{
internal interface IYLookup
{
string Lookup(string Z);
}
}
我用来尝试UnitTest的代码:
[TestMethod]
public void Test1()
{
string h = "{\r\n\t\"took\": 2,\r\n\t\"timed_out\": false,\r\n\t\"_shards\": {\r\n\t\t\"total\": 6,\r\n\t\t\"successful\": 6,\r\n\t\t\"failed\": 0\r\n\t},\r\n\t\"hits\": {\r\n\t\t\"total\": 0,\r\n\t\t\"max_score\": null,\r\n\t\t\"hits\": []\r\n\t}\r\n}";
Mock<IApiCallDetails> apiCallDetails = new Mock<IApiCallDetails>(MockBehavior.Strict);
apiCallDetails.Setup(x => x.Success).Returns(true);
Mock<ElasticsearchResponse<string>> elasticsearchResponse = new Mock<ElasticsearchResponse<string>>();
elasticsearchResponse.Setup(x => x.Body).Returns(h);
Mock<StringResponse> s = new Mock<StringResponse>();
s.Setup(x => x.ApiCall).Returns(apiCallDetails.Object);
Mock<IElasticLowLevelClient> elasticLowLevelClient = new Mock<IElasticLowLevelClient>(MockBehavior.Strict);
elasticLowLevelClient.Setup(x => x.Search<StringResponse>(It.IsAny<string>(), It.IsAny<string>(),, It.IsAny<PostData>(), It.IsAny<SearchRequestParameters>())).Returns(s.Object);
}
我遇到的错误是:
invalid setup on a non-virtual (overridable in vb) member
我需要设置成功属性和body属性,我没有看到如何使用所涉及对象的复杂结构来设置主体。
有人有解决方案或者能看出我做错了什么吗? 感谢。
P.S。请忽略命名。我故意将它们改为无意义的名字。
答案 0 :(得分:2)
通过查看来源(Elasticsearch-net on GitHub),您应该能够直接创建StringResponse
的实例,并传入ctor中的Body
。 ApiCall
上的ElasticsearchResponseBase
属性具有公共获取/设置对,因此您应该能够按照
[TestMethod]
public void Test1()
{
string h = "{\r\n\t\"took\": 2,\r\n\t\"timed_out\": false,\r\n\t\"_shards\": {\r\n\t\t\"total\": 6,\r\n\t\t\"successful\": 6,\r\n\t\t\"failed\": 0\r\n\t},\r\n\t\"hits\": {\r\n\t\t\"total\": 0,\r\n\t\t\"max_score\": null,\r\n\t\t\"hits\": []\r\n\t}\r\n}";
Mock<IApiCallDetails> apiCallDetails = new Mock<IApiCallDetails>(MockBehavior.Strict);
apiCallDetails.Setup(x => x.Success).Returns(true);
var resp = new StringResponse(h);
resp.ApiCall = apiCallDetails.Object;
Mock<IElasticLowLevelClient> elasticLowLevelClient = new Mock<IElasticLowLevelClient>(MockBehavior.Strict);
elasticLowLevelClient.Setup(x => x.Search<StringResponse>(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<PostData>(), It.IsAny<SearchRequestParameters>())).Returns(resp);
}
我已经从上面复制了lowLevelClient设置的代码(删除了额外的逗号)但是如果我们要检查是否正确调用了搜索,我们应该将它们与实际参数匹配,而不是使用()。