Mock API calls in Plugin tests

Hi
We want to be able to mock calls to external APIs when running tests for the plugin. Currently we have acceptance testing but since it can be costly we would like to be able to mock certain API calls. I have not been able to find a way to do this and I understand that on the scaffolding framework repo it says:

Note: Acceptance tests create real resources, and often cost money to run.

Could you please advise on how this can be achieved? Or in case you are aware of other plugins that are able to mock API calls successfully for testing?

Hi @maastha :wave:

If you’re able to configure the URL that is being called by the provider, then one option would be to use a pattern similar to the http provider which uses the httptest package and calls NewServer() to start a new test http server. The acceptance tests then use the URL of the test server in the terraform configuration.

If you’re able to set the URL of the external API that is being called during your acceptance tests then you could take a similar approach.

Certain providers, such as the hashicorp/google provider, have gone the route of implementing HTTP mocking for acceptance testing via tools such as go-vcr. A potential terraform-plugin-framework based provider implementation pattern that can help here is to introduce a “testing” provider.Provider implementation that wraps the “production” provider.Provider by implementing any necessary testing/mocking logic during Configure in addition to calling the “production” Configure logic. The acceptance tests can be pointed at a provider server using the “testing” provider code instead of the “production” provider code.

It is important to note though that it is a fairly non-trivial process to setup (code example / testing provider server example, let alone all the necessary CI components for updating mocks) and does introduce additional differences between reality and the provider implementation. API responses need to constantly be kept up-to-date and you can miss out on latent API behaviors such as error handling and rate limiting scenarios that practitioners might encounter, especially across multiple resources.