简体   繁体   中英

How to mock the behavior of a database

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.

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:

  • you create an abstraction layer that hides the details of ElasticSearch. Meaning: instead of creating a new ElasticSearch object, you create an object of your own class (which you don't create via new , but via a factory object for example).
  • you read about PowerMock, and how to use that to mock calls to 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM