AWS Developer Guide: Writing and Running Test Code
Write and run test code by using AWS services and tools
AWS Developer Guide: Writing and Running Test Code
Testing in the AWS ecosystem requires a shift from traditional local testing to a hybrid approach involving local emulation, cloud-based integration testing, and automated validation within CI/CD pipelines. This guide focuses on the tools and strategies required for the AWS Certified Developer - Associate (DVA-C02) exam.
Learning Objectives
After studying this guide, you should be able to:
- Configure and execute unit tests using the AWS Serverless Application Model (SAM) CLI.
- Design JSON test events for AWS Lambda and API Gateway.
- Implement automated testing phases within an AWS CodeBuild
buildspec.ymlfile. - Perform integration testing using Amazon API Gateway stages and mock integrations.
- Utilize Amazon Q Developer to generate automated test cases efficiently.
Key Terms & Glossary
- AWS SAM (Serverless Application Model): An open-source framework for building serverless applications. It provides a CLI to local-invoke and test functions.
- buildspec.yml: A collection of build commands and settings in YAML format that AWS CodeBuild uses to run a build and its associated tests.
- Mock Integration: An API Gateway feature that allows developers to return a response directly from the API without calling a backend service, useful for testing frontend components.
- Lambda Alias: A pointer to a specific Lambda function version, often used to differentiate between
DEV,TEST, andPRODenvironments. - Integration Testing: Testing the communication between multiple AWS services (e.g., Lambda to DynamoDB) to ensure they work together as expected.
The "Big Idea"
In an AWS environment, Testing is not a single event—it is a continuous layer. Effective testing moves from Local (using SAM to simulate Lambda) to Automated Build (using CodeBuild to run suites) to Staging (using API Gateway stages to verify deployments). The goal is to catch configuration errors and integration failures before they reach the production environment.
Formula / Concept Box
| Testing Level | Primary Tool | Key Artifact | Validation Focus |
|---|---|---|---|
| Unit Testing | AWS SAM / PyTest / Jest | sam local invoke | Business logic in isolation |
| Automated Build | AWS CodeBuild | buildspec.yml | Code quality & package integrity |
| Integration | API Gateway / Lambda | JSON Test Events | Permissions (IAM) & Data Flow |
| Environment | AWS AppConfig / Aliases | Lambda Aliases | Configuration & Performance |
Hierarchical Outline
- Local Development & Unit Testing
- AWS SAM CLI: Using
sam local start-apiandsam local invoketo simulate the cloud environment locally. - Amazon Q Developer: Generating unit test boilerplate and edge-case scenarios using AI-assisted coding.
- AWS SAM CLI: Using
- Lambda Test Events
- JSON Payloads: Creating specific structures that mimic AWS service triggers (e.g., S3 Put, SQS message).
- Shareable Test Events: Using the Lambda console to save and share events with team members.
- Continuous Integration (CI) Testing
- AWS CodeBuild: Executing tests in a managed environment.
- Buildspec Structure: Defining
pre_buildandbuildphases to run linters and test suites.
- API Testing & Stages
- API Gateway Stages: Using stages (e.g.,
/v1,/beta) to isolate test traffic. - Stage Variables: Passing dynamic values to Lambda functions to toggle between test and production databases.
- API Gateway Stages: Using stages (e.g.,
Visual Anchors
Automated Test Workflow
Lambda Testing Architecture
\begin{tikzpicture}[node distance=2cm, every node/.style={rectangle, draw, rounded corners, minimum width=3cm, minimum height=1cm, align=center}] \node (event) [fill=blue!10] {\textbf{Test Event}$JSON Payload)}; \node (lambda) [right=of event, fill=orange!10] {\textbf{AWS Lambda}$Logic/Handler)}; \node (mock) [below=of lambda, fill=gray!10] {\textbf{Mocks/Stubs}$External APIs)}; \node (output) [right=of lambda, fill=green!10] {\textbf{Test Result}$Success/Fail)};
\draw[->, thick] (event) -- (lambda);
\draw[->, thick] (lambda) -- (output);
\draw[<->, dashed] (lambda) -- (mock);
\node[draw=none, below=0.5cm of event] {\small Input Simulation};
\node[draw=none, below=0.5cm of output] {\small Response Validation};\end{tikzpicture}
Definition-Example Pairs
- Test Event Payload: A JSON object representing the data a service sends to Lambda.
- Example: An S3 Event payload containing the bucket name and file key so a Lambda can test its image-processing logic without an actual upload.
- Environment Variable Injection: Providing configuration to code at runtime rather than hardcoding values.
- Example: Using a variable
TABLE_NAMEthat points toMovies_Testduring CodeBuild testing andMovies_Prodduring final deployment.
- Example: Using a variable
- Canary Testing: A deployment strategy where a small percentage of traffic is shifted to a new version to test its stability.
- Example: Routing 10% of users to a new API Gateway stage to monitor for 5XX errors before a full rollout.
Worked Examples
Example 1: AWS CodeBuild buildspec.yml with Testing
To automate tests during the build process, you must define the install and build phases.
version: 0.2
phases:
install:
runtime-versions:
python: 3.9
commands:
- pip install -r requirements.txt
- pip install pytest
pre_build:
commands:
- echo Running unit tests...
- pytest tests/unit_tests.py
build:
commands:
- echo Build started on `date`
- sam package --output-template-file packaged.yaml
artifacts:
files:
- packaged.yamlExample 2: Invoking Lambda Locally with SAM
If you have a file named event.json, you can test your Lambda locally without deploying to AWS:
# Invokes the function 'MyLambdaFunction' using the local JSON event
sam local invoke MyLambdaFunction -e event.jsonCheckpoint Questions
- Which file is used to provide AWS CodeBuild with instructions on how to run tests and compile code?
- What is the benefit of using API Gateway Stage Variables for integration testing?
- How does AWS SAM assist in the "Inner Loop" of development (the phase before code is committed)?
- True or False: Amazon Q Developer can be used to generate automated tests based on existing code context.
▶Click to view answers
- buildspec.yml (typically located at the root of the source directory).
- They allow you to dynamically change backend endpoints or database names without modifying the application code.
- It allows developers to test Lambda functions and APIs locally on their machine, reducing the feedback loop and cloud costs.
- True. It assists in generating test code and identifying edge cases.