DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Apache Spark 3 to Apache Spark 4 Migration: What Breaks, What Improves, What's Mandatory
  • Hybrid Vector Graph with AI Agents for Software Test Case Creation
  • Building Realistic Test Data in Java: A Hands-On Guide for Developers
  • Top 7 Mistakes When Testing JavaFX Applications

Trending

  • A 5-Step SOC Guide That Meets RBI Expectations and Strengthens Security Operations
  • You Don't Get to Retrofit Trust: Why API Security Must Be Designed In, Not Bolted On
  • Integrating AI-Driven Decision-Making in Agile Frameworks: A Deep Dive into Real-World Applications and Challenges
  • Building a Production-Ready AI Agent in 2026: Beyond the Hello World Demo
  1. DZone
  2. Testing, Deployment, and Maintenance
  3. Testing, Tools, and Frameworks
  4. JUnit 5 Custom TestListeners

JUnit 5 Custom TestListeners

Post your test execution results directly from CI/CD to your Test Management System via Zephyr API via JUnit5 Test Execution Listeners.

By 
Prathyusha Nama user avatar
Prathyusha Nama
·
Jul. 23, 24 · Tutorial
Likes (3)
Comment
Save
Tweet
Share
6.4K Views

Join the DZone community and get the full member experience.

Join For Free

If you are using JUnit5 for your Automation and would like to post your test execution results directly from CI/CD to your Test Management System via Zephyr API, it is possible to do so via JUnit5 Test Execution Listeners.

Custom Listener

You can create a custom Listener according to your needs. In our case, the API needs the results in a specific format and zipped. We will have to add custom logic for that and send the Test case name and key along with the execution result for a test. you can do this by using the following Listener methods.

Java
 
    @Override
    public void beforeTestExecution(ExtensionContext context) {
        testCaseDataMap.clear();
        String testCase = TestUtil.getTestCaseName(context);
        String key = TestUtil.getTestCaseKey(context);
        testCaseDataMap.put("testCaseKey", key);
        testCaseDataMap.put("testCaseName", testCase);
    }

    @Override
    public void executionFinished(TestIdentifier testIdentifier, TestExecutionResult testExecutionResult) {
        String testCaseKey = testCaseDataMap.get("testCaseKey");
        String testCaseName = testCaseDataMap.get("testCaseName");
        if (!isTestCaseExecuted(testCaseKey)) {
            ObjectNode execution = objectMapper.createObjectNode();
            execution.put("result", getResultString(testExecutionResult.getStatus()));
            execution.put("source", testCaseName);
            ObjectNode testCase = objectMapper.createObjectNode();
            testCase.put("key", testCaseKey);
            execution.set("testCase", testCase);
            executions.add(execution);
        }
        }


We will create a map before Test Execution starts with "testCaseKey" and "testCaseName" and then once the execution is finished we grab the values from test methods and put them into the map along with the execution results status.

Now, once we have the data we need, we can format the data in the expected format of API.

Java
 
@Override
    public void testPlanExecutionFinished(TestPlan testPlan)
     {
         if (postResults) {
             root.put("version", 1);
             root.set("executions", executions);
             writeResultsToJsonFile();
             try {
                 zipJsonFile();
             } catch (IOException e) {
                 throw new RuntimeException("Failed to zip json file", e);
             }
         }
     }


Java
 
 private void writeResultsToJsonFile() {
        try {
            ObjectWriter writer = objectMapper.writerWithDefaultPrettyPrinter();
            String json = writer.writeValueAsString(root);
            Files.writeString(Paths.get("output.json"), json);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
Java
 
 private void zipJsonFile() throws IOException {
        String jsonFilePath = "output.json";
        String zipFilePath = "output.zip";

        try (FileOutputStream fos = new FileOutputStream(zipFilePath);
             ZipOutputStream zos = new ZipOutputStream(fos);
             FileInputStream fis = new FileInputStream(jsonFilePath)) {

            ZipEntry zipEntry = new ZipEntry(jsonFilePath);
            zos.putNextEntry(zipEntry);

            byte[] buffer = new byte[1024];
            int length;
            while ((length = fis.read(buffer)) >= 0) {
                zos.write(buffer, 0, length);
            }
            zos.closeEntry();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            Path path = Paths.get(jsonFilePath);
            Files.deleteIfExists(path);
        } catch (IOException e) {
            e.printStackTrace();
        }


We have the Execution results JSON file created after the Test Execution of all methods is completed and the output JSON file has TestCaseky, Test CaseName, and Execution Result. We then format the file based on API expectations and then zip the file.

The final step is to send the file to POST call for results to be posted.

Java
 
        RestAssured.given()
                .header("Authorization", System.getProperty("authToken"))
                .contentType("multipart/form-data")
                .pathParam("projectKey", projectKey)
                .multiPart("file", new File(zipFilePath))
                .multiPart("testCycle", jsonString)
                .post("/automation/execution/{projectKey}")
                .then()
                .statusCode(200)
                .extract().response()
                .then().assertThat().body("testCycle", hasKey("key"));


With this approach, we don't have to maintain or create a new pipeline or script maintained outside the repo to post Execution Results from the CI pipeline to the Test Case Management system for traceability. All of this is case of by the Test Listeners.

Important Note

Custom Listener needs to be registered for us to use it with our framework.

Create a Listener file in the following location and register the Custom Listener.

listener

Specify your Listener in the File as shown below:

Java
 
listeners.CustomListener


That's all. You are good to go.

Happy coding!

Management system Test case Test management Java (programming language) Testing

Opinions expressed by DZone contributors are their own.

Related

  • Apache Spark 3 to Apache Spark 4 Migration: What Breaks, What Improves, What's Mandatory
  • Hybrid Vector Graph with AI Agents for Software Test Case Creation
  • Building Realistic Test Data in Java: A Hands-On Guide for Developers
  • Top 7 Mistakes When Testing JavaFX Applications

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook