Browse Source

Add nullability annotations to tests in module/spring-boot-micrometer-metrics

See gh-47263
pull/47626/head
Moritz Halbritter 2 months ago
parent
commit
11d50ae293
  1. 8
      module/spring-boot-micrometer-metrics/build.gradle
  2. 5
      module/spring-boot-micrometer-metrics/src/test/java/org/springframework/boot/micrometer/metrics/ValidationFailureAnalyzerTests.java
  3. 16
      module/spring-boot-micrometer-metrics/src/test/java/org/springframework/boot/micrometer/metrics/actuate/endpoint/MetricsEndpointTests.java
  4. 5
      module/spring-boot-micrometer-metrics/src/test/java/org/springframework/boot/micrometer/metrics/autoconfigure/MeterRegistryCustomizerTests.java
  5. 31
      module/spring-boot-micrometer-metrics/src/test/java/org/springframework/boot/micrometer/metrics/autoconfigure/MeterRegistryPostProcessorTests.java
  6. 15
      module/spring-boot-micrometer-metrics/src/test/java/org/springframework/boot/micrometer/metrics/autoconfigure/MetricsAspectsAutoConfigurationTests.java
  7. 1
      module/spring-boot-micrometer-metrics/src/test/java/org/springframework/boot/micrometer/metrics/autoconfigure/MetricsAutoConfigurationMeterRegistryPostProcessorIntegrationTests.java
  8. 7
      module/spring-boot-micrometer-metrics/src/test/java/org/springframework/boot/micrometer/metrics/autoconfigure/MetricsAutoConfigurationTests.java
  9. 1
      module/spring-boot-micrometer-metrics/src/test/java/org/springframework/boot/micrometer/metrics/autoconfigure/PropertiesMeterFilterTests.java
  10. 9
      module/spring-boot-micrometer-metrics/src/test/java/org/springframework/boot/micrometer/metrics/autoconfigure/export/prometheus/PrometheusMetricsExportAutoConfigurationTests.java
  11. 8
      module/spring-boot-micrometer-metrics/src/test/java/org/springframework/boot/micrometer/metrics/autoconfigure/startup/StartupTimeMetricsListenerAutoConfigurationTests.java
  12. 16
      module/spring-boot-micrometer-metrics/src/test/java/org/springframework/boot/micrometer/metrics/startup/StartupTimeMetricsListenerTests.java

8
module/spring-boot-micrometer-metrics/build.gradle

