I have a little trouble understanding java streams. I created a JUnit test that basically stores an element in a database, retrieves it (results are returned in a stream), and then compares both elements. The test failed, so I started to debug. Suddenly the test passed. Turns out my breakpoint gave the stream the time it needed to build?!
@Test
public void matchAllTest() {
client.insert(object); //database schema is empty
Stream<Object> stream = client.query("{ query matching all objects }");
Object firstResult = stream.findFirst().get();
assertObjectEquals(object, firstResult);
}
query
works with Elasticsearch as a database and looks like this:
public Stream<Object> query(String query) {
SearchRequestBuilder request = client.prepareSearch("index");
request.setQuery(query);
Stream.Builder<Object> stream = Stream.builder();
SearchResponse response = request.get();
SearchHits hits = response.getHits();
hits.forEach(object -> stream.accept(object);
return stream.build();
}
client
in the test refers to a class with the query
method. client
in the second code snippet refers to an Elasticsearch node client, see ES Java docs.
The test fails with a NoSuchElementException ("No value present")—unless I give it time.
What exactly is happening here and how can I avoid an exception?