DEV Community

Roger Murariu
Roger Murariu

Posted on • Updated on

Unit testing your AWS infrastructure

Everyone loves infrastructure as code because it gives you consistency across environments as no manual steps will be forgotten and it makes it easier to handle infrastructure. Writing software defined infrastructure inside AWS started with CloudFormation which is a low level interaction (YAML/JSON templates).

AWS CDK offers a higher level of abstraction, by compiling your code into CloudFormation YAML templates, which are then used to provision AWS resources. The fact that AWS CDK offers you the ability to write IaC in our own language of choice (JavaScript, TypeScript, Python, Java, C# and Go), makes it very attractive as you can use programming idioms and your infrastructure output can be used as input for your runtime code.

Since you can write infrastructure as code, let's see how you can write unit tests. We will be creating the following AWS resources using CDK and will write unit tests for them using C#.
Image description

AWS Infrastructure

  1. IAM Role which has permissions to create and write logs into CloudWatch and has custom DynamoDB API permissions for a particular table and all its indexes.

  2. Api Gateway - Rest API which will proxy all GET/PUT/POST/DELETE requests to a Lambda function.

  3. In our construct we define an IAM Role for the lambda, an API Gateway (both described above) and a Lambda.

Writing unit tests

Once we have our construct, writing unit tests is fairly easy. You can use CDK assertions for fine grained assertions👇.

I think AWS CDK is a great framework because it brings the infrastructure inside your IDE alongside with your runtime code, makes your environments consistent and easier to manage and you can create reusable bits of infrastructure. Having infrastructure unit tests setup in your CI pipeline is a best practice that you should follow and will make you more confident to go to prod on Fridays😱.

HAPPY CODING!💻🚀☁️

Top comments (0)