Skip to main content
Redhat Developers  Logo
  • Products

    Platforms

    • Red Hat Enterprise Linux
      Red Hat Enterprise Linux Icon
    • Red Hat AI
      Red Hat AI
    • Red Hat OpenShift
      Openshift icon
    • Red Hat Ansible Automation Platform
      Ansible icon
    • View All Red Hat Products

    Featured

    • Red Hat build of OpenJDK
    • Red Hat Developer Hub
    • Red Hat JBoss Enterprise Application Platform
    • Red Hat OpenShift Dev Spaces
    • Red Hat OpenShift Local
    • Red Hat Developer Sandbox

      Try Red Hat products and technologies without setup or configuration fees for 30 days with this shared Openshift and Kubernetes cluster.
    • Try at no cost
  • Technologies

    Featured

    • AI/ML
      AI/ML Icon
    • Linux
      Linux Icon
    • Kubernetes
      Cloud icon
    • Automation
      Automation Icon showing arrows moving in a circle around a gear
    • View All Technologies
    • Programming Languages & Frameworks

      • Java
      • Python
      • JavaScript
    • System Design & Architecture

      • Red Hat architecture and design patterns
      • Microservices
      • Event-Driven Architecture
      • Databases
    • Developer Productivity

      • Developer productivity
      • Developer Tools
      • GitOps
    • Automated Data Processing

      • AI/ML
      • Data Science
      • Apache Kafka on Kubernetes
    • Platform Engineering

      • DevOps
      • DevSecOps
      • Ansible automation for applications and services
    • Secure Development & Architectures

      • Security
      • Secure coding
  • Learn

    Featured

    • Kubernetes & Cloud Native
      Openshift icon
    • Linux
      Rhel icon
    • Automation
      Ansible cloud icon
    • AI/ML
      AI/ML Icon
    • View All Learning Resources

    E-Books

    • GitOps Cookbook
    • Podman in Action
    • Kubernetes Operators
    • The Path to GitOps
    • View All E-books

    Cheat Sheets

    • Linux Commands
    • Bash Commands
    • Git
    • systemd Commands
    • View All Cheat Sheets

    Documentation

    • Product Documentation
    • API Catalog
    • Legacy Documentation
  • Developer Sandbox

    Developer Sandbox

    • Access Red Hat’s products and technologies without setup or configuration, and start developing quicker than ever before with our new, no-cost sandbox environments.
    • Explore Developer Sandbox

    Featured Developer Sandbox activities

    • Get started with your Developer Sandbox
    • OpenShift virtualization and application modernization using the Developer Sandbox
    • Explore all Developer Sandbox activities

    Ready to start developing apps?

    • Try at no cost
  • Blog
  • Events
  • Videos

How to write tests with Fabric8 Kubernetes Client

January 24, 2023
Rohan Kumar
Related topics:
JavaKubernetes
Related products:
Red Hat Enterprise Linux

Share:

    Like regular applications, it is essential to write tests while building applications that interact with the Kubernetes API server (i.e., Kubernetes Operators). However, it is not always possible to have a Kubernetes test environment available for running tests. Also, our tests may require us to satisfy certain prerequisites (some specific Kubernetes version) in order to run successfully.

    In this blog post, we will look at testing libraries made available by Fabric8 Kubernetes Client and focus mainly on Fabric8 Kubernetes Mock Server and Fabric8 JUnit5 Extension.

    This article is the final installment in my series:

    • Part 1: How to use Fabric8 Java Client with Kubernetes
    • Part 2:  Programming Kubernetes custom resources in Java
    • Part 3: How to use Kubernetes dynamic client with Fabric8
    • Part 4: How to generate code using Fabric8 Kubernetes Client
    • Part 5: How to write tests with Fabric8 Kubernetes Client

    How to write tests using Fabric8 Kubernetes Mock Server

    Since it’s not always possible to have a Kubernetes Cluster available for testing while writing tests, most developers try to mock KubernetesClient calls using mocking frameworks like Mockito and JMockit. While this can work for most scenarios, overuse of mocking nested KubernetesClient calls can leave tests cluttered with mock calls and decrease readability.

    Fabric8 Kubernetes Client provides a Kubernetes Mock Server that provides spins up a server during testing that looks very much like a real Kubernetes API server. Based on OkHttp’s MockWebServer, it tries to emulate the Kubernetes API server’s calls for common operations such as get, list, create, watch, etc., which can be common scenarios while testing Kubernetes applications.

    In order to use Kubernetes Mock Server, you need to add the following dependency:

    <dependency>
        <groupId>io.fabric8</groupId>
        <artifactId>kubernetes-server-mock</artifactId>
        <version>${fabric8.version}</version>
        <scope>test</scope>
    </dependency>
    

    Once added as a dependency, you can start using Kubernetes Mock Server in your tests. Let’s see how we can get started with using Kubernetes Mock Server in our tests.

    If you’re using JUnit4, you can add a JUnit Rule for Kubernetes Mock Server in your test as follows:

    import io.fabric8.kubernetes.client.server.mock.KubernetesServer;
    
    public class Foo {
      @Rule
      public KubernetesServer crudServer = new KubernetesServer(true, true);
    
      // …
    }
    

    There are two configurable arguments when initializing Kubernetes Mock Server:

    1. Crud: Enable Opinionated Kubernetes mock server, where users don’t need to provide expectations for their operations (defaults to false). 
    2. Https: Use HTTPS or not (defaults to true).

    If you’re using JUnit5, you can use the following  @EnableKubernetesMockClient annotation:

    import io.fabric8.kubernetes.client.server.mock.EnableKubernetesMockClient;
    
    @EnableKubernetesMockClient
    class Foo {
       private KubernetesClient kubernetesClient;
       private KubernetesMockServer server;
    
       // ..  
    }
    

    You can use Kubernetes Mock Server in two modes:

    1. CRUD Mode: Opinionated Kubernetes Mock Server acts very similar to a real Kubernetes API Server and processes common operations such as get, create, watch, etc.
    2. Expectations Mode: The user defines expectations for Kubernetes Mock Server for API endpoints expected to hit during test execution and defines response elements.

    I will explain both modes with the help of an example.

    Consider an elementary class PodGroupService that manages a group of pods in the currently logged namespace sharing some labels. 

    Refer to my Kubernetes Client demo PodGroupService.java.

    package io.fabric8.demos.tests.mockserver;
    
    import io.fabric8.kubernetes.client.KubernetesClient;
    import java.util.Map;
    
    public class PodGroupService {
      private final KubernetesClient kubernetesClient;
      private final Map<String, String> matchLabels;
    
      public PodGroupService(KubernetesClient client, Map<String, String> matchLabels) {
        this.kubernetesClient = client;
        this.matchLabels = matchLabels;
      }
    
      public PodList list() {
        return kubernetesClient.pods().withLabels(matchLabels).list();
      }
    
      public int size() {
        return list().getItems().size();
      }
    
      // Rest of methods
    
    }
    

    Next, let’s try to write a test for this size method using Kubernetes Mock Server using both modes.

    CRUD mode

    In CRUD mode, you don’t need to set any expectations. You need to use KubernetesClient assuming a real Kubernetes API server is running in the background. You can see it’s quite transparent and readable:

    Refer to PodGroupServiceCrudTest.java.

    package io.fabric8.demos.tests.mockserver;
    
    import io.fabric8.kubernetes.api.model.PodBuilder;
    import io.fabric8.kubernetes.client.KubernetesClient;
    import io.fabric8.kubernetes.client.server.mock.EnableKubernetesMockClient;
    import io.fabric8.kubernetes.client.server.mock.KubernetesMockServer;
    import org.junit.jupiter.api.Test;
    
    import java.util.Collections;
    
    import static org.junit.jupiter.api.Assertions.assertEquals;
    
    @EnableKubernetesMockClient(crud = true)
    class PodGroupServiceCrudTest {
      private KubernetesClient kubernetesClient;
      private KubernetesMockServer server;
    
      @Test
      void size_whenPodsWithLabelPresent_thenReturnCount() {
        // Given
        Map<String, String> matchLabel = Collections.singletonMap("foo", "bar");
        kubernetesClient.pods().resource(createNewPod("p1", matchLabel)).create();
        PodGroupService podGroupService = new PodGroupService(kubernetesClient, matchLabel);
    
        // When
        int count = podGroupService.size();
    
        // Then
        assertEquals(1, count);
      }
    }
    

    Expectations mode

    While in Expectations mode, we need to set up expectations for the behavior we want when a certain Kubernetes resource endpoint the KubernetesClient requests:

    Refer to the PodGroupServiceTest.java.

    package io.fabric8.demos.tests.mockserver;
    
    import io.fabric8.kubernetes.api.model.PodBuilder;
    import io.fabric8.kubernetes.api.model.PodListBuilder;
    import io.fabric8.kubernetes.client.KubernetesClient;
    import io.fabric8.kubernetes.client.server.mock.EnableKubernetesMockClient;
    import io.fabric8.kubernetes.client.server.mock.KubernetesMockServer;
    import org.junit.jupiter.api.Test;
    
    import java.util.Collections;
    
    import static java.net.HttpURLConnection.HTTP_OK;
    import static org.junit.jupiter.api.Assertions.assertEquals;
    
    @EnableKubernetesMockClient
    class PodGroupServiceTest {
      private KubernetesClient kubernetesClient;
      private KubernetesMockServer server;
    
      @Test
      void size_whenPodsWithLabelPresent_thenReturnCount() {
        // Given
        server.expect().get()
            .withPath("/api/v1/namespaces/test/pods?labelSelector=foo%3Dbar")
            .andReturn(HTTP_OK, new PodListBuilder().addToItems(
                    new PodBuilder()
                        .withNewMetadata()
                        .withName("pod1")
                        .addToLabels("foo", "bar")
                        .endMetadata()
                        .build())
                .build())
            .once();
        PodGroupService podGroupService = new PodGroupService(kubernetesClient, Collections.singletonMap("foo", "bar"));
    
        // When
        int count = podGroupService.size();
    
        // Then
        assertEquals(1, count);
      }
    }
    

    Writing tests against real Kubernetes clusters

    Apart from Kubernetes Mock Server, Fabric8 Kubernetes Client provides a set of JUnit5 extension annotations that can simplify writing tests against a real Kubernetes Cluster.

    To use these JUnit5 annotations, you need to add this dependency:

    <dependency>
        <groupId>io.fabric8</groupId>
        <artifactId>kubernetes-junit-jupiter</artifactId>
        <version>${fabric8.version}</version>
        <scope>test</scope>
    </dependency>
    

    The following table lists the annotations provided by this dependency:

    Name

    Description

    @KubernetesTest

    Creates a temporary test namespace and configures a KubernetesClient instance in the test class to use in the tests.

    See example.

    @LoadKubernetesManifests

    Apply a YAML file to set up the environment before test execution.

    See example.

    @RequireK8sSupport

    Only execute the test when a specific Kubernetes resource is present in the Kubernetes cluster before test execution. It’s quite helpful in the case of custom resources.

    See example.

    @RequireK8sVersionAtLeast

    Only execute test when Kubernetes version is at least specified version.

    See example.

     

    Now let’s come back to our PodGroupService example and try to write an end-to-end test for the size() method. You can see it’s very similar to the test we wrote for Kubernetes Mock Server in CRUD mode, but here we’re using the JUnit5 annotations: PodGroupServiceIT.java.

    package io.fabric8.demos.tests.e2e;
    
    // …
    
    import io.fabric8.junit.jupiter.api.KubernetesTest;
    import io.fabric8.junit.jupiter.api.RequireK8sSupport;
    import io.fabric8.junit.jupiter.api.RequireK8sVersionAtLeast;
    
    
    @KubernetesTest
    @RequireK8sSupport(Pod.class)
    @RequireK8sVersionAtLeast(majorVersion = 1, minorVersion = 16)
    class PodGroupServiceIT {
      KubernetesClient kubernetesClient;
    
      @Test
      void size_whenPodsPresent_thenReturnActualSize() {
        // Given
        PodGroupService podGroupService = new PodGroupService(kubernetesClient, Collections.singletonMap("app", "size-non-zero"));
        podGroupService.addToGroup(createNewPod("p1", "size-non-zero"));
        podGroupService.addToGroup(createNewPod("p2", "size-non-zero"));
    
        // When
        int result = podGroupService.size();
    
        // Then
        assertEquals(2, result);
      }
    }
    

    Fabric8 Kubernetes series wrap-up

    This concludes my series on Fabric8 Kubernetes Java for developers. This article demonstrated how to write unit and end-to-end tests using testing libraries provided by Fabric8 Kubernetes Client. You can find the code in this GitHub repository.

    For more information, check out the Fabric8 Kubernetes Client GitHub page. Feel free to follow us on these channels:

    • StackOverflow
    • Fabric8 Kubernetes Client CHEATSHEET
    • Twitter
    • Gitter Chat

    Related Posts

    • How to use Kubernetes dynamic client with Fabric8

    • How to use Fabric8 Java Client with Kubernetes

    • Programming Kubernetes custom resources in Java

    • How to use Kubernetes dynamic client with Fabric8

    Recent Posts

    • Cloud bursting with confidential containers on OpenShift

    • Reach native speed with MacOS llama.cpp container inference

    • A deep dive into Apache Kafka's KRaft protocol

    • Staying ahead of artificial intelligence threats

    • Strengthen privacy and security with encrypted DNS in RHEL

    What’s up next?

    Find out how you can move your legacy Java application into a container and deploy it to Kubernetes in minutes using the Developer Sandbox for Red Hat OpenShift.

    Try Java in the sandbox
    Red Hat Developers logo LinkedIn YouTube Twitter Facebook

    Products

    • Red Hat Enterprise Linux
    • Red Hat OpenShift
    • Red Hat Ansible Automation Platform

    Build

    • Developer Sandbox
    • Developer Tools
    • Interactive Tutorials
    • API Catalog

    Quicklinks

    • Learning Resources
    • E-books
    • Cheat Sheets
    • Blog
    • Events
    • Newsletter

    Communicate

    • About us
    • Contact sales
    • Find a partner
    • Report a website issue
    • Site Status Dashboard
    • Report a security problem

    RED HAT DEVELOPER

    Build here. Go anywhere.

    We serve the builders. The problem solvers who create careers with code.

    Join us if you’re a developer, software engineer, web designer, front-end designer, UX designer, computer scientist, architect, tester, product manager, project manager or team lead.

    Sign me up

    Red Hat legal and privacy links

    • About Red Hat
    • Jobs
    • Events
    • Locations
    • Contact Red Hat
    • Red Hat Blog
    • Inclusion at Red Hat
    • Cool Stuff Store
    • Red Hat Summit
    © 2025 Red Hat

    Red Hat legal and privacy links

    • Privacy statement
    • Terms of use
    • All policies and guidelines
    • Digital accessibility

    Report a website issue