Skip to main content
Redhat Developers  Logo
  • AI

    Get started with AI

    • Red Hat AI
      Accelerate the development and deployment of enterprise AI solutions.
    • AI learning hub
      Explore learning materials and tools, organized by task.
    • AI interactive demos
      Click through scenarios with Red Hat AI, including training LLMs and more.
    • AI/ML learning paths
      Expand your OpenShift AI knowledge using these learning resources.
    • AI quickstarts
      Focused AI use cases designed for fast deployment on Red Hat AI platforms.
    • No-cost AI training
      Foundational Red Hat AI training.

    Featured resources

    • OpenShift AI learning
    • Open source AI for developers
    • AI product application development
    • Open source-powered AI/ML for hybrid cloud
    • AI and Node.js cheat sheet

    Red Hat AI Factory with NVIDIA

    • Red Hat AI Factory with NVIDIA is a co-engineered, enterprise-grade AI solution for building, deploying, and managing AI at scale across hybrid cloud environments.
    • Explore the solution
  • Learn

    Self-guided

    • Documentation
      Find answers, get step-by-step guidance, and learn how to use Red Hat products.
    • Learning paths
      Explore curated walkthroughs for common development tasks.
    • Guided learning
      Receive custom learning paths powered by our AI assistant.
    • See all learning

    Hands-on

    • Developer Sandbox
      Spin up Red Hat's products and technologies without setup or configuration.
    • Interactive labs
      Learn by doing in these hands-on, browser-based experiences.
    • Interactive demos
      Click through product features in these guided tours.

    Browse by topic

    • AI/ML
    • Automation
    • Java
    • Kubernetes
    • Linux
    • See all topics

    Training & certifications

    • Courses and exams
    • Certifications
    • Skills assessments
    • Red Hat Academy
    • Learning subscription
    • Explore training
  • Build

    Get started

    • Red Hat build of Podman Desktop
      A downloadable, local development hub to experiment with our products and builds.
    • Developer Sandbox
      Spin up Red Hat's products and technologies without setup or configuration.

    Download products

    • Access product downloads to start building and testing right away.
    • Red Hat Enterprise Linux
    • Red Hat AI
    • Red Hat OpenShift
    • Red Hat Ansible Automation Platform
    • See all products

    Featured

    • Red Hat build of OpenJDK
    • Red Hat JBoss Enterprise Application Platform
    • Red Hat OpenShift Dev Spaces
    • Red Hat Developer Toolset

    References

    • E-books
    • Documentation
    • Cheat sheets
    • Architecture center
  • Community

    Get involved

    • Events
    • Live AI events
    • Red Hat Summit
    • Red Hat Accelerators
    • Community discussions

    Follow along

    • Articles & blogs
    • Developer newsletter
    • Videos
    • Github

    Get help

    • Customer service
    • Customer support
    • Regional contacts
    • Find a partner

    Join the Red Hat Developer program

    • Download Red Hat products and project builds, access support documentation, learning content, and more.
    • Explore the benefits

How to write tests with Fabric8 Kubernetes Client

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

    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

    • Debugging image mode with Red Hat OpenShift 4.20: A practical guide

    • EvalHub: Because "looks good to me" isn't a benchmark

    • SQL Server HA on RHEL: Meet Pacemaker HA Agent v2 (tech preview)

    • Deploy with confidence: Continuous integration and continuous delivery for agentic AI

    • Every layer counts: Defense in depth for AI agents with Red Hat AI

    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

    Platforms

    • Red Hat AI
    • Red Hat Enterprise Linux
    • Red Hat OpenShift
    • Red Hat Ansible Automation Platform
    • See all products

    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
    © 2026 Red Hat

    Red Hat legal and privacy links

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

    Chat Support

    Please log in with your Red Hat account to access chat support.