I've been looking around for aws-sam-local unit testing strategies and haven't found much. Just looking for suggestions?
-
2This is a good question with not much info available: the aws-sam-cli framework provides a testing folder with a 'test_handler.py' file but I can't find much about how to invoke it or write appropriate unit tests within the framework.This article "https://dev.to/johndemian/how-to-test-serverless-applications-59g2" suggests its no longer necessary and that integration tests are the main source of bugs, but think this is a bit presumptuous - please post if if you find any guidance? – user3062260 Jul 08 '19 at 14:09
2 Answers
To run the 'test_handler.py' in the 'tests' directory you can do the following. You probably don't need all the steps. Do this in the directory where you would do the 'sam build' command.
$ python3 -m venv venv
$ source venv/bin/activate
(venv) $ pip3 install pytest
(venv) $ pip3 install pytest-mock
(venv) $ python3 -m pytest tests/ -v

- 440
- 4
- 13
-
This works very well with an IDE that has good unit testing embedded (e.g. Pycharm or VS Code with pytest) and the AWS Toolkit installed. May add as answer if I have the time. – Marakai Feb 26 '20 at 07:35
-
Aye, VS Code is excellent for this. Back to the question, I've written an answer for another question which describes using LocalStack for testing. However, for me, this meant converting from SAM to Serverless. See https://stackoverflow.com/questions/60077552/how-to-deploy-sam-stack-with-localstack/60290582#60290582 – LazyBrush Feb 26 '20 at 20:51
I generally just recommend unit testing your code how you always would in any project regardless of language. Ex: JUnit for java,
Unique to sam for testing sometimes I maintain several payloads test-case-1.json, test-case-2.json
and you can run
sam local invoke -e test-case-1.json
and validate you got proper outputs either manually or programmatically for more e2e functional testing of your function.
Or if its an API Ill start up the container during build and run some integration tests. Id also recommend running integration tests after actually deploying in to your account in a staging env/alias since that will be most realistic.

- 1,356
- 1
- 14
- 22