gpt4 book ai didi

java - 模拟 InfluxDB 客户端来测试 MetricCollector 类

转载 作者:行者123 更新时间:2023-11-30 06:31:33 25 4
gpt4 key购买 nike

我有一个在 InfluxDB 上存储数据的指标收集器,我想测试存储该指标的方法。我正在尝试,但无法模拟 InfluxDB 客户端。我不想指出测试环境中真实的 InfluxDB

到目前为止我所取得的一切都是一些“空指针异常”和连接被拒绝。

这是我的测试(使用 TestNG)。我究竟做错了什么?

    @Test
public void validateMetrics() {
String influxHost = "http://localhost";
String credentials = "admin:admin";
String influxDatabaseName = "testDataBase";
influxDB = InfluxDBFactory.connect(influxHost, credentials.split(":")[0], credentials.split(":")[1]);

MetricsCollector metricsCollector = null;

try {
String hostName = "test-server-01";
int statusValue = 1;
metricsCollector = new MetricsCollector(influxDB);


BatchPoints metrics = metricsCollector.initBatchPoint(influxDatabaseName);
Point point = metricsCollector.setMetric(hostName, "status", statusValue);
metrics = metricsCollector.addToMetrics(metrics, point);

Assert.assertTrue(metrics.getPoints().get(0).lineProtocol().contains(hostName));
Assert.assertTrue(metrics.getPoints().get(0).lineProtocol().contains("status=" + statusValue));
} finally {
if (metricsCollector != null) {
metricsCollector.closeConnection();
}
}
}

最佳答案

我怀疑您无法模拟 InfluxDB 客户端的原因是它是由静态方法创建的:InfluxDBFactory.connect()。要模拟这个,你需要 PowerMock .

类似这样的事情:

@PrepareForTest({InfluxDBFactory.class})
public class ATestClass {

@Test
public void validateMetrics() {
// this allows you to mock static methods on InfluxDBFactory
PowerMockito.mockStatic(InfluxDBFactory.class);

String influxHost = "http://localhost";
String credentials = "admin:admin";
String influxDatabaseName = "testDataBase";

InfluxDB influxDB = Mockito.mock(InfluxDB.class);

// when the connect() method is invoked in your test run it will return a mocked InfluxDB rather than a _real_ InfluxDB
PowerMockito.when(InfluxDBFactory.connect(influxHost, credentials.split(":")[0], credentials.split(":")[1])).thenReturn(influxDB);

// you won't do this in your test, I've only included it here to show you that InfluxDBFactory.connect() returns the mocked instance of InfluxDB
InfluxDB actual = InfluxDBFactory.connect(influxHost, credentials.split(":")[0], credentials.split(":")[1]);
Assert.assertSame(influxDB, actual);

// the rest of your test
// ...
}
}

注意:TestNG、Mockito 和 PowerMock 有特定的兼容性要求 herehere .

关于java - 模拟 InfluxDB 客户端来测试 MetricCollector 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45998514/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com