Issue
I create an integration test for retrieving data from elasticsearch.
I am using default values for the testContainer so my RestHighLevelClient should have access to the test container but all the time I am getting the same exception (java.net.ConnecteException: Connection refused
) when I am trying to index data, but when I run my locally the docker image by command
docker run -d --rm -p 9200:9200 -p 9300:9300 -e "discovery.type=single-node" -e "transport.host=127.0.0.1" --name elastic docker.elastic.co/elasticsearch/elasticsearch:6.5.4
my test works correctly.
Where is the problem, because the port mapping is the same? What is the reason of this exception?
My test:
@ExtendWith(SpringExtension.class)
@Testcontainers
@WebMvcTest
class FlowerResourceTest {
@Container
private ElasticsearchContainer esContainer = new ElasticsearchContainer("docker.elastic.co/elasticsearch/elasticsearch:6.5.4");
@Autowired
private ElasticsearchConfiguration esConfig;
@Autowired
private FlowerService flowerService;
private RestHighLevelClient client;
@Test
void test() throws IOException, InterruptedException {
client = esConfig.client();
var jsonFlower = "{\n" +
" \"name\": \"XXX\",\n" +
" \"color\" : \"red\"\n" +
"}";
IndexRequest indexRequest = new IndexRequest("flowers", "doc", "1")
.source(jsonFlower, XContentType.JSON);
assertTrue(esContainer.isRunning());
client.index(indexRequest, RequestOptions.DEFAULT);
var flowers = flowerService.findAll();
assertTrue(flowers.size() > 0);
DeleteRequest deleteRequest = new DeleteRequest("flowers", "doc", "1");
client.delete(deleteRequest, RequestOptions.DEFAULT);
}
}
Solution
If I remember well, you can ask for the exposed port using the following command:
esContainer.getMappedPort(ELASTICSEARCH_PORT);
The Docker container exposes a random available port, so check the port as with the mentioned command. Use that port for the client. A colleague of mine wrote a blog post about this with some sample code if you are interested: https://www.luminis.eu/blog/search-en/elasticsearch-instances-for-integration-testing/
Answered By - Jettro Coenradie
Answer Checked By - Timothy Miller (JavaFixing Admin)