Course contentsShow
← Cloud and Infrastructure
Lesson 2879 of 2,98963. Infrastructure TestingFree lesson

Unit Testing IaC with Terratest

Writing Go-based unit tests for Terraform modules using Terratest to verify resource creation and configuration.

Unit Testing IaC with Terratest

What you'll learn: How to write Go-based unit tests that validate your Terraform modules actually create and configure resources correctly before deploying to production.

Why Unit Test Infrastructure?

You've already validated syntax with terraform validate and caught style issues with linting. But how do you know your module actually works—that it creates the right resources with the correct settings? Unit testing infrastructure code deploys your Terraform to a real (but temporary) environment, verifies the results, then tears everything down.

What is Terratest?

Terratest is a Go library specifically designed for testing infrastructure code. Think of it as your infrastructure's quality assurance robot: it deploys your Terraform, pokes and prods the created resources to verify they match expectations, then cleans up after itself.

How It Works

  1. Deploy: Terratest runs terraform apply with your module
  2. Validate: Your Go test code checks actual resource properties (security group rules, EC2 instance types, S3 bucket policies)
  3. Destroy: Terratest runs terraform destroy to clean up

Since Terratest uses Go's built-in testing framework, you write tests as standard Go functions. Each test typically provisions real infrastructure in a sandbox account, validates specific behaviors, then destroys everything.

The Value Proposition

Unlike static checks that only examine code structure, Terratest validates runtime behavior. It catches issues like incorrect AMI IDs, misconfigured security groups, or broken references between resources—problems that only surface during actual deployment.

Key Takeaway: Terratest provides automated unit testing for Terraform modules by deploying to real cloud environments, validating resource configuration, and automatically cleaning up—catching deployment issues before they reach production.