作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个在 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
// ...
}
}
关于java - 模拟 InfluxDB 客户端来测试 MetricCollector 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45998514/
我有一个在 InfluxDB 上存储数据的指标收集器,我想测试存储该指标的方法。我正在尝试,但无法模拟 InfluxDB 客户端。我不想指出测试环境中真实的 InfluxDB。 到目前为止我所取得的一
我是一名优秀的程序员,十分优秀!