@ -82,3 +82,11 @@ dependencies { @@ -82,3 +82,11 @@ dependencies {
testRuntimeOnly("ch.qos.logback:logback-classic")
}
tasks.named("compileTestJava") {
options.nullability.checking = "tests"
}
tasks.named("compileDockerTestJava") {
options.nullability.checking = "tests"
}

5
module/spring-boot-micrometer-metrics/src/test/java/org/springframework/boot/micrometer/metrics/ValidationFailureAnalyzerTests.java

@ -19,6 +19,7 @@ package org.springframework.boot.micrometer.metrics; @@ -19,6 +19,7 @@ package org.springframework.boot.micrometer.metrics;
import io.micrometer.core.instrument.Clock;
import io.micrometer.newrelic.NewRelicConfig;
import io.micrometer.newrelic.NewRelicMeterRegistry;
import org.jspecify.annotations.Nullable;
import org.junit.jupiter.api.Test;
import org.springframework.boot.diagnostics.FailureAnalysis;
@ -51,7 +52,7 @@ class ValidationFailureAnalyzerTests { @@ -51,7 +52,7 @@ class ValidationFailureAnalyzerTests {
private Exception createFailure(Class<?> configuration) {
try (ConfigurableApplicationContext context = new AnnotationConfigApplicationContext(configuration)) {
fail("Expected failure did not occur");
return null;
throw new AssertionError("Should not be reached");
}
catch (Exception ex) {
return ex;
@ -66,7 +67,7 @@ class ValidationFailureAnalyzerTests { @@ -66,7 +67,7 @@ class ValidationFailureAnalyzerTests {
return new NewRelicMeterRegistry(new NewRelicConfig() {
@Override
public String get(String key) {
public @Nullable String get(String key) {
return null;
}

16
module/spring-boot-micrometer-metrics/src/test/java/org/springframework/boot/micrometer/metrics/actuate/endpoint/MetricsEndpointTests.java

@ -30,6 +30,7 @@ import io.micrometer.core.instrument.simple.SimpleMeterRegistry; @@ -30,6 +30,7 @@ import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
import org.junit.jupiter.api.Test;
import org.springframework.boot.actuate.endpoint.InvalidEndpointRequestException;
import org.springframework.boot.micrometer.metrics.actuate.endpoint.MetricsEndpoint.MetricDescriptor;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
@ -85,10 +86,12 @@ class MetricsEndpointTests { @@ -85,10 +86,12 @@ class MetricsEndpointTests {
this.registry.counter("cache", "result", "miss", "host", "1").increment(2);
this.registry.counter("cache", "result", "hit", "host", "2").increment(2);
MetricsEndpoint.MetricDescriptor response = this.endpoint.metric("cache", Collections.emptyList());
assertThat(response).isNotNull();
assertThat(response.getName()).isEqualTo("cache");
assertThat(availableTagKeys(response)).containsExactly("result", "host");
assertThat(getCount(response)).hasValue(6.0);
response = this.endpoint.metric("cache", Collections.singletonList("result:hit"));
assertThat(response).isNotNull();
assertThat(availableTagKeys(response)).containsExactly("host");
assertThat(getCount(response)).hasValue(4.0);
}
@ -107,10 +110,12 @@ class MetricsEndpointTests { @@ -107,10 +110,12 @@ class MetricsEndpointTests {
secondLevel.counter("cache", "result", "hit", "host", "2").increment(2);
MetricsEndpoint endpoint = new MetricsEndpoint(composite);
MetricsEndpoint.MetricDescriptor response = endpoint.metric("cache", Collections.emptyList());
assertThat(response).isNotNull();
assertThat(response.getName()).isEqualTo("cache");
assertThat(availableTagKeys(response)).containsExactly("result", "host");
assertThat(getCount(response)).hasValue(6.0);
response = endpoint.metric("cache", Collections.singletonList("result:hit"));
assertThat(response).isNotNull();
assertThat(availableTagKeys(response)).containsExactly("host");
assertThat(getCount(response)).hasValue(4.0);
}
@ -132,6 +137,7 @@ class MetricsEndpointTests { @@ -132,6 +137,7 @@ class MetricsEndpointTests {
this.registry.counter("cache", "host", "1", "region", "east", "result", "hit");
this.registry.counter("cache", "host", "1", "region", "east", "result", "miss");
MetricsEndpoint.MetricDescriptor response = this.endpoint.metric("cache", Collections.singletonList("host:1"));
assertThat(response).isNotNull();
assertThat(response.getAvailableTags()
.stream()
.filter((t) -> t.getTag().equals("region"))
@ -143,6 +149,7 @@ class MetricsEndpointTests { @@ -143,6 +149,7 @@ class MetricsEndpointTests {
this.registry.counter("counter", "key", "a space").increment(2);
MetricsEndpoint.MetricDescriptor response = this.endpoint.metric("counter",
Collections.singletonList("key:a space"));
assertThat(response).isNotNull();
assertThat(response.getName()).isEqualTo("counter");
assertThat(availableTagKeys(response)).isEmpty();
assertThat(getCount(response)).hasValue(2.0);
@ -193,11 +200,10 @@ class MetricsEndpointTests { @@ -193,11 +200,10 @@ class MetricsEndpointTests {
private void assertMetricHasStatisticEqualTo(MeterRegistry registry, String metricName, Statistic stat,
Double value) {
MetricsEndpoint endpoint = new MetricsEndpoint(registry);
assertThat(endpoint.metric(metricName, Collections.emptyList())
.getMeasurements()
.stream()
.filter((sample) -> sample.getStatistic().equals(stat))
.findAny()).hasValueSatisfying((sample) -> assertThat(sample.getValue()).isEqualTo(value));
MetricDescriptor metric = endpoint.metric(metricName, Collections.emptyList());
assertThat(metric).isNotNull();
assertThat(metric.getMeasurements().stream().filter((sample) -> sample.getStatistic().equals(stat)).findAny())
.hasValueSatisfying((sample) -> assertThat(sample.getValue()).isEqualTo(value));
}
private Optional<Double> getCount(MetricsEndpoint.MetricDescriptor response) {

5
module/spring-boot-micrometer-metrics/src/test/java/org/springframework/boot/micrometer/metrics/autoconfigure/MeterRegistryCustomizerTests.java

@ -21,6 +21,7 @@ import io.micrometer.atlas.AtlasMeterRegistry; @@ -21,6 +21,7 @@ import io.micrometer.atlas.AtlasMeterRegistry;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.prometheusmetrics.PrometheusConfig;
import io.micrometer.prometheusmetrics.PrometheusMeterRegistry;
import org.jspecify.annotations.Nullable;
import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations;
@ -43,7 +44,7 @@ class MeterRegistryCustomizerTests { @@ -43,7 +44,7 @@ class MeterRegistryCustomizerTests {
.withBean(AtlasMeterRegistry.class, () -> new AtlasMeterRegistry(new AtlasConfig() {
@Override
public String get(String k) {
public @Nullable String get(String k) {
return null;
}
@ -51,7 +52,7 @@ class MeterRegistryCustomizerTests { @@ -51,7 +52,7 @@ class MeterRegistryCustomizerTests {
.withBean(PrometheusMeterRegistry.class, () -> new PrometheusMeterRegistry(new PrometheusConfig() {
@Override
public String get(String key) {
public @Nullable String get(String key) {
return null;
}

31
module/spring-boot-micrometer-metrics/src/test/java/org/springframework/boot/micrometer/metrics/autoconfigure/MeterRegistryPostProcessorTests.java

@ -33,6 +33,8 @@ import org.mockito.InOrder; @@ -33,6 +33,8 @@ import org.mockito.InOrder;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.micrometer.metrics.autoconfigure.MeterRegistryPostProcessor.CompositeMeterRegistries;
@ -60,18 +62,23 @@ class MeterRegistryPostProcessorTests { @@ -60,18 +62,23 @@ class MeterRegistryPostProcessorTests {
private final List<MeterBinder> binders = new ArrayList<>();
@Mock
@SuppressWarnings("NullAway.Init")
private MeterRegistryCustomizer<MeterRegistry> mockCustomizer;
@Mock
@SuppressWarnings("NullAway.Init")
private MeterFilter mockFilter;
@Mock
@SuppressWarnings("NullAway.Init")
private MeterBinder mockBinder;
@Mock
@SuppressWarnings("NullAway.Init")
private MeterRegistry mockRegistry;
@Mock
@SuppressWarnings("NullAway.Init")
private Config mockConfig;
MeterRegistryPostProcessorTests() {
@ -94,8 +101,8 @@ class MeterRegistryPostProcessorTests { @@ -94,8 +101,8 @@ class MeterRegistryPostProcessorTests {
void postProcessAndInitializeWhenAutoConfiguredCompositeAppliesCustomizer() {
this.customizers.add(this.mockCustomizer);
MeterRegistryPostProcessor processor = new MeterRegistryPostProcessor(CompositeMeterRegistries.AUTO_CONFIGURED,
createObjectProvider(this.properties), createObjectProvider(this.customizers), null,
createObjectProvider(this.binders));
createObjectProvider(this.properties), createObjectProvider(this.customizers),
createEmptyObjectProvider(), createObjectProvider(this.binders));
AutoConfiguredCompositeMeterRegistry composite = new AutoConfiguredCompositeMeterRegistry(Clock.SYSTEM,
Collections.emptyList());
postProcessAndInitialize(processor, composite);
@ -152,7 +159,8 @@ class MeterRegistryPostProcessorTests { @@ -152,7 +159,8 @@ class MeterRegistryPostProcessorTests {
given(this.mockRegistry.config()).willReturn(this.mockConfig);
MeterRegistryPostProcessor processor = new MeterRegistryPostProcessor(
CompositeMeterRegistries.ONLY_USER_DEFINED, createObjectProvider(this.properties),
createObjectProvider(this.customizers), createObjectProvider(this.filters), null);
createObjectProvider(this.customizers), createObjectProvider(this.filters),
createEmptyObjectProvider());
postProcessAndInitialize(processor, this.mockRegistry);
then(this.mockBinder).shouldHaveNoInteractions();
}
@ -161,8 +169,8 @@ class MeterRegistryPostProcessorTests { @@ -161,8 +169,8 @@ class MeterRegistryPostProcessorTests {
void whenAutoConfiguredCompositeThenPostProcessAndInitializeAutoConfiguredCompositeBindsTo() {
this.binders.add(this.mockBinder);
MeterRegistryPostProcessor processor = new MeterRegistryPostProcessor(CompositeMeterRegistries.AUTO_CONFIGURED,
createObjectProvider(this.properties), createObjectProvider(this.customizers), null,
createObjectProvider(this.binders));
createObjectProvider(this.properties), createObjectProvider(this.customizers),
createEmptyObjectProvider(), createObjectProvider(this.binders));
AutoConfiguredCompositeMeterRegistry composite = new AutoConfiguredCompositeMeterRegistry(Clock.SYSTEM,
Collections.emptyList());
postProcessAndInitialize(processor, composite);
@ -174,7 +182,7 @@ class MeterRegistryPostProcessorTests { @@ -174,7 +182,7 @@ class MeterRegistryPostProcessorTests {
this.binders.add(this.mockBinder);
MeterRegistryPostProcessor processor = new MeterRegistryPostProcessor(CompositeMeterRegistries.AUTO_CONFIGURED,
createObjectProvider(this.properties), createObjectProvider(this.customizers),
createObjectProvider(this.filters), null);
createObjectProvider(this.filters), createEmptyObjectProvider());
CompositeMeterRegistry composite = new CompositeMeterRegistry();
postProcessAndInitialize(processor, composite);
then(this.mockBinder).shouldHaveNoInteractions();
@ -185,7 +193,7 @@ class MeterRegistryPostProcessorTests { @@ -185,7 +193,7 @@ class MeterRegistryPostProcessorTests {
given(this.mockRegistry.config()).willReturn(this.mockConfig);
MeterRegistryPostProcessor processor = new MeterRegistryPostProcessor(CompositeMeterRegistries.AUTO_CONFIGURED,
createObjectProvider(this.properties), createObjectProvider(this.customizers),
createObjectProvider(this.filters), null);
createObjectProvider(this.filters), createEmptyObjectProvider());
postProcessAndInitialize(processor, this.mockRegistry);
then(this.mockBinder).shouldHaveNoInteractions();
}
@ -264,4 +272,13 @@ class MeterRegistryPostProcessorTests { @@ -264,4 +272,13 @@ class MeterRegistryPostProcessorTests {
return objectProvider;
}
private <T> ObjectProvider<T> createEmptyObjectProvider() {
return new ObjectProvider<T>() {
@Override
public T getObject() throws BeansException {
throw new NoSuchBeanDefinitionException("No bean");
}
};
}
}

15
module/spring-boot-micrometer-metrics/src/test/java/org/springframework/boot/micrometer/metrics/autoconfigure/MetricsAspectsAutoConfigurationTests.java

@ -16,7 +16,10 @@ @@ -16,7 +16,10 @@
package org.springframework.boot.micrometer.metrics.autoconfigure;
import java.util.function.Function;
import io.micrometer.common.annotation.ValueExpressionResolver;
import io.micrometer.common.annotation.ValueResolver;
import io.micrometer.core.aop.CountedAspect;
import io.micrometer.core.aop.CountedMeterTagAnnotationHandler;
import io.micrometer.core.aop.MeterTagAnnotationHandler;
@ -78,7 +81,7 @@ class MetricsAspectsAutoConfigurationTests { @@ -78,7 +81,7 @@ class MetricsAspectsAutoConfigurationTests {
void shouldUseUserDefinedMeterTagAnnotationHandler() {
this.contextRunner
.withBean("customMeterTagAnnotationHandler", MeterTagAnnotationHandler.class,
() -> new MeterTagAnnotationHandler(null, null))
() -> new MeterTagAnnotationHandler(getResolverProvider(), getExpressionResolverProvider()))
.run((context) -> {
assertThat(context).hasSingleBean(TimedAspect.class).hasSingleBean(MeterTagAnnotationHandler.class);
assertThat(context.getBean(TimedAspect.class)).extracting("meterTagAnnotationHandler")
@ -101,7 +104,7 @@ class MetricsAspectsAutoConfigurationTests { @@ -101,7 +104,7 @@ class MetricsAspectsAutoConfigurationTests {
void shouldUseUserDefinedCountedMeterTagAnnotationHandler() {
this.contextRunner
.withBean("customCountedMeterTagAnnotationHandler", CountedMeterTagAnnotationHandler.class,
() -> new CountedMeterTagAnnotationHandler(null, null))
() -> new CountedMeterTagAnnotationHandler(getResolverProvider(), getExpressionResolverProvider()))
.run((context) -> {
assertThat(context).hasSingleBean(CountedAspect.class)
.hasSingleBean(CountedMeterTagAnnotationHandler.class);
@ -144,6 +147,14 @@ class MetricsAspectsAutoConfigurationTests { @@ -144,6 +147,14 @@ class MetricsAspectsAutoConfigurationTests {
});
}
private Function<Class<? extends ValueExpressionResolver>, ValueExpressionResolver> getExpressionResolverProvider() {
return (clazz) -> mock(ValueExpressionResolver.class);
}
private Function<Class<? extends ValueResolver>, ValueResolver> getResolverProvider() {
return (clazz) -> mock(ValueResolver.class);
}
@Configuration(proxyBeanMethods = false)
static class CustomAspectsConfiguration {

1
module/spring-boot-micrometer-metrics/src/test/java/org/springframework/boot/micrometer/metrics/autoconfigure/MetricsAutoConfigurationMeterRegistryPostProcessorIntegrationTests.java

@ -131,7 +131,6 @@ class MetricsAutoConfigurationMeterRegistryPostProcessorIntegrationTests { @@ -131,7 +131,6 @@ class MetricsAutoConfigurationMeterRegistryPostProcessorIntegrationTests {
if (bean instanceof Bravo) {
MeterRegistry meterRegistry = context.getBean(MeterRegistry.class);
meterRegistry.gauge("test", 1);
System.out.println(meterRegistry.find("test").gauge().getId().getTags());
}
return bean;
}

7
module/spring-boot-micrometer-metrics/src/test/java/org/springframework/boot/micrometer/metrics/autoconfigure/MetricsAutoConfigurationTests.java

@ -17,7 +17,7 @@ @@ -17,7 +17,7 @@
package org.springframework.boot.micrometer.metrics.autoconfigure;
import io.micrometer.core.instrument.Clock;
import io.micrometer.core.instrument.Meter;
import io.micrometer.core.instrument.Counter;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.binder.MeterBinder;
import io.micrometer.core.instrument.config.MeterFilter;
@ -71,9 +71,10 @@ class MetricsAutoConfigurationTests { @@ -71,9 +71,10 @@ class MetricsAutoConfigurationTests {
MeterRegistry meterRegistry = context.getBean(MeterRegistry.class);
MeterFilter[] filters = (MeterFilter[]) ReflectionTestUtils.getField(meterRegistry, "filters");
assertThat(filters).hasSize(3);
assertThat(filters[0].accept((Meter.Id) null)).isEqualTo(MeterFilterReply.DENY);
Counter counter = meterRegistry.counter("counter");
assertThat(filters[0].accept(counter.getId())).isEqualTo(MeterFilterReply.DENY);
assertThat(filters[1]).isInstanceOf(PropertiesMeterFilter.class);
assertThat(filters[2].accept((Meter.Id) null)).isEqualTo(MeterFilterReply.ACCEPT);
assertThat(filters[2].accept(counter.getId())).isEqualTo(MeterFilterReply.ACCEPT);
then((MeterBinder) context.getBean("meterBinder")).should().bindTo(meterRegistry);
then(context.getBean(MeterRegistryCustomizer.class)).should().customize(meterRegistry);
});

1
module/spring-boot-micrometer-metrics/src/test/java/org/springframework/boot/micrometer/metrics/autoconfigure/PropertiesMeterFilterTests.java

@ -46,6 +46,7 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException @@ -46,6 +46,7 @@ import static org.assertj.core.api.Assertions.assertThatIllegalArgumentException
class PropertiesMeterFilterTests {
@Test
@SuppressWarnings("NullAway") // Test null check
void createWhenPropertiesIsNullShouldThrowException() {
assertThatIllegalArgumentException().isThrownBy(() -> new PropertiesMeterFilter(null))
.withMessageContaining("'properties' must not be null");

9
module/spring-boot-micrometer-metrics/src/test/java/org/springframework/boot/micrometer/metrics/autoconfigure/export/prometheus/PrometheusMetricsExportAutoConfigurationTests.java

@ -28,6 +28,7 @@ import io.prometheus.metrics.expositionformats.PrometheusTextFormatWriter; @@ -28,6 +28,7 @@ import io.prometheus.metrics.expositionformats.PrometheusTextFormatWriter;
import io.prometheus.metrics.model.registry.PrometheusRegistry;
import io.prometheus.metrics.tracer.common.SpanContext;
import org.assertj.core.api.InstanceOfAssertFactories;
import org.jspecify.annotations.Nullable;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
@ -266,7 +267,9 @@ class PrometheusMetricsExportAutoConfigurationTests { @@ -266,7 +267,9 @@ class PrometheusMetricsExportAutoConfigurationTests {
private PushGateway getPushGateway(AssertableApplicationContext context) {
assertThat(context).hasSingleBean(PrometheusPushGatewayManager.class);
PrometheusPushGatewayManager gatewayManager = context.getBean(PrometheusPushGatewayManager.class);
return (PushGateway) ReflectionTestUtils.getField(gatewayManager, "pushGateway");
Object field = ReflectionTestUtils.getField(gatewayManager, "pushGateway");
assertThat(field).isNotNull();
return (PushGateway) field;
}
@Configuration(proxyBeanMethods = false)
@ -335,12 +338,12 @@ class PrometheusMetricsExportAutoConfigurationTests { @@ -335,12 +338,12 @@ class PrometheusMetricsExportAutoConfigurationTests {
return new SpanContext() {
@Override
public String getCurrentTraceId() {
public @Nullable String getCurrentTraceId() {
return null;
}
@Override
public String getCurrentSpanId() {
public @Nullable String getCurrentSpanId() {
return null;
}

8
module/spring-boot-micrometer-metrics/src/test/java/org/springframework/boot/micrometer/metrics/autoconfigure/startup/StartupTimeMetricsListenerAutoConfigurationTests.java

@ -53,12 +53,12 @@ class StartupTimeMetricsListenerAutoConfigurationTests { @@ -53,12 +53,12 @@ class StartupTimeMetricsListenerAutoConfigurationTests {
this.contextRunner.run((context) -> {
assertThat(context).hasSingleBean(StartupTimeMetricsListener.class);
SimpleMeterRegistry registry = context.getBean(SimpleMeterRegistry.class);
context.publishEvent(new ApplicationStartedEvent(new SpringApplication(), null,
context.publishEvent(new ApplicationStartedEvent(new SpringApplication(), new String[0],
context.getSourceApplicationContext(), Duration.ofMillis(1500)));
TimeGauge startedTimeGage = registry.find("application.started.time").timeGauge();
assertThat(startedTimeGage).isNotNull();
assertThat(startedTimeGage.value(TimeUnit.MILLISECONDS)).isEqualTo(1500L);
context.publishEvent(new ApplicationReadyEvent(new SpringApplication(), null,
context.publishEvent(new ApplicationReadyEvent(new SpringApplication(), new String[0],
context.getSourceApplicationContext(), Duration.ofMillis(2000)));
TimeGauge readyTimeGage = registry.find("application.ready.time").timeGauge();
assertThat(readyTimeGage).isNotNull();
@ -72,9 +72,9 @@ class StartupTimeMetricsListenerAutoConfigurationTests { @@ -72,9 +72,9 @@ class StartupTimeMetricsListenerAutoConfigurationTests {
.withPropertyValues("management.metrics.enable.application.started.time:false",
"management.metrics.enable.application.ready.time:false")
.run((context) -> {
context.publishEvent(new ApplicationStartedEvent(new SpringApplication(), null,
context.publishEvent(new ApplicationStartedEvent(new SpringApplication(), new String[0],
context.getSourceApplicationContext(), Duration.ofMillis(2500)));
context.publishEvent(new ApplicationReadyEvent(new SpringApplication(), null,
context.publishEvent(new ApplicationReadyEvent(new SpringApplication(), new String[0],
context.getSourceApplicationContext(), Duration.ofMillis(3000)));
SimpleMeterRegistry registry = context.getBean(SimpleMeterRegistry.class);
assertThat(registry.find("application.started.time").timeGauge()).isNull();

16
module/spring-boot-micrometer-metrics/src/test/java/org/springframework/boot/micrometer/metrics/startup/StartupTimeMetricsListenerTests.java

@ -23,12 +23,14 @@ import io.micrometer.core.instrument.MeterRegistry; @@ -23,12 +23,14 @@ import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Tags;
import io.micrometer.core.instrument.TimeGauge;
import io.micrometer.core.instrument.simple.SimpleMeterRegistry;
import org.jspecify.annotations.Nullable;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.ConfigurableApplicationContext;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.BDDMockito.given;
@ -72,7 +74,8 @@ class StartupTimeMetricsListenerTests { @@ -72,7 +74,8 @@ class StartupTimeMetricsListenerTests {
@Test
void metricRecordedWithoutMainAppClassTag() {
SpringApplication application = mock(SpringApplication.class);
this.listener.onApplicationEvent(new ApplicationStartedEvent(application, null, null, Duration.ofSeconds(2)));
this.listener.onApplicationEvent(new ApplicationStartedEvent(application, new String[0],
mock(ConfigurableApplicationContext.class), Duration.ofSeconds(2)));
TimeGauge applicationStartedGauge = this.registry.find("application.started.time").timeGauge();
assertThat(applicationStartedGauge).isNotNull();
assertThat(applicationStartedGauge.getId().getTags()).isEmpty();
@ -83,7 +86,8 @@ class StartupTimeMetricsListenerTests { @@ -83,7 +86,8 @@ class StartupTimeMetricsListenerTests {
SpringApplication application = mock(SpringApplication.class);
Tags tags = Tags.of("foo", "bar");
this.listener = new StartupTimeMetricsListener(this.registry, "started", "ready", tags);
this.listener.onApplicationEvent(new ApplicationReadyEvent(application, null, null, Duration.ofSeconds(2)));
this.listener.onApplicationEvent(new ApplicationReadyEvent(application, new String[0],
mock(ConfigurableApplicationContext.class), Duration.ofSeconds(2)));
TimeGauge applicationReadyGauge = this.registry.find("ready").timeGauge();
assertThat(applicationReadyGauge).isNotNull();
assertThat(applicationReadyGauge.getId().getTags()).containsExactlyElementsOf(tags);
@ -97,17 +101,17 @@ class StartupTimeMetricsListenerTests { @@ -97,17 +101,17 @@ class StartupTimeMetricsListenerTests {
assertThat(this.registry.find("application.ready.time").timeGauge()).isNull();
}
private ApplicationStartedEvent applicationStartedEvent(Long startupTimeMs) {
private ApplicationStartedEvent applicationStartedEvent(@Nullable Long startupTimeMs) {
SpringApplication application = mock(SpringApplication.class);
given(application.getMainApplicationClass()).willAnswer((invocation) -> TestMainApplication.class);
return new ApplicationStartedEvent(application, null, null,
return new ApplicationStartedEvent(application, new String[0], mock(ConfigurableApplicationContext.class),
(startupTimeMs != null) ? Duration.ofMillis(startupTimeMs) : null);
}
private ApplicationReadyEvent applicationReadyEvent(Long startupTimeMs) {
private ApplicationReadyEvent applicationReadyEvent(@Nullable Long startupTimeMs) {
SpringApplication application = mock(SpringApplication.class);
given(application.getMainApplicationClass()).willAnswer((invocation) -> TestMainApplication.class);
return new ApplicationReadyEvent(application, null, null,
return new ApplicationReadyEvent(application, new String[0], mock(ConfigurableApplicationContext.class),
(startupTimeMs != null) ? Duration.ofMillis(startupTimeMs) : null);
}

Loading…
Cancel
Save