[英]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 的行为以及如何编写单元测试。
基本上有两个答案:
new
调用。 我绝对建议您选择第一个选项:仅仅因为这会改进您的设计。 您看,为什么要将所有代码紧密耦合到弹性搜索? 但是假设这个实现已经是围绕弹性搜索的抽象层 - 那么你仍然应该使用依赖注入来获取你需要实际调用方法的ElasticSearch
对象。 如上所述,使用工厂或真正的 DI 框架。 这将允许您使用“简单”的模拟框架,例如 Mockito 或 EasyMock。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.