I'm testing my class ElasticUtility which requires an instance of the ElasticClient in order to work properly so I mocked such class and injected it into the ElasticUtility instance (utility)
private ElasticUtility utility;
private Mock<IElasticClient> elasticClientMock;
private string elasticSearchIndexName;
elasticClientMock = new Mock<IElasticClient>();
utility = new UhhElasticUtility(elasticClientMock.Object);
This is the actual test code:
[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());
}
I get a Null reference exception when the Moq library calls the .Search() method inside the mocked ElastiClient.
EDIT:
the constructor of ElasticUtility:
protected ElasticUtility(IElasticClient elasticClient, string elasticIndexName)
{
this.ElasticClient = elasticClient;
this.ElasticIndexName = elasticIndexName;
}
EDIT: GetPvData() method:
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();
}
UhhElasticUtilityand the implementation ofGetPvDataUhhElasticUtilityC'tor andGetPvData....Documentsyou didn't set an expectation, then search returnnull...