When we run this main.go file against a running cluster, we end up creating a pod called test-pod in the default namespace.
Now, let us write a unit test for the same using the Go’s testing package. Here, inorder to create the Kubernetes Clientset, we use the NewSimpleClientSet() constructor from the fake package of client-go/kubernetes package instead of NewForConfig() constructor.
What is the difference?
NewForConfig() constructor returns the actual ClientSet that has the clients for every Kubernetes groups and operates upon an actual cluster. Whereas, NewSimpleClientSet() constructor returns clientset that will respond with the provided objects. It’s backed by a very simple object tracker that processes creates, updates and deletions as-is, without applying any validations and/or defaults.
What is important to note here is that the Clientset of the fake package also implements the Kubernetes Interface. Meant to be embedded into a struct to get a default implementation. This makes faking out just the method you want to test easier.
Now, if we run this test file using go test command, we will successfully execute the CreatePod() method even without running this against any running K8s cluster & by bypassing the Get() call by mimicing it to return the same object as sent as a parameter to it. Output will be something as shown
You can keep this article as reference and build upon this, a test framework or a unit test package for your applications employing Kubernetes client-go.