测试
Micrometer Observation 提供了一个 micrometer-observation-test
模块,该模块允许你对 Observations 进行单元测试。
安装
建议使用 Micrometer(或您使用的框架,如果有的话)提供的 BOM,您可以在此处查看如何配置它 here。以下示例假定您正在使用 BOM。
Gradle
在 BOM 配置 完成后,添加以下依赖:
testImplementation 'io.micrometer:micrometer-observation-test'
由于该依赖项的版本由 BOM 定义,因此不需要指定版本。
Maven
在 配置 完 BOM 之后,添加以下依赖:
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-observation-test</artifactId>
<scope>test</scope>
</dependency>
由于该依赖项的版本由 BOM 定义,因此不需要指定版本。
运行观察单元测试
假设你有以下生产代码。它将创建一个带有两个标签(低基数和高基数)的观测,然后调用 observe
来启动观测,将其放入作用域中,关闭作用域,并停止观测:
static class Example {
private final ObservationRegistry registry;
Example(ObservationRegistry registry) {
this.registry = registry;
}
void run() {
Observation.createNotStarted("foo", registry)
.lowCardinalityKeyValue("lowTag", "lowTagValue")
.highCardinalityKeyValue("highTag", "highTagValue")
.observe(() -> System.out.println("Hello"));
}
}
要对这段代码进行单元测试,你可以使用 TestObservationRegistry
类:
@Test
void should_assert_your_observation() {
// create a test registry in your tests
TestObservationRegistry registry = TestObservationRegistry.create();
// run your production code with the TestObservationRegistry
new Example(registry).run();
// check your observation
assertThat(registry)
.doesNotHaveAnyRemainingCurrentObservation()
.hasObservationWithNameEqualTo("foo")
.that()
.hasHighCardinalityKeyValue("highTag", "highTagValue")
.hasLowCardinalityKeyValue("lowTag", "lowTagValue")
.hasBeenStarted()
.hasBeenStopped();
}
观察验证器
如果你使用 TestObservationRegistry
,一个名为 ObservationValidator
的 ObservationHandler
会被自动注册。这个 ObservationHandler
的目的是验证 Observation
上的调用顺序(例如,stop
不应该在 start
之前调用,或者两者都不应该被调用两次等)。请查看 ObservationValidatorTests
以了解无效场景的列表。
如果 ObservationValidator
检测到此类问题,它将抛出一个 InvalidObservationException
,其中包含一个验证消息(解释为什么 Observation
无效)、原始的 Observation.Context
以及一个包含在 Observation
上进行的调用的相关堆栈跟踪的历史记录。这些信息应该能帮助你排查仪器化过程中出现的问题。InvalidObservationException
的 toString()
方法会提供错误消息和历史记录的文本摘要,类似于以下内容:
io.micrometer.observation.tck.InvalidObservationException: Invalid error signal: Observation has already been stopped
START: app//io.micrometer.observation.tck.ObservationValidatorTests.errorAfterStopShouldBeInvalid(ObservationValidatorTests.java:98)
STOP: app//io.micrometer.observation.tck.ObservationValidatorTests.errorAfterStopShouldBeInvalid(ObservationValidatorTests.java:99)
ERROR: app//io.micrometer.observation.tck.ObservationValidatorTests.errorAfterStopShouldBeInvalid(ObservationValidatorTests.java:100)
基于此,似乎 error
(在 ObservationValidatorTests.java
文件的第 #100
行)是在 stop
(在 ObservationValidatorTests.java
文件的第 #99
行)之后被调用的,这是一个无效的场景。如果你在 IDE 中查看错误,位置(例如:ObservationValidatorTests.java:98
)应该是“链接”,点击它们应该会让 IDE 跳转到该行。
如果你在第三方库的插装过程中遇到类似上述的错误,请为该项目提交 issue 或 pull request。