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);
}
}
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");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With