Pro ยท Lesson 9 of 12

Testing and validation

validate checks the configuration. A test file checks behavior you describe. Neither replaces reading a plan against production state.

Sign in to save your place.

Picture it this way

validate asks whether the sentence is grammatical. A test asks whether the recipe does what you claimed, sometimes with a pretend shop so you do not buy real vegetables.

Four different checks

terraform fmt is style. terraform validate is references and types. A variable validation block rejects a bad input. A precondition or postcondition rejects a plan when a rule fails. A check block records a failure without always stopping the apply the way a postcondition does. Read the current language page before you pick one. The stopping behavior is the point.

terraform test runs files ending in tftest.hcl. Assertions name a condition. A test that needs a real cloud account is an integration test. Treat it like one: separate state, fake names, and a bill you meant to pay.

Mocks are version-specific

Terraform can mock providers so a test does not create cloud resources. The mock syntax has changed as the test framework grew. Copy a mock from a page that matches your terraform version. An old snippet that fails validate is a version mismatch, not a reason to skip tests.

OpenTofu's test command is its own documentation. A green terraform test does not certify tofu test, and the reverse is the same.

Check Fails when
validate The configuration does not make sense
validation An input breaks your condition
terraform test An assertion you wrote is false
plan review The diff is not what you wanted, even if tests passed

What each check sees

  1. validate
  2. test
  3. plan

Step 1 of 3validate never talks to your production account.

Lab: one assertion against the name module

Save this next to the module lab if you still have it. Run terraform test. If the command is unknown, your binary is older than the test framework. Say so in your notes instead of inventing a pass.

# name.tftest.hcl
run "dev_prefix" {
  command = plan
  variables {
    environment = "dev"
  }
  assert {
    condition     = output.name_prefix == "dfd-dev"
    error_message = "Expected the dev prefix."
  }
}

Concept summary

Knowledge check

terraform validate passed. Can you skip the plan?

A test snippet from a blog fails on your binary. What is a likely reason?

What is the sensitive flag not a substitute for?

Official sources

Checked against the linked documentation in October 2026. A later release can move a flag, a price, or a supported pair. Use the page for the version you installed.