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
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Testing Java and Spring Applications With Kotlin: Low-Risk to Adoption
  • The Math Behind AI Testing: Why 1,000 Test Cases May Tell You Less Than 100
  • 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

Trending

  • Beyond State Consistency: Preventing Stale Decisions in AI Agent Systems
  • Two AI Agents, One Database: Solving Concurrent Updates With Optimistic Locking
  • The Pipeline Failed, But the Infrastructure Changed
  • Build Production-Ready AI Phone Agents: Infrastructure, Models, and Telephony

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  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
·
Jul. 23, 24 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
6.8K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

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

  • Testing Java and Spring Applications With Kotlin: Low-Risk to Adoption
  • The Math Behind AI Testing: Why 1,000 Test Cases May Tell You Less Than 100
  • 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

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • 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