Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Micrometer Unit Test Java

I have created a Micrometer class where counters are created and incremented. How to write unit test cases for the public method and avoid registering or sending the events to micrometer.

public class MicroMeter {
private static final MeterRegistry registry = Metrics.globalRegistry;
private Counter createCounter(final String meterName, Map<String, String> mp) {

    List<Tag> tags = new ArrayList<>();
    for (Map.Entry<String, String> entry : mp.entrySet()) {
        tags.add(Tag.of(entry.getKey(), entry.getValue()));
    }
    return Counter
            .builder(meterName)
            .tags(tags)
            .register(registry);
}

private void incrementCounter(Counter counter)  {
        counter.increment();
}

public static void createCounterAndIncrement(final String meterName, Map<String, String> mp){
    MicroMeter microMeter = new MicroMeter();
    Counter counter = microMeter.createCounter(meterName, dimensions);
    microMeter.incrementCounter(counter);
}

}

like image 225
Firdosh Alia Avatar asked Jun 10 '26 19:06

Firdosh Alia


1 Answers

One way of writing a test for this scenario is to utilize the SimpleMeterRegistry by adding it to the globalRegistry, fetch the Counter and then test the expected behaviour.

Example snippet:

private MeterRegistry meterRegistry;

@BeforeEach
void setUp() {
  meterRegistry = new SimpleMeterRegistry();
  Metrics.globalRegistry.add(meterRegistry);
}

@AfterEach
void tearDown() {
  meterRegistry.clear();
  Metrics.globalRegistry.clear();
}

@Test
void testCreateCounterAndIncrement() {
  // When
  MicroMeter.createCounterAndIncrement("meterName", Map.of("key", "val"));

  // Then
  var counter = meterRegistry.find("meterName").counter();
  then(counter).isNotNull();
  then(counter.count()).isEqualTo(1);
  then(counter.getId().getTag("key")).isEqualTo("val");
 }
like image 166
Hans-Christian Avatar answered Jun 12 '26 08:06

Hans-Christian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!