Reputation: 7376
I am trying to test the functionality of persisting the data into elasticsearch using JUnits. This is the first time I am using JUnits and this is my first test case.
I have an interface which is like the below
public interface ElasticSearchIndexer {
void writeTo(String inputJson) throws IOException;
}
The interface is implemented by multiple classes. The sample implementation looks like below
public class HardwareEOXIndexer implements ElasticSearchIndexer {
private static final Logger logger = LoggerFactory.getLogger(HardwareEOXIndexer.class);
private final String es_index = "/hardwareeox/inv/";
private String hostname;
public HardwareEOXIndexer(String hostname) {
this.hostname = hostname;
}
public void writeTo(String inputJson) throws IOException {
ReadContext ctx = JsonPath.parse(inputJson);
String hardwareEOXId = Integer.toString(ctx.read("$.EoXBulletin.items[0].hardwareEOXId"));
StringBuilder documentID = new StringBuilder().append(hardwareEOXId);
logger.info("Indexing the document with ID :: {} ", documentID.toString());
try {
new ElasticSearchContext().getContext(hostname, inputJson, es_index, documentID);
} catch (Exception e) {
e.printStackTrace();
logger.error("HardwareEOXIndexer : es_index: " + es_index + " ------> " + e.getMessage());
}
}
}
How do I mock the behavior of the elasticsearch and how to write unit tests.
Upvotes: 1
Views: 116
Reputation: 140613
The interface part is bogus within the question, the core point is:
How do I mock the behavior of the elasticsearch and how to write unit tests.
And there are basically two answers:
new
.I definitely suggest you to go for the first option: simply because that will improve your design. You see, why do you want to tightly couple all of your code to elastic search? But assuming that this implementation is already meant as abstraction layer around elastic search - then you should still use dependency injection to acquire that ElasticSearch
object you need to actually invoke methods on. As said, use a factory or a real DI framework. That will allow you to say with "simple" mocking frameworks such as Mockito or EasyMock.
Upvotes: 1