Claude
Skills
Sign in
Back

python-test-micrometer-testing-metrics

Included with Lifetime
$97 forever

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.

Data & Analytics

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