Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elasticsearch unit testing

With the latest elasticsearch 6.4.1 I would like to implement unit testing. Currently implemented unit testing as integration testing as RestHighLevelClient is not mockable.I see that RestClient though mockable cannot be set to the restHighLevelClient. I want to mock elasticsearch so that i can run tests anywhere. Any possible way using the Node and Settings i don't want a full blown cluster.

like image 576
Raghuveer Avatar asked Jun 16 '26 01:06

Raghuveer


1 Answers

The real question is what exactly is the purpose of such a test

There are two possible options:

  • The test that tests business logic and assumes the "Data Access Layer" (with elasticseach as a persistency engine) works as expected

  • The test should test the code that talks with ES (check that the requests are supplied with correct parameters, correctly created and executed)

So, if the test falls into the first category, then you don't need an elasticsearch at all, just mock out the DAL layer with mockito or something, and you're done. Of course for this thing to work best, you should have a well-defined Data Access Layer

Most of the code can be checked like this and this is a proper unit test.

For checking the DAL layer itself, however, this is not enough. You'll have to work against a real elasticsearch engine.

I can recommend an approach of starting the Elasticsearch in Docker (see project testcontainers before test case and stop it afterward (you can even cache it between the test cases to start it only once).

You'll get a randomly generated ports that will map to 9200/9300 of Docker container so that running many tests simultaneously on the same machine (like CI or something) won't interfere.

Another approach is using the Allegro library. It allows creating embedded elasticsearch configurations as a part of your tests and used primarily for integration testing.

I haven't tested it by myself though

like image 160
Mark Bramnik Avatar answered Jun 18 '26 00:06

Mark Bramnik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!