Testing Serverless and Event-Driven Applications
Overview
Testing cloud applications is harder than testing a single process: logic is spread across Lambda functions, queues, streams and managed services. A good strategy mixes unit tests that run in milliseconds, local emulation with the SAM CLI, and integration tests against real AWS resources in a dev environment.
The testing pyramid applies. Many small unit tests check pure logic; fewer integration tests verify wiring and permissions; a handful of end-to-end tests walk a whole user journey. Think of building a car: you test each bolt, then each assembled subsystem, then take the finished car around the track.
DVA-C02 covers test events (JSON payloads), SAM local invocation, mock API integrations, dev stages, and how to test event-driven flows where results arrive asynchronously.
Key Concepts
- Unit tests isolate handler logic by injecting fakes or mocking AWS clients (moto, botocore Stubber, Jest mocks,
aws-sdk-client-mock). - Test events are saved JSON payloads that mimic real triggers (API Gateway, SQS, S3, DynamoDB Streams) and can be shared in the Lambda console or committed in the repo.
sam local invokeruns a function in a Docker container locally;sam local start-apihosts API routes;sam local start-lambdaexposes a local Lambda endpoint.sam remote invokeandsam logstest deployed functions in the cloud, including--tailfor streaming logs;sam syncspeeds up dev iteration.- Integration tests deploy a real stack (often with a unique name per developer or per pull request) and call real endpoints.
- Mock integrations in API Gateway and tools like LocalStack or DynamoDB Local let teams develop before backends exist.
- Event-driven tests publish an event and poll for the outcome (a record in a table, a message in a queue) with timeouts instead of fixed sleeps.
- Use separate dev, test and prod stages or accounts so tests never touch production data.
Detailed Notes
Test layers
| Layer | Speed | What it proves | Tools |
|---|---|---|---|
| Unit | Milliseconds | Business logic, parsing, branching | pytest, Jest, moto, client mocks |
| Local emulation | Seconds | Handler runs in Lambda runtime image, event shape | sam local invoke |
| Integration | Minutes | IAM permissions, wiring, real service behaviour | Dev stack, sam remote invoke |
| End-to-end | Minutes | Entire user journey | Synthetic scripts, CloudWatch Synthetics |
Keep logic in plain functions separate from the handler so most code is testable without AWS.
Unit testing with mocks
import boto3, json
from moto import mock_aws
import app
@mock_aws
def test_put_order_is_idempotent():
ddb = boto3.resource("dynamodb", region_name="eu-west-1")
ddb.create_table(TableName="orders", BillingMode="PAY_PER_REQUEST",
KeySchema=[{"AttributeName": "pk", "KeyType": "HASH"}],
AttributeDefinitions=[{"AttributeName": "pk", "AttributeType": "S"}])
event = {"body": json.dumps({"orderId": "o1"})}
assert app.handler(event, None)["statusCode"] == 201
assert app.handler(event, None)["statusCode"] == 200 # duplicate ignored
For Node.js, aws-sdk-client-mock replaces SDK v3 commands: mockClient(DynamoDBDocumentClient).on(PutCommand).resolves({}).
Test events
Store events under events/ and run them locally. Generate realistic samples with sam local generate-event.
sam local generate-event sqs receive-message --body '{"orderId":"o1"}' > events/sqs.json
sam build
sam local invoke OrderFn --event events/sqs.json --env-vars env.json
sam local start-api --port 3000 &
curl http://127.0.0.1:3000/orders/o1
env.json provides environment variables such as a table name, or points the function at DynamoDB Local or LocalStack through an endpoint URL. Local emulation does not enforce real IAM, quotas or network paths, so it cannot replace cloud tests.
Testing deployed resources
sam deploy --stack-name orders-dev-alice --parameter-overrides Env=dev --no-confirm-changeset
sam remote invoke OrderFn --stack-name orders-dev-alice --event-file events/sqs.json
sam logs --stack-name orders-dev-alice --name OrderFn --tail
sam sync --stack-name orders-dev-alice --watch # fast code sync while developing
Per-developer or per-pull-request stacks isolate tests. Delete them afterwards with sam delete. Run integration tests in a CodeBuild stage of the pipeline against a test stage, then promote the same artifact.
Testing event-driven flows
Asynchronous outcomes need polling with a deadline:
import time, boto3
def wait_for_item(table, key, timeout=30):
end = time.time() + timeout
while time.time() < end:
item = table.get_item(Key=key).get("Item")
if item:
return item
time.sleep(1)
raise AssertionError("event was not processed in time")
def test_order_event_creates_invoice():
events.put_events(Entries=[{"Source": "test.orders", "DetailType": "OrderPlaced",
"Detail": json.dumps({"orderId": "o9"}), "EventBusName": BUS}])
assert wait_for_item(invoices, {"pk": "o9"})["status"] == "CREATED"
Test failure paths too: send a poison message and assert it reaches the DLQ, and throttle a dependency to confirm retries and backoff.
API testing and mocks
API Gateway mock integrations return a static response defined in the integration (status 200 and a mapping template) and let front-end teams build against the contract. Import an OpenAPI definition, use the console Test button or aws apigateway test-invoke-method, and run contract tests that compare responses to the schema. Deploy a dev stage with its own stage variables and a lower throttle.
aws apigateway test-invoke-method --rest-api-id a1b2c3 --resource-id r1s2t3 \
--http-method GET --path-with-query-string "/orders/o1"
Generating tests with Amazon Q Developer
Use Amazon Q Developer to draft unit tests and edge cases from existing handlers, then review, run and refine them. Treat generated tests as a starting point; verify they assert behaviour, not implementation details.
Pipelines
A typical pipeline: unit tests in CodeBuild on every commit, deploy to a test environment, run integration tests, then promote the same artifact with an approval before production. Fail the build on test failure and publish reports in the CodeBuild reports section.
Real World Example
A payments team had Lambda tests that only ran in production-like environments and took 20 minutes. They extracted business logic into pure functions covered by pytest with moto, kept a folder of test events generated by sam local generate-event, and created a per-pull-request stack for integration tests that publish an EventBridge event and poll DynamoDB. Feedback dropped to three minutes, and a DLQ test caught a missing IAM permission before release.
Architecture Diagram
Fast local tests first, then real cloud integration tests.
- 1A commit triggers unit tests with mocked AWS services.
- 2SAM local invokes handlers with saved test events.
- 3The pipeline deploys a disposable test stack.
- 4Integration tests publish events and poll for outcomes before promoting.
Best Practices
- ✓Keep business logic out of handlers so most tests need no AWS.
- ✓Commit test events and reuse them locally, in CI and in the console.
- ✓Run integration tests in isolated stacks or accounts and clean them up.
- ✓Poll with timeouts for asynchronous results; avoid fixed sleeps.
- ✓Test failure paths: DLQs, retries, throttling and malformed events.
Common Interview Questions
Exam Tips
DVA-C02 focus
- Saved JSON payloads that mimic triggers are test events.
- Local Lambda tests use sam local invoke; cloud tests use sam remote invoke and sam logs.
- A backend-free API response for front-end development means a mock integration.
- Local emulation does not validate IAM or quotas; deploy to a dev stage for that.
Finished this lesson?
0 of 46 lessons done · 0% of the course

