Skip to content

Commit 004ab04

Browse files
committed
Add a counter and a unit test for it
1 parent 0070096 commit 004ab04

File tree

2 files changed

+31
-4
lines changed

2 files changed

+31
-4
lines changed

src/main/java/com/tutorialworks/demos/springbootwithmetrics/GreetingController.java

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ public GreetingController(MeterRegistry registry) {
3232
@Timed(value = "greeting.time", description = "Time taken to return greeting",
3333
percentiles = {0.5, 0.90})
3434
public Greeting greeting(@RequestParam(value = "name", defaultValue = "World") String name) {
35+
registry.counter("greetings.counter").increment();
3536
return new Greeting(counter.incrementAndGet(), String.format(template, name));
3637
}
3738

Lines changed: 30 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,39 @@
11
package com.tutorialworks.demos.springbootwithmetrics;
22

3+
import io.micrometer.core.instrument.MeterRegistry;
34
import org.junit.jupiter.api.Test;
5+
import org.springframework.beans.factory.annotation.Autowired;
46
import org.springframework.boot.test.context.SpringBootTest;
7+
import org.springframework.boot.test.web.client.TestRestTemplate;
8+
import org.springframework.http.ResponseEntity;
59

6-
@SpringBootTest
10+
import java.util.Map;
11+
12+
import static org.assertj.core.api.Assertions.assertThat;
13+
14+
/**
15+
* Basic integration tests to check that metrics are rendered.
16+
*/
17+
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
718
class SpringBootWithMetricsApplicationTests {
819

9-
@Test
10-
void contextLoads() {
11-
}
20+
@Autowired
21+
private TestRestTemplate restTemplate;
22+
23+
@Autowired
24+
MeterRegistry registry;
25+
26+
/**
27+
* Sends a test request to the Greeting API, then asserts that the counter
28+
* has increased to 1.
29+
* @throws InterruptedException
30+
*/
31+
@Test
32+
void testMetricsRequestCounterIncreases() throws InterruptedException {
33+
// Make a test request to the Greeting service
34+
ResponseEntity<String> response = this.restTemplate.getForEntity("/greeting", String.class);
35+
36+
assertThat(registry.get("greetings.counter").counter().count()).isEqualTo(1);
37+
}
1238

1339
}

0 commit comments

Comments
 (0)