Combining Unit Tests with Mocks and Integration Tests in the Cloud
This lesson explains how unit tests replace AWS services with mocks while integration tests run against real resources, and why a healthy test suite needs both.
Learning outcomes
After completing this lesson, you will be able to:
- Describe the levels of the testing pyramid and what each level tests.
- Explain how mocking libraries and stubs remove the dependency on real AWS services in unit tests.
- Explain why integration tests for serverless applications usually run in the cloud.
The testing pyramid
The testing pyramid describes how to divide testing effort between three levels. At the base are many unit tests, which test individual functions with AWS calls replaced by mocks. They run in milliseconds, need no AWS account and pinpoint the failing code, so they run on every change.
In the middle are fewer integration tests, which run the code against real AWS services in a test environment. They catch problems that mocks hide, such as a missing IAM permission, a wrong table name or an event in an unexpected format, but they are slower and need deployed resources. At the top are a small number of end-to-end tests, which exercise the whole deployed application through its public interface, such as placing an order through the API and checking that a confirmation is sent. They give the most confidence but are the slowest and hardest to diagnose when they fail. The following table summarises the three levels.
| Level | How many | Runs against |
|---|---|---|
| Unit tests | Many, fast | Mocks or emulators |
| Integration tests | Fewer | Real services in a test environment |
| End-to-end tests | A small number | The whole deployed application |
Keep handlers thin and move business logic into functions that can be tested in isolation.
Mocking AWS services
Unit tests should not depend on real AWS services, because calls to them are slow, cost money, need credentials and can fail for reasons unrelated to the code under test. Two approaches remove the dependency.
Mocking libraries intercept SDK calls inside the test process. In Python, moto provides in-memory implementations of many AWS services, so the code creates a table, writes an item and reads it back as if the service were real, while botocore.stub.Stubber returns exact responses that the test specifies, including error responses for testing failure handling. In JavaScript, the AWS SDK client mock library plays the same role for SDK v3 clients.
Emulators run a local version of a service that the code calls over the network. DynamoDB Local is a downloadable version of DynamoDB, and LocalStack, a third-party tool, emulates many services. Emulators suit tests that need realistic behaviour across several calls, but they can differ from the real services in details. The following table summarises the tools.
| Tool | Use |
|---|---|
moto, botocore.stub.Stubber | Mock AWS calls in Python |
| AWS SDK client mock library | Mock AWS calls in JavaScript |
| DynamoDB Local, LocalStack | Emulate AWS services locally |
Example. moto intercepts boto3 calls, so the test runs the real handler against an in-memory table, with no account and no cost.
import boto3
from moto import mock_aws
@mock_aws
def test_create_order_saves_item(monkeypatch):
monkeypatch.setenv("TABLE_NAME", "Orders")
ddb = boto3.resource("dynamodb", region_name="eu-west-1")
ddb.create_table(
TableName="Orders",
KeySchema=[{"AttributeName": "pk", "KeyType": "HASH"}],
AttributeDefinitions=[{"AttributeName": "pk", "AttributeType": "S"}],
BillingMode="PAY_PER_REQUEST",
)
from app import handler
handler({"orderId": "9017"}, None)
assert ddb.Table("Orders").get_item(Key={"pk": "9017"})["Item"]["status"] == "NEW"Integration testing in the cloud
Emulators cannot reproduce IAM, quotas and service behaviour exactly, so serverless teams often test in the cloud. Integration tests deploy the stack to a test environment or account and exercise it end to end, catching problems mocks miss, such as missing IAM permissions or a misconfigured trigger.
- Ephemeral environments: CI deploys a temporary stack for each branch or pull request, runs the tests and deletes it.
- API Gateway mock integrations return fixed responses, so front-end work and contract tests can proceed before the backend exists.
Where each test belongs
Each test should be placed at the level of the testing pyramid that suits it. The following table classifies several tests and indicates whether each involves real AWS services.
| Test | Kind | AWS involved? |
|---|---|---|
| Order total calculation applies discounts correctly | Unit test | No |
| Handler writes the right item to DynamoDB | Unit test with a mock (moto or Stubber) | No: mocked |
| Deployed function, API and table work together | Integration test against a test stack | Yes |
| The checkout journey works in a browser | End-to-end test | Yes |
Mocks make unit tests fast and free but can hide real problems, such as a missing IAM permission or a wrong table name in configuration. The integration test against a short-lived stack, created by the pipeline and deleted afterwards, is what catches those.
Which problems do integration tests in the cloud find that unit tests with mocked AWS calls cannot?
Show answer
Problems in the real environment, such as missing IAM permissions, wrong resource names, misconfigured triggers and event formats that differ from the mock.
Exam Tips
Remember for the exam
- To run DynamoDB locally for tests, use DynamoDB Local.
- An API that returns a fixed response with no backend uses an API Gateway mock integration.
- To catch IAM and trigger misconfiguration, run integration tests in a real test environment.
- For per-branch test environments, deploy and tear down ephemeral stacks in CI.