Skip to content

Instantly share code, notes, and snippets.

@netoisc
Created June 26, 2017 16:10
Show Gist options
  • Select an option

  • Save netoisc/5d456850d79f246685fee23be2469155 to your computer and use it in GitHub Desktop.

Select an option

Save netoisc/5d456850d79f246685fee23be2469155 to your computer and use it in GitHub Desktop.
How to test ElasticClient with Moq and .net
[Test]
public async Task ElasticClient_Test()
{
var people = new List<Person>
{
new Person { Id = 1 },
new Person { Id = 2 },
};
var hits = new List<IHit<Person>>
{
new Mock<IHit<Person>>().Object
};
var mockSearchResponse = new Mock<ISearchResponse<Person>>();
mockSearchResponse.Setup(x => x.Documents).Returns(people);
mockSearchResponse.Setup(x => x.Hits).Returns(hits);
var mockElasticClient = new Mock<IElasticClient>();
mockElasticClient.Setup(x => x
.Search(It.IsAny<Func<SearchDescriptor<Person>, ISearchRequest>>()))
.Returns(mockSearchResponse.Object);
var mockResponse = new Mock<IIndexResponse>();
mockResponse.Setup(r => r.Id).Returns("AResponse");
mockElasticClient.Setup(y => y.Index<Person>(It.IsAny<Person>(), It.IsAny<Func<IndexDescriptor<Person>, IndexRequest<Person>>>()))
.Returns(mockResponse.Object);
var typeConfig = new TypeName();
typeConfig.Name = "config";
var rq = new IndexRequest<Person>("archiving", typeConfig);
//rq.Document = new Person();
var r2 = mockElasticClient.Object.Index(new Person(), null);
var result = mockElasticClient.Object.Search<Person>(s => s);
Assert.AreEqual(2, result.Documents.Count());
Assert.AreEqual(1, result.Hits.Count());
}
public class Person
{
public int Id { get; set; } = 10;
}
@deanmalone

Copy link
Copy Markdown

👍 Thank you!

@prabhdeep-kaur

Copy link
Copy Markdown

I need example of setting mockSearchResponse.Setup(x => x.Fields).Returns(fields);
How to set fields data?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment