Skip to content

Conversation

@phipag
Copy link
Contributor

@phipag phipag commented Sep 3, 2025

Summary

This PR allows customers to use a plain Lambda context mock when unit testing request handlers annotated with @FlushMetrics. This addresses an issue where an exception was raised due to a missing AWS Request ID when attempting to collect the cold start metric.

After merging this PR, the following unit test should pass (I also included such a test in the metrics module itself):

@ExtendWith(MockitoExtension.class)
class RequestHandlerTest {

    // For developer convenience, no exceptions should be thrown when using a plain Lambda Context mock
    @Mock
    Context lambdaContext;

    private final PrintStream standardOut = System.out;
    private ByteArrayOutputStream outputStreamCaptor;
    private final ObjectMapper objectMapper = new ObjectMapper();

    @BeforeEach
    void setUp() {
        outputStreamCaptor = new ByteArrayOutputStream();
        System.setOut(new PrintStream(outputStreamCaptor));
    }

    @AfterEach
    void tearDown() throws Exception {
        System.setOut(standardOut);
    }

    @Test
    void shouldCaptureMetricsFromAnnotatedHandler() throws Exception {
        // Given
        RequestHandler<Map<String, Object>, String> handler = new HandlerWithMetricsAnnotation();
        Map<String, Object> input = new HashMap<>();

        // When
        handler.handleRequest(input, lambdaContext);

        // Then
        String emfOutput = outputStreamCaptor.toString().trim();
        JsonNode rootNode = objectMapper.readTree(emfOutput);

        assertThat(rootNode.has("test-metric")).isTrue();
        assertThat(rootNode.get("test-metric").asDouble()).isEqualTo(100.0);
        assertThat(rootNode.get("_aws").get("CloudWatchMetrics").get(0).get("Namespace").asText())
                .isEqualTo("CustomNamespace");
        assertThat(rootNode.has("Service")).isTrue();
        assertThat(rootNode.get("Service").asText()).isEqualTo("CustomService");
    }

    static class HandlerWithMetricsAnnotation implements RequestHandler<Map<String, Object>, String> {
        @Override
        @FlushMetrics(namespace = "CustomNamespace", service = "CustomService")
        public String handleRequest(Map<String, Object> input, Context context) {
            Metrics metrics = MetricsFactory.getMetricsInstance();
            metrics.addMetric("test-metric", 100, MetricUnit.COUNT);
            return "OK";
        }
    }
}

Changes

Issue number: #2019


By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of your choice.

Disclaimer: We value your time and bandwidth. As such, any pull requests created on non-triaged issues might not be successful.

@phipag phipag changed the title test(metrics): Improve testability of @FlushMetrics annotation test(metrics): Improve testability of @FlushMetrics annotation Sep 3, 2025
@phipag phipag self-assigned this Sep 3, 2025
@phipag phipag moved this to Pending review in Powertools for AWS Lambda (Java) Sep 3, 2025
@sonarqubecloud
Copy link

sonarqubecloud bot commented Sep 3, 2025

@phipag phipag merged commit 22ea06a into main Sep 4, 2025
15 checks passed
@phipag phipag deleted the phipag/metrics-unit-test-improvements branch September 4, 2025 08:42
@github-project-automation github-project-automation bot moved this from Pending review to Coming soon in Powertools for AWS Lambda (Java) Sep 4, 2025
@phipag phipag linked an issue Sep 4, 2025 that may be closed by this pull request
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

Status: Coming soon

Development

Successfully merging this pull request may close these issues.

NullPointerException thrown by instrumented metrics code in unit tests.

2 participants