我有一个非常简单的类,它使用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我需要设置success属性和body属性,但是我不知道如何使用复杂的对象结构来设置body。
有没有人有解决方案,或者能看到我做错了什么?谢谢。
附注:请忽略命名。我故意把它们改成了这些无意义的名字。
发布于 2018-02-15 20:54:11
通过查看源代码(Elasticsearch-net on GitHub),您应该能够直接创建StringResponse的实例,在ctor中传入Body。ElasticsearchResponseBase上的ApiCall属性有一个公共的get/set对,因此您应该能够执行类似以下内容的操作
[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设置复制了上面的代码(删除多余的逗号),但是如果我们想要检查是否正确地调用了搜索,我们应该将它们与实际的参数进行匹配,而不是使用()。
https://stackoverflow.com/questions/48802102
复制相似问题