Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Discovering Tests
3.
Executing Tests
4.
Third-party Test Engines
5.
Third-party Post-Discovery Filters
6.
Third-party Test Execution Listeners
7.
Platform Reporting
8.
Example
9.
FAQs
10.
Key Takeaways
Last Updated: Mar 27, 2024

JUnit Platform Launcher API

gp-icon
Basics of javascript
Free guided path
10 chapters
68+ problems
gp-badge
Earn badges and level up

Introduction

JUnit is a framework in Java used for unit testing. It is vital in the development of test-driven development. It is part of the xUnit frameworks. We link the JUnit as a JAR file at compile time. JUnit5 resides under the org.junit.jupiter package in Java.

import org.junit.jupiter.api.*;

One of the most critical features of JUnit is to achieve a robust and stable interface between the client and JUnit. To enhance the power and make the interface more reliable, JUnit5 introduces the launcher module. The Platform Launcher module helps clients connect with third-party test libraries like Spock, Cucumber, and FitNesse.

The launcher API is present in the junit-platform-launcher module. Some of the primary features of Platform Launcher API are,

  • Discovering Tests
  • Executing Tests
  • Providing access to third-party Test Engines
  • Providing access to third-party Post-Discovery Filters
  • Providing access to third-party Test Execution Listeners
  • We can deactivate Test Execution Listeners
  • We can generate JUnit Platform reports

Discovering Tests

Test discovery as a feature of the platform is a very robust tool and prevents developers the hassle of having separate software for identifying test cases and test methods. Let us look at an example to understand this concept better,

import static org.junit.platform.engine.discovery.*;
import java.io.PrintWriter;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.junit.platform.launcher.*;
import org.junit.platform.reporting.legacy.xml.LegacyXmlReportGeneratingListener;
LauncherDiscoveryRequest request = LauncherDiscoveryRequestBuilder.request()
    .selectors(
        selectPackage("com.example.mytest1"),
        selectClass(TestClass.class)
    )
    .filters(
        includeClassNamePatterns(".*Tests")
    )
    .build();
Launcher launcher = LauncherFactory.create();
TestPlan testPlan = launcher.discover(request);

Clients can register more than one LauncherDiscoveryListener implementation in the above code to get details about the events that occur during test discovery through the LauncherDiscoveryRequestBuilder. The builder can register a default listener that can be later changed through the junit.platform.discovery.listener.default configuration parameter. If we don't set any parameter in the above code, test discovery will be aborted right after the first failure is encountered.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Executing Tests

Platform launchers can be used to execute tests or create new requests. We can achieve Test progress and reporting by registering one or more TestExecutionListener implementations with the Launcher.

LauncherDiscoveryRequest request = LauncherDiscoveryRequestBuilder.request()
    .selectors(
        selectPackage("com.example.mytests"),
        selectClass(MyTestClass.class)
    )
    .filters(
        includeClassNamePatterns(".*Tests")
    )
    .build();
Launcher launch_obj = LauncherFactory.create();
SummaryGeneratingListener listen_obj = new SummaryGeneratingListener();
launch_obj.registerTestExecutionListeners(listen_obj);
launch_obj.execute(request);
TestExecutionSummary summary = listener.getSummary();

We can now access the generated summary stored in the variable named summary.

Third-party Test Engines

JUnit provides us with two basic test search engines,

  • junit-jupiter-engine: This is a core JUnit Jupiter search engine
  • junit-vintage-engine: This is a prominent feature of JUnit4 that allows running vintage tests.

Using Platform Launcher API, we can enable third-party Test Search Engines in JUnit. We can implement the Test Engine Interface of the third party in the junit-platform-engine module and then register the Test engine using Java. We can register a Test Engine using the java.util.ServiceLoader package.

Third-party Post-Discovery Filters

In continuation to specifying post-discovery filters as part of a LauncherDiscoveryRequest passed to the Launcher API, custom PostDiscoveryFilter implementations will be discovered at runtime via Java’s java.util.ServiceLoader mechanism and automatically applied by the Launcher.

Third-party Test Execution Listeners

In continuation to the public Launcher API method for registering test execution listeners programmatically, custom TestExecutionListener implementations will be discovered at runtime via Java’s java.util.ServiceLoader mechanism and automatically registered with the Launcher created via the LauncherFactory. 

Platform Reporting

The junit-platform-reporting artifact contains the TestExecutionListener implementations that are used to generate test reports. These listeners are used mainly by various IDEs and development tools. 

The Java package org.junit.platform.reporting.legacy.xml contains the LegacyXmlReportGeneratingListener, which is used to generate a separate XML report for each of the roots in the TestPlan. 

Example

public class PlatformTestAPIRunner {
    SummaryGeneratingListener listen = new SummaryGeneratingListener();


    public void runOne() {
        LauncherDiscoveryRequest req = LauncherDiscoveryRequestBuilder.request()
                .selectors(selectClass(testClass.class))   
                .selectors(selectPackage("com.example"))     
                .filters(TagFilter.includeTags("test_example")) 
                .build();
        Launcher launch_obj = LauncherFactory.create();
        TestPlan test_obj = launcher.discover(req);
        launch_obj.registerTestExecutionListeners(listen);
        launch_obj.execute(req);
    }


    public static void main(String[] args) {
        final PlatformTestAPIRunner runner = new PlatformTestAPIRunner();
        runner.runOne();
        TestExecutionSummary summary = runner.listener.getSummary();
        summary.printTo(new PrintWriter(System.out));
    }
}

In the above code, first, we select the Java class we want to test (the testClass.class). Then we choose the package to be included for the test cases. We have selected the com.example package. As the last step, we provide a tag, test cases having the same name as the tag are considered for filtering. In our case, we have selected test_example as a tag.

FAQs

  1. What is JUnit?
    JUnit is a framework in Java used for unit testing. It is vital in the development of test-driven development. It is part of the xUnit frameworks. We link the JUnit as a JAR file at compile time. JUnit5 resides under the org.junit.jupiter package in Java.
     
  2. What is the latest version of JUnit?
    The most recent version of JUnit is Junit5, although the previous versions of Junit are still equally famous. For instance, JUnit4 has over 100,000 usages.
     
  3. What is JUnit Platform Launcher Module?
    To enhance the power and make the interface more reliable, JUnit5 introduces the launcher module. The Platform Launcher module helps clients connect with third-party test libraries like Spock, Cucumber, and FitNesse.
     
  4. What are the features of the Platform Launcher Module?
    Some of the primary features of Platform Launcher API are:
    Discovering Tests
    Executing Tests
    Providing access to third-party Test Engines
    Providing access to third-party Post-Discovery Filters
    Providing access to third-party Test Execution Listeners
    We can deactivate Test Execution Listeners
    We can generate JUnit Platform reports
     
  5. Why should we use JUnit Test Engines?
    JUnit Test Engines create a new instance for the test cases before invoking each test method. This makes the execution order more reliable by making the tests independent.

Key Takeaways

This Blog covered all the necessary points about the JUnit Platform Launcher API and all the features of the JUnit Platform Launcher API. We further discussed how to implement the JUnit Platform Launcher API using Java.

Check out JUnit Interview Questions here.

Don’t stop here; check out Coding Ninjas for more unique courses and guided paths. Also, try Coding Ninjas Studio for more exciting articles, interview experiences, and fantastic Data Structures and Algorithms problems.

Previous article
JUnit5 Dependency Injection for constructors and Methods
Next article
JUnit Platform Test Kit
Guided path
Free
gridgp-icon
Basics of javascript
10 chapters
68+ Problems
gp-badge
Earn badges and level up
Live masterclass