python-test-micrometer-testing-metrics
Tests custom Micrometer metrics in unit and integration tests using SimpleMeterRegistry. Use when writing tests for services that record metrics, validating metric values after operations, testing percentiles and histograms, or asserting metric behavior without full Spring context. Essential for ensuring metrics are accurately recorded in business logic.
What this skill does
# Micrometer Testing Metrics
## Table of Contents
**Quick Start** → [What Is This](#purpose) | [When to Use](#when-to-use) | [Simple Example](#quick-start)
**How to Implement** → [Step-by-Step](#instructions) | [Test Registry Setup](#step-1-choose-the-right-registry-for-your-test) | [Examples](#examples)
**Help** → [Anti-Patterns](#anti-patterns-to-avoid) | [Requirements](#requirements)
**Reference** → [Related Skills](#see-also)
## Purpose
Testing metrics requires explicit registry setup since Micrometer doesn't auto-wire in unit tests. This skill shows how to verify that custom metrics are correctly recorded in unit tests (SimpleMeterRegistry), integration tests (@AutoConfigureMetrics), and percentile/histogram calculations.
## When to Use
Use this skill when:
- Writing unit tests for services that record metrics
- Validating metric values after business operations
- Testing percentiles and histogram configurations
- Asserting metric behavior without full Spring context
- Verifying counter increments, timer durations, or gauge values
- Testing integration with Spring Boot Actuator
- Debugging why metrics aren't being recorded in tests
## Quick Start
For unit tests, use `SimpleMeterRegistry`:
```java
class ChargeServiceTest {
private SimpleMeterRegistry registry;
private ChargeService chargeService;
@BeforeEach
void setUp() {
registry = new SimpleMeterRegistry();
chargeService = new ChargeService(registry);
}
@Test
void testChargeProcessingRecordsMetrics() {
Charge charge = new Charge("SUP123", BigDecimal.valueOf(150.00));
chargeService.processCharge(charge);
Counter counter = registry.get("charge.processed").counter();
assertThat(counter.count()).isEqualTo(1);
}
}
```
## Instructions
### Step 1: Choose the Right Registry for Your Test
**SimpleMeterRegistry** (unit tests, no Spring):
- Use for testing service logic in isolation
- Fast, no Spring context startup
- Meters accessible immediately after recording
- No percentile calculations (use assertions instead)
**MeterRegistry with @AutoConfigureMetrics** (integration tests):
- Use when testing with Spring context
- Spring auto-configures actual metrics
- Slower but tests real behavior
- Supports percentiles if configured
**CompositeMeterRegistry** (multi-backend testing):
- Use when testing with multiple backends
- Rarely needed in unit tests
```java
// ❌ Wrong: no registry
class ServiceTest {
private Service service = new Service(); // Needs registry!
}
// ✅ Unit test: SimpleMeterRegistry
class ServiceTest {
private SimpleMeterRegistry registry = new SimpleMeterRegistry();
private Service service = new Service(registry);
}
// ✅ Integration test: Spring auto-configures
@SpringBootTest
@AutoConfigureMetrics
class ServiceIntegrationTest {
@Autowired private MeterRegistry registry;
@Autowired private Service service;
}
```
### Step 2: Set Up Test Fixtures
Create test fixtures for common patterns:
```java
// Base test class for metrics testing
class MetricsTestBase {
protected SimpleMeterRegistry registry;
@BeforeEach
void setUp() {
registry = new SimpleMeterRegistry();
}
/**
* Assert that a counter with given name and tags exists and has expected count.
*/
protected void assertCounterValue(String name, long expectedValue, Tag... tags) {
Counter counter = registry.get(name)
.tags(tags)
.counter();
assertThat(counter.count())
.as("Counter %s with tags %s", name, Arrays.asList(tags))
.isEqualTo(expectedValue);
}
/**
* Assert that a timer with given name has recorded expected count.
*/
protected void assertTimerCount(String name, long expectedCount, Tag... tags) {
Timer timer = registry.get(name)
.tags(tags)
.timer();
assertThat(timer.count())
.as("Timer %s count with tags %s", name, Arrays.asList(tags))
.isEqualTo(expectedCount);
}
/**
* Assert that a distribution summary has expected count and total.
*/
protected void assertDistributionSummary(
String name,
long expectedCount,
double expectedTotal,
Tag... tags) {
DistributionSummary summary = registry.get(name)
.tags(tags)
.summary();
assertThat(summary.count())
.as("DistributionSummary %s count", name)
.isEqualTo(expectedCount);
assertThat(summary.totalAmount())
.as("DistributionSummary %s total", name)
.isCloseTo(expectedTotal, within(0.01));
}
/**
* List all metrics for debugging.
*/
protected void printMetrics() {
registry.getMeters().forEach(meter -> {
System.out.println(meter.getId().getName() +
" [" + meter.getId().getTags() + "]: " +
meter.measure());
});
}
}
```
### Step 3: Test Counter Metrics
Test that counters increment correctly:
```java
class ChargeServiceTest extends MetricsTestBase {
private ChargeService chargeService;
@BeforeEach
void setUp() {
super.setUp();
chargeService = new ChargeService(registry);
}
@Test
void testChargeProcessingIncrementsCounter() {
Charge charge = new Charge("SUP123", BigDecimal.valueOf(150.00));
chargeService.processCharge(charge);
assertCounterValue("charge.processed", 1);
}
@Test
void testMultipleChargesIncrementCounter() {
chargeService.processCharge(new Charge("SUP1", BigDecimal.valueOf(100)));
chargeService.processCharge(new Charge("SUP2", BigDecimal.valueOf(200)));
chargeService.processCharge(new Charge("SUP3", BigDecimal.valueOf(300)));
assertCounterValue("charge.processed", 3);
}
@Test
void testChargeRejectionRecordsWithReason() {
chargeService.rejectCharge("validation");
chargeService.rejectCharge("duplicate");
chargeService.rejectCharge("validation");
assertCounterValue("charge.rejected", 2, Tag.of("reason", "validation"));
assertCounterValue("charge.rejected", 1, Tag.of("reason", "duplicate"));
}
}
```
### Step 4: Test Timer Metrics
Test that timers record duration:
```java
class ChargeProcessingTest extends MetricsTestBase {
private ChargeService service;
@BeforeEach
void setUp() {
super.setUp();
service = new ChargeService(registry);
}
@Test
void testChargeApprovalRecordsDuration() {
Charge charge = new Charge("SUP123", BigDecimal.valueOf(150.00));
service.processCharge(charge);
Timer timer = registry.get("charge.approval.duration").timer();
assertThat(timer.count()).isEqualTo(1);
assertThat(timer.totalTime(TimeUnit.MILLISECONDS)).isGreaterThan(0);
}
@Test
void testTimerRecordsAllOperations() {
for (int i = 0; i < 5; i++) {
service.processCharge(new Charge("SUP" + i, BigDecimal.ONE));
}
Timer timer = registry.get("charge.approval.duration").timer();
assertThat(timer.count()).isEqualTo(5);
assertThat(timer.totalTime(TimeUnit.MILLISECONDS))
.isGreaterThan(timer.count() * 1); // At least 1ms per operation
}
@Test
void testTimerTracksMaxDuration() {
service.recordApprovalTime(Duration.ofMillis(10));
service.recordApprovalTime(Duration.ofMillis(100));
service.recordApprovalTime(Duration.ofMillis(50));
Timer timer = registry.get("charge.approval.duration").timer();
assertThat(timer.max(TimeUnit.MILLISECONDS)).isEqualTo(100);
}
}
```
### Step 5: Test Distribution Summary Metrics
Test value distributions:
```java
class ChargeValueMetricsTest extends MetricsTestBase {
private ChargeService service;
Related in Data & Analytics
clawarr-suite
IncludedComprehensive management for self-hosted media stacks (Sonarr, Radarr, Lidarr, Readarr, Prowlarr, Bazarr, Overseerr, Plex, Tautulli, SABnzbd, Recyclarr, Unpackerr, Notifiarr, Maintainerr, Kometa, FlareSolverr). Deep library exploration, analytics, dashboard generation, content management, request handling, subtitle management, indexer control, download monitoring, quality profile sync, library cleanup automation, notification routing, collection/overlay management, and media tracker integration (Trakt, Letterboxd, Simkl).
querying-soql
IncludedSOQL query generation, optimization, and analysis with 100-point scoring. Use this skill when the user needs SOQL/SOSL authoring or optimization: natural-language-to-query generation, relationship queries, aggregates, query-plan analysis, and performance or safety improvements for Salesforce queries. TRIGGER when: user writes, optimizes, or debugs SOQL/SOSL queries, touches .soql files, or asks about relationship queries, aggregates, or query performance. DO NOT TRIGGER when: bulk data operations (use handling-sf-data), Apex DML logic (use generating-apex), or report/dashboard queries.
app-store-optimization
IncludedApp Store Optimization (ASO) toolkit for researching keywords, analyzing competitor rankings, generating metadata suggestions, and improving app visibility on Apple App Store and Google Play Store. Use when the user asks about ASO, app store rankings, app metadata, app titles and descriptions, app store listings, app visibility, or mobile app marketing on iOS or Android. Supports keyword research and scoring, competitor keyword analysis, metadata optimization, A/B test planning, launch checklists, and tracking ranking changes.
habit-flow
IncludedAI-powered atomic habit tracker with natural language logging, streak tracking, smart reminders, and coaching. Use for creating habits, logging completions naturally ("I meditated today"), viewing progress, and getting personalized coaching.
app-store-optimization
IncludedApp Store Optimization (ASO) toolkit for researching keywords, analyzing competitor rankings, generating metadata suggestions, and improving app visibility on Apple App Store and Google Play Store. Use when the user asks about ASO, app store rankings, app metadata, app titles and descriptions, app store listings, app visibility, or mobile app marketing on iOS or Android. Supports keyword research and scoring, competitor keyword analysis, metadata optimization, A/B test planning, launch checklists, and tracking ranking changes.
visualizing-data
IncludedBuilds dashboards, reports, and data-driven interfaces requiring charts, graphs, or visual analytics. Provides systematic framework for selecting appropriate visualizations based on data characteristics and analytical purpose. Includes 24+ visualization types organized by purpose (trends, comparisons, distributions, relationships, flows, hierarchies, geospatial), accessibility patterns (WCAG 2.1 AA compliance), colorblind-safe palettes, and performance optimization strategies. Use when creating visualizations, choosing chart types, displaying data graphically, or designing data interfaces.