Java 如何模拟数据库的行为

Java 如何模拟数据库的行为,java,junit,Java,Junit,我正在尝试使用JUnits测试将数据持久化到elasticsearch中的功能。这是我第一次使用JUnits,这是我的第一个测试用例 我有一个界面,如下所示 public interface ElasticSearchIndexer { void writeTo(String inputJson) throws IOException; } 该接口由多个类实现。示例实现如下所示 public class HardwareEOXIndexer implements ElasticSea

我正在尝试使用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

接口的单元测试(没有默认方法)没有意义。您只能测试它的一个实现。我感谢您的快速接受!还有第三个选项(我经常使用):在一个方法后面插入一个工厂,隐藏
新的ElasticSearchContext()
,然后可以对该方法进行模拟,以返回
ElasticSearchContext
模拟。@Mick助记符您分别是对的:我在写答案时没有完全精确。我也想到了这个解决方案。我编辑了我的问题。我一开始的目的是理解接口的单元测试用例,但与数据库层不同。谢谢你的指点。