1.1.7 Write and Run Unit Tests

Unit Tests in Development Environments

AWS SAM Local Testing

SAM CLI cho phép test Lambda functions locally trước khi deploy.

CommandMô tả
sam local invokeInvoke Lambda function locally
sam local start-apiStart local API Gateway endpoint
sam local start-lambdaStart local Lambda endpoint
sam local generate-eventGenerate sample event payloads
# Invoke function với event file
sam local invoke MyFunction -e event.json

# Start local API Gateway
sam local start-api

# Generate S3 event
sam local generate-event s3 put --bucket my-bucket --key my-key

Testing Strategies

LevelMô tảTools
Unit TestTest individual functions/methodspytest, Jest, JUnit
Integration TestTest với AWS services thậtSAM local, LocalStack
End-to-End TestTest toàn bộ flowAWS CDK integ-tests

Mocking AWS Services

# Python — sử dụng moto library
import boto3
from moto import mock_aws

@mock_aws
def test_dynamodb_put():
    client = boto3.client("dynamodb", region_name="us-east-1")
    client.create_table(
        TableName="test-table",
        KeySchema=[{"AttributeName": "id", "KeyType": "HASH"}],
        AttributeDefinitions=[{"AttributeName": "id", "AttributeType": "S"}],
        BillingMode="PAY_PER_REQUEST"
    )
    client.put_item(
        TableName="test-table",
        Item={"id": {"S": "123"}, "name": {"S": "test"}}
    )
    response = client.get_item(
        TableName="test-table",
        Key={"id": {"S": "123"}}
    )
    assert response["Item"]["name"]["S"] == "test"

Environment Variables cho Testing

# template.yaml — SAM template
Globals:
  Function:
    Environment:
      Variables:
        TABLE_NAME: !Ref MyTable
        STAGE: !Ref Stage
  • Dùng env.json file cho local testing với sam local invoke --env-vars env.json
  • Tách biệt config giữa test/staging/production

Exam Tip: SAM CLI là tool chính để test Lambda locally. sam local invoke cho single invocation, sam local start-api cho API testing liên tục.