如何模拟数据库的行为

流浪的和尚

我正在尝试测试使用JUnits将数据持久化到Elasticsearch中的功能。这是我第一次使用JUnits,这是我的第一个测试用例。

我有一个类似于下面的界面

public interface ElasticSearchIndexer {

    void writeTo(String inputJson) throws IOException;
}

该接口由多个类实现。示例实现如下所示

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());
        }
    }

}

我如何模拟Elasticsearch的行为以及如何编写单元测试。

幽灵猫

接口部分为问题中伪造,其核心观点是:

我如何模拟Elasticsearch的行为以及如何编写单元测试。

基本上有两个答案:

  • 您将创建一个抽象层来隐藏ElasticSearch的详细信息。含义:您无需创建新的ElasticSearch对象,而是创建您自己的类的对象(例如,您不是通过new创建的,而是通过factory对象创建的)。
  • 您了解了PowerMock,以及如何使用它模拟对的调用new

我绝对建议您选择第一个选择:仅因为这将改善您的设计。您知道,为什么要将所有代码紧密地耦合到弹性搜索?但是,假设此实现已被用作弹性搜索周围的抽象层-那么您仍应使用依赖注入来获取ElasticSearch实际调用方法所需要的对象。如前所述,使用工厂或真实的DI框架。这样一来,您就可以使用“简单的”模拟框架(例如Mockito或EasyMock)来说。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章