繁体   English   中英

如何模拟数据库的行为

[英]How to mock the behavior of a database

我正在尝试使用 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创建的,而是通过工厂对象创建的)。
  • 您阅读了 PowerMock,以及如何使用它来模拟对new调用。

我绝对建议您选择第一个选项:仅仅因为这会改进您的设计。 您看,为什么要将所有代码紧密耦合到弹性搜索? 但是假设这个实现已经是围绕弹性搜索的抽象层 - 那么你仍然应该使用依赖注入来获取你需要实际调用方法的ElasticSearch对象。 如上所述,使用工厂或真正的 DI 框架。 这将允许您使用“简单”的模拟框架,例如 Mockito 或 EasyMock。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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