Unit Testing

Unit testing in Terraform involves testing individual modules or resources in isolation to ensure they work as expected. This guide covers modern unit testing approaches for Terraform as of 2025.

Test Framework Options

1. Terratest

Terratest is the most popular testing framework for Terraform. Here's a basic example:

package test

import (
    "testing"
    "github.com/gruntwork-io/terratest/modules/terraform"
    "github.com/stretchr/testify/assert"
)

func TestTerraformModule(t *testing.T) {
    terraformOptions := &terraform.Options{
        TerraformDir: "../examples/complete",
        Vars: map[string]interface{}{
            "environment": "test",
            "region":     "us-west-2",
        },
    }

    // Clean up resources after the test
    defer terraform.Destroy(t, terraformOptions)
    
    // Deploy the infrastructure
    terraform.InitAndApply(t, terraformOptions)
    
    // Validate the outputs
    output := terraform.Output(t, terraformOptions, "instance_id")
    assert.NotEmpty(t, output)
}

2. Built-in Testing Framework

As of Terraform 1.6+, there's a built-in testing framework:

Best Practices

1. Test Structure

Organize your tests following this structure:

2. Test Cases to Include

  • Input validation

  • Resource creation

  • Output verification

  • Error handling

  • Edge cases

  • Security configurations

3. Mocking Strategies

4. Automated Validation

Set up pre-commit hooks for automated testing:

Integration with CI/CD

GitHub Actions Example

Common Testing Patterns

1. Resource Configuration Testing

2. Security Configuration Testing

Troubleshooting

Common Issues and Solutions

  1. Test Cleanup Failures

  2. Parallel Test Conflicts

  3. Provider Authentication

Last updated