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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Test Driven Development Using TestNG, Gradle
  • Spring 5 Web Reactive: Flux, Mono, and JUnit Testing
  • How to Test QR Codes in Your Applications
  • Selenium Grid Tutorial: Essential Tips and How to Set It Up

Trending

  • The Future of Java and AI: Coding in 2025
  • Tired of Spring Overhead? Try Dropwizard for Your Next Java Microservice
  • Monolith: The Good, The Bad and The Ugly
  • How to Create a Successful API Ecosystem
  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
5.6K 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

  • Test Driven Development Using TestNG, Gradle
  • Spring 5 Web Reactive: Flux, Mono, and JUnit Testing
  • How to Test QR Codes in Your Applications
  • Selenium Grid Tutorial: Essential Tips and How to Set It Up

Partner Resources

×

Comments
Oops! Something Went Wrong

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

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!