Testing and Deployment · Topic 3 of 6

Testing Lambda and API Code

Test serverless code for DVA-C03: SAM local commands, CDK assertions, template validation, API Gateway mock integrations, test events and AI test tools.

  • 5 min
In a nutshell
  • validate-template checks syntax only, and a change set previews real changes.
  • SAM local commands need Docker and do not test real IAM permissions.
  • A mock integration returns a configured response with no backend call.

What it is

Testing serverless code means checking three things: the function logic, the infrastructure template that creates it, and the integration between services. Each has a cheap, early check that runs before anything reaches production.

The exam asks which tool or command fits a given need, such as running a function locally, validating a template, faking a backend or sending a realistic event.

Unit testshandler logicTemplate checksIaC validationLocal runSAM CLICloud testtest events and stages

How it works

Validating infrastructure templates

ToolWhat it checks
aws cloudformation validate-templateTemplate syntax only, not whether resources will succeed
sam validateA SAM template for errors
CloudFormation change setA preview of what a stack update would create, change or replace
CDK assertionsUnit tests on the synthesized template
cdk diffDifferences between the app and the deployed stack

The CDK assertions library lets a test synthesize a stack into a template, then assert on it. A fine grained assertion checks that a resource with specific properties exists, for example a Lambda function with a given runtime. A snapshot test compares the template to a saved copy and fails when anything changes.

Running code locally with SAM

The SAM CLI runs your function in a container that imitates the Lambda environment, so it needs Docker.

  • sam local invoke runs one function once, with an event from a file.
  • sam local start-api starts a local endpoint for API Gateway routes.
  • sam local generate-event prints a sample event for a service, such as an S3 put.
  • sam sync pushes code changes to the cloud quickly for testing against real services.

Local runs are good for logic. They do not enforce your real IAM permissions the way the cloud does, so permission problems appear only after deployment.

Unit testing code that calls AWS

Unit tests should not call real AWS services. Use a mocking tool to replace the SDK client, so a test can return a canned DynamoDB response or force an error. Keep the handler thin and move business logic into plain functions that are easy to test without any event at all.

Mock APIs with API Gateway

A mock integration on a REST API returns a response without calling any backend. You configure the integration request to send a status code and map the integration response to the body and headers you want.

Use it to stand in for an external dependency that is not built yet, is paid per call or is unreliable. Front end teams can build against the mock, and test stages can use it in place of a partner system.

Test clientcallsAPI Gatewaymock integrationreturnsFixed JSON response

Creating test events

A Lambda event is JSON whose shape depends on the caller. In the console you create a test event from an event template for S3, SQS, API Gateway and other sources, then save it and replay it. The console keeps up to 10 saved test events.

From the CLI, aws lambda invoke --function-name my-fn --payload file://event.json out.json sends an event. With AWS CLI v2, inline JSON also needs --cli-binary-format raw-in-base64-out.

For an API Gateway Lambda proxy integration, the event includes httpMethod, path, headers, queryStringParameters, pathParameters and body. The body is a string, even when it holds JSON. HTTP APIs with payload format 2.0 use a different shape with rawPath and routeKey. You can also use the API Gateway Test feature to call a method directly with a sample request.

AI tools for testing

Kiro can generate unit tests from specs and agent chat, and its hooks run on events such as a file save, so a hook can run your test suite automatically. Amazon Q Developer IDE plugins offered similar test generation, but AWS will discontinue them on April 30, 2027 in favor of Kiro. In a pipeline, AWS CodeBuild collects test and code coverage reports from the test framework output.

Generated tests are a draft. You still review them for correct assertions and real coverage of edge cases.

How the exam asks about this

  • "Run the function on a laptop with a sample S3 event." -> sam local generate-event and sam local invoke.
  • "Frontend developers need the API before the backend exists." -> API Gateway mock integration.
  • "Check that the synthesized template contains a function with a 30 second timeout." -> CDK assertions test.

What to remember for the exam

  • validate-template checks syntax only, and a change set previews real changes.
  • SAM local commands need Docker and do not test real IAM permissions.
  • A mock integration returns a configured response with no backend call.
  • Proxy integration event body is a string, and the response body must also be a string.
  • Lambda console test events are saved per function, and the CLI uses invoke with a payload.
  • AI generated tests need human review, and CodeBuild reports show results and coverage.
Watch out

A function that passes locally can still fail in AWS because of its execution role, VPC settings or quotas. Always test once against the deployed stack.

Common mistakes

Trusting validate-template to prove a deployment will work. It cannot detect missing permissions, name conflicts or quota limits.

Calling real services in unit tests. Tests become slow, flaky and may change real data. Mock the SDK client.

Sending a JSON object as the body in a proxy test event. The body must be a JSON string, otherwise the code parses it incorrectly.

Check yourself

  • Which command prints a sample event for testing a function locally?

    sam local generate-event.

  • How can API Gateway answer requests without any backend?

    With a mock integration that returns a configured response.

  • What does aws cloudformation validate-template verify?

    Only the template syntax, not whether the resources can be created.

Topic 3 of 6 in Testing and Deployment

Test yourself on Testing and Deployment

The full AWS DVA-C03 question bank has 850 questions, with timed practice exams and an explanation for every answer.

This study guide is independent and is not affiliated with, endorsed by, or sponsored by AWS. Vendor names, certification names and exam codes are trademarks of their respective owners and are used for identification only.