Course contentsShow
← Docker, Kubernetes & CI/CD
Lesson 480 of 8027. Package Management and AutomationFree lesson

Testing Operators with Envtest and Integration Suites

You will write integration tests using the Envtest library to verify that your operator correctly manages resources in a simulated cluster environment.

In this lesson, you will learn how to use envtest to run high-fidelity integration tests that verify your operator's reconciliation logic without needing a full-blown Kubernetes cluster.

Why Envtest?

When writing operators, unit testing only checks the logic of your functions. However, operators rely heavily on the Kubernetes API server to watch resources and trigger reconciliations. envtest provides a real, lightweight API server and etcd instance that runs locally during your test suite. It allows you to create Custom Resources (CRs) and observe how your controller reacts, ensuring your business logic correctly creates, updates, or deletes managed resources.

Setting Up the Test Environment

To use envtest, you typically initialize the test environment in a suite_test.go file within your project. This spins up the API server before your tests execute:

var testEnv *envtest.Environment

func TestMain(m *testing.M) {
    testEnv = &envtest.Environment{
        CRDDirectoryPaths: []string{filepath.Join("config", "crd", "bases")},
    }

    cfg, err := testEnv.Start()
    // Handle error...

    code := m.Run()

    testEnv.Stop()
    os.Exit(code)
}

Running Integration Tests

Once the environment is running, your test suite can use a client.Client to interact with the API server. You define a test where you create a custom resource, invoke your Reconciler.Reconcile method, and then assert that the expected side effects occurred (such as the creation of a Deployment or Service).

Because envtest uses a real API server, it respects the schema defined by your CRDs. If your operator is supposed to create a ConfigMap when a CR is applied, your test simply applies the CR and then uses the client to Get the ConfigMap. If the ConfigMap exists and has the expected values, your reconciliation logic is verified as functional.

This approach is significantly faster than spinning up a Minikube or Kind cluster, making it ideal for inclusion in your CI pipelines to catch regressions before they reach your staging environment.

Key Takeaway: envtest allows you to validate the entire reconciliation loop against a real API server, providing a fast, reliable, and automated way to confirm your operator behaves correctly under Kubernetes-like conditions.