1.2.4 Write and Run Test Code

Write and Run Test Code for Lambda

Testing Approaches

ApproachToolMô tả
Local invokesam local invokeChạy Lambda locally với Docker
Local APIsam local start-apiLocal API Gateway endpoint
Unit testpytest, JestMock AWS services
Integration testSAM + real AWSTest với services thật
Console testAWS ConsoleTest event trực tiếp trên console

SAM Local Testing

# Invoke với sample event
sam local invoke MyFunction -e events/s3-put.json

# Generate sample events
sam local generate-event s3 put --bucket my-bucket --key test.json

# Start local API
sam local start-api --port 3000

Unit Testing với Mocking

# test_handler.py
import json
from unittest.mock import patch, MagicMock

def test_handler_success():
    with patch('handler.boto3') as mock_boto3:
        mock_table = MagicMock()
        mock_boto3.resource.return_value.Table.return_value = mock_table
        mock_table.get_item.return_value = {
            'Item': {'id': '123', 'name': 'test'}
        }

        from handler import lambda_handler
        event = {'pathParameters': {'id': '123'}}
        result = lambda_handler(event, None)

        assert result['statusCode'] == 200
        body = json.loads(result['body'])
        assert body['name'] == 'test'

Lambda Test Event trên Console

  • Tạo test events từ templates (API Gateway, S3, SQS, etc.)
  • Shareable test events trong cùng account
  • Xem execution results, logs, duration, memory used

Exam Tip: sam local invoke cho quick local testing. sam local start-api cho API testing liên tục. Unit tests nên mock AWS services để chạy nhanh và không tốn cost.