You can mock your tests by using
- mock providers - in this scenario you do not call the providers and do not require credentials to be configured. This is the fastest because it doesn't make a actual call to the providers.
- override block - mocking out certain resources, data and modules. This allow us to specifically mock out certain or all resources/data or module.
An example can be shown here. As your can see here, we mock out azurerm. If you run terraform init and terraform test, you will noticed test run much faster.
mock_provider "azurerm" {}
run "resource-group-name-created-correctly" {
variables {
prefix = "test"
}
command = plan
assert {
condition = azurerm_resource_group.example.name == "myrg"
error_message = "Resource group created is not expected"
}
}
run "storage-account-prefix-created-correctly" {
variables {
prefix = "dev"
}
command = plan
assert {
condition = azurerm_storage_account.example.name == "mytestdev"
error_message = "storage account created is not expected"
}
}
In the example, below we use overrides block which looks something like this.
Please note with override block you need to setup credentials such as ARM_TENANT_ID and other details before you can run it.
override_resource {
target = azurerm_resource_group.example
}
override_resource {
target = azurerm_storage_account.example
}
run "resource-group-name-created-correctly" {
variables {
prefix = "test"
}
command = plan
assert {
condition = azurerm_resource_group.example.name == "myrg"
error_message = "Resource group created is not expected"
}
}
run "storage-account-prefix-created-correctly" {
variables {
prefix = "dev"
}
command = plan
assert {
condition = azurerm_storage_account.example.name == "mytestdev"
error_message = "storage account created is not expected"
}
}
Here we mock out calls to azurerm_storage_account.example.
Full source code can be found here.
https://github.com/mitzenjeremywoo/tf-test-mock
Comments