Testing a Terraform module against real infrastructure can be slow and costly. A mock replaces a real provider with a fake one that returns computed values without creating infrastructure. This makes mocks useful for checking module logic and brings Terraform tests closer to unit tests. Integration tests instead exercise real systems. section 9.4.3 section 9.1.4
Mock values have the expected types, but their default contents may not resemble real infrastructure: numbers default to 0, booleans to false, and collections to empty values. Set the values your assertion depends on rather than assuming the defaults are realistic. section 9.4.3
Listing 9.24 Mock resources and data sources
mock_provider "aws" {
mock_data "aws_region" { #1
defaults = {
name = "us-east-1"
}
}
}
run "dns_record_name" {
command = plan #2
variables {
zone_id = "Z1234567890"
records = ["127.0.0.1"]
domain = "example.com"
name = "my_test"
}
assert {
condition = aws_route53_record.main.name ==
"my_test.us-east-1.example.com" #3
error_message = "Domain name not properly generated from region."
}
}
#1 Here we provide mock data for all of the tests in this file.
#2 Since we are testing what a parameter is going to be set to we can run a plan instead of an apply.
#3 Now our domain will be generated with the region we set in our mock.
A mock AWS region returns `us-east-1`; a plan-only test then asserts that a DNS record name incorporates that region. section 9.4.3
Use `mock_provider` to select the provider to replace. Within it, `mock_resource` and `mock_data` set defaults for a resource or data-source type across the test. For a single target, use an override such as `override_data`. Reusable defaults can live in `tfmock.hcl` files; `source` points to a directory, not an individual file. section 9.4.3
Listing 9.27 Overrides and scope
mock_provider "aws" {}
run "dns_record_name" {
command = plan
override_data { #1
target = data.aws_region.current #2
values = {
name = "us-east-1"
}
}
variables {
zone_id = "Z1234567890"
records = ["127.0.0.1"]
domain = "example.com"
name = "my_test"
}
assert {
condition = aws_route53_record.main.name ==
"my_test.us-east-1.example.com" #3
error_message = "Domain name not properly generated from region."
}
}
#1 Rather than changing the default for every data source we can target a specific one.
#2 This is the path to the exact resource we want to override.
#3 Now our domain uses our region.
A run-scoped `override_data` targets one region data source, leaving other mocked data sources unaffected. section 9.4.3
Mocks save the time and expense of provisioning infrastructure, but they do not establish that a module works with real services. Use them for logic checks, and retain integration testing where interaction with real systems matters. Terraform introduced mocks in v1.7; they were still considered beta at the time described. section 9.4.3 section 9.1.4




















