I have Micronaut
application connecting to elasticsearch using java-client API, we are using ElasticsearchClient to stores and retrieve the data into elastic search.
I'm writing integration test cases using @MicronautTest
annotation by spinning up docker using docker-compose.yml
version: "3.0"
services:
elasticsearch:
container_name: es-container
image: docker.elastic.co/elasticsearch/elasticsearch:7.16.0
environment:
- "ES_JAVA_OPTS=-Xms512m -Xmx512m"
- discovery.type=single-node
- node.store.allow_mmap=false
- xpack.security.enabled=false
ports:
- "9200:9200"
The problem in below test class is, for every test cases we are inserting data and since previous test data is not cleaning up, some of the test cases are failing with in correct results. My question to delete before every test case execution ?
ElasticSearchTest
@MicronautTest
public class ElasticSearchTest {
@Autowired
private MockMvc mockMvc;
@Test
public void test1() {
// inserting some test data into ElasticSearch
//mockmvc API call and asserting response
}
@Test
public void test2() {
// inserting some test data into ElasticSearch
//mockmvc API call and asserting response
}
}
For in this use case you can use @Before
in junit-4 and @BeforeEach
in junit-5 to clean up the data before any test case execution (baeldung artical).
As first step, you can inject ElasticsearchClient
and create Query with MatchAllQuery
@Inject
ElasticsearchClient elasticsearchClient
@BeforeEach
public void setUp() {
Query matchAll = new Query.Builder()
.matchAll(new MatchAllQuery.Builder().build())
.build()
DeleteByQueryRequest deleteRequest = new DeleteByQueryRequest.Builder()
.index("_all")
.query(matchAll)
.build()
elasticsearchClient.deleteByQuery(deleteRequest).deleted()
}