### Pattern Matching Examples for Configuration Parameters Source: https://docs.junit.org/current/user-guide/index Provides examples of pattern matching syntax used with JUnit Platform configuration parameters. These patterns are applied to fully qualified class names (FQCN) for features like deactivating conditions or filtering extensions. The syntax allows for wildcard matching and specific class name matching. ```text * org.junit.* *.MyCustomImpl *System* *System*, *Unit* org.example.MyCustomImpl org.example.MyCustomImpl, org.example.TheirCustomImpl ``` -------------------------------- ### JUnit Platform Pattern Matching Syntax Examples Source: https://docs.junit.org/current/user-guide Provides examples of the pattern matching syntax used for JUnit Platform configuration parameters. This syntax is applied to features like deactivating conditions, listeners, and filtering extensions. ```plaintext # Matches all candidate classes. * # Matches all candidate classes under the org.junit base package and its subpackages. org.junit.* # Matches every candidate class whose simple class name is exactly MyCustomImpl. *.MyCustomImpl # Matches every candidate class whose FQCN contains System. *System* # Matches every candidate class whose FQCN contains System or Unit. *System*, *Unit* # Matches the candidate class whose FQCN is exactly org.example.MyCustomImpl. org.example.MyCustomImpl # Matches candidate classes whose FQCN is exactly org.example.MyCustomImpl or org.example.TheirCustomImpl. org.example.MyCustomImpl, org.example.TheirCustomImpl ``` -------------------------------- ### JUnit Platform Suite Annotation Example Source: https://docs.junit.org/current/user-guide/index Demonstrates how to annotate a class with @Suite to mark it as a test suite. It includes examples of selector and filter annotations like @SelectPackages and @IncludeClassNamePatterns to control the suite's contents. This requires the JUnit Platform Suite API. ```java import org.junit.platform.suite.api.IncludeClassNamePatterns; import org.junit.platform.suite.api.SelectPackages; import org.junit.platform.suite.api.Suite; import org.junit.platform.suite.api.SuiteDisplayName; @Suite @SuiteDisplayName("JUnit Platform Suite Demo") @SelectPackages("example") @IncludeClassNamePatterns(".*Tests") class SuiteDemo { } ``` -------------------------------- ### Get Containers Started Count (Java) - org.junit.platform.launcher.listeners.TestExecutionSummary Source: https://docs.junit.org/current/api/index-files/index-7 Gets the number of containers that were started during test execution. This is a count provided by the test execution summary. ```Java long org.junit.platform.launcher.listeners.TestExecutionSummary.getContainersStartedCount() ``` -------------------------------- ### VintageTestEngine Constructor Source: https://docs.junit.org/current/api/org.junit.vintage.engine/org/junit/vintage/engine/VintageTestEngine Initializes a new instance of the VintageTestEngine. ```APIDOC ## POST /constructor/VintageTestEngine ### Description Initializes a new instance of the VintageTestEngine. ### Method POST ### Endpoint /constructor/VintageTestEngine ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```json { "example": "No request body needed for constructor" } ``` ### Response #### Success Response (200) - **instance** (VintageTestEngine) - A new instance of VintageTestEngine. #### Response Example ```json { "example": "Instance of VintageTestEngine created successfully" } ``` ``` -------------------------------- ### JUnit 5: Get Started Events Stream Source: https://docs.junit.org/current/api/index-files/index-19 Retrieves a `Stream` of `Events` objects that have a `STARTED` status. This allows for functional-style processing of started events. ```java Events.started().stream() ``` -------------------------------- ### Implement Global Setup/Teardown with JUnit LauncherSessionListener in Java Source: https://docs.junit.org/current/user-guide/index This Java code defines a LauncherSessionListener that initializes an HTTP server before the first test execution and ensures it's stopped when the launcher session closes. It leverages the JUnit Platform's store mechanism for lazy initialization and resource management. Dependencies include JUnit Platform API and JDK's http.server module. ```java package example.session; import static java.net.InetAddress.getLoopbackAddress; import java.io.IOException; import java.io.UncheckedIOException; import java.net.InetSocketAddress; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import com.sun.net.httpserver.HttpServer; import org.junit.platform.engine.support.store.Namespace; import org.junit.platform.engine.support.store.NamespacedHierarchicalStore; import org.junit.platform.launcher.LauncherSession; import org.junit.platform.launcher.LauncherSessionListener; import org.junit.platform.launcher.TestExecutionListener; import org.junit.platform.launcher.TestPlan; public class GlobalSetupTeardownListener implements LauncherSessionListener { @Override public void launcherSessionOpened(LauncherSession session) { // Avoid setup for test discovery by delaying it until tests are about to be executed session.getLauncher().registerTestExecutionListeners(new TestExecutionListener() { @Override public void testPlanExecutionStarted(TestPlan testPlan) { NamespacedHierarchicalStore store = session.getStore(); store.getOrComputeIfAbsent(Namespace.GLOBAL, "httpServer", key -> { InetSocketAddress address = new InetSocketAddress(getLoopbackAddress(), 0); HttpServer server; try { server = HttpServer.create(address, 0); } catch (IOException e) { throw new UncheckedIOException("Failed to start HTTP server", e); } server.createContext("/test", exchange -> { exchange.sendResponseHeaders(204, -1); exchange.close(); }); ExecutorService executorService = Executors.newCachedThreadPool(); server.setExecutor(executorService); server.start(); return new CloseableHttpServer(server, executorService); }); } }); } } ``` -------------------------------- ### JUnit 5: Get Started Executions Stream Source: https://docs.junit.org/current/api/index-files/index-19 Retrieves a `Stream` of `Executions` objects that have a `STARTED` status. This enables stream-based operations on started test executions. ```java Executions.started().stream() ``` -------------------------------- ### Get Started Executions - Java Source: https://docs.junit.org/current/api/org.junit.platform.testkit/org/junit/platform/testkit/engine/Executions Retrieves all started executions from the current Executions object. This represents tests that have begun execution. ```java Executions started() ``` -------------------------------- ### Launcher Discovery and Execution Source: https://docs.junit.org/current/api/org.junit.platform.launcher/org/junit/platform/launcher/package-use Details on how to use the `Launcher` to discover and execute tests, involving requests and listeners. ```APIDOC ## API Operations: Test Discovery and Execution ### Description This section covers the core operations of discovering and executing tests using the `Launcher` API, including the use of requests and listeners. ### Methods * **Discover Tests**: `Launcher.discover(LauncherDiscoveryRequest request)` * **Execute Tests**: `Launcher.execute(LauncherDiscoveryRequest request)` or `Launcher.execute(TestPlan testPlan)` ### Endpoint N/A (Java API) ### Parameters #### `LauncherDiscoveryRequest` Parameters * **Engine Filters**: (`EngineFilter`) - Optional - Filters to apply to `TestEngines` before discovery. * **Post Discovery Filters**: (`PostDiscoveryFilter`) - Optional - Filters to apply to `TestDescriptors` after discovery. * **Listeners**: (`TestExecutionListener`, `LauncherDiscoveryListener`, etc.) - Optional - Listeners to register for events during discovery and execution. ### Request Example (Illustrative Java code for setting up a request and executing) ```java Launcher launcher = LauncherFactory.create(); LauncherDiscoveryRequest request = LauncherDiscoveryRequestBuilder.request() .selectors(...) // Configure selectors (e.g., ClassSelector, MethodSelector) .filters(...) // Configure filters .listeners(...) .build(); TestPlan testPlan = launcher.discover(request); launcher.execute(testPlan); ``` ### Response #### Success Response * **`discover()`**: Returns a `TestPlan` object representing the discovered tests. * **`execute()`**: Executes the tests. Results are reported via registered `TestExecutionListener` implementations. #### Response Example (Illustrative Java code showing listener callback) ```java launcher.execute(testPlan, new TestExecutionListener() { @Override public void executionStarted(TestIdentifier testIdentifier) { System.out.println("Started: " + testIdentifier.getDisplayName()); } @Override public void executionFinished(TestIdentifier testIdentifier, TestExecutionResult result) { System.out.println("Finished: " + testIdentifier.getDisplayName() + " - Result: " + result.getStatus()); } }); ``` ``` -------------------------------- ### Get Started Executions in Java Source: https://docs.junit.org/current/api/org.junit.platform.testkit/org/junit/platform/testkit/engine/Executions Filters and returns only the executions that have been started. This method is useful for tracking the progress of executions. It guarantees to return a non-null Executions object. ```java public Executions started() Get the started `Executions` contained in this `Executions` object. Returns: the filtered `Executions`; never `null` ``` -------------------------------- ### Launcher API Overview Source: https://docs.junit.org/current/api/org.junit.platform.launcher/module-summary This section outlines the main packages, modules, and services provided by the JUnit Platform Launcher API. ```APIDOC ## JUnit Platform Launcher API ### Description Public API for configuring and launching test plans. This API is typically used by IDEs and build tools. ### Packages **Exports:** - `org.junit.platform.launcher`: Public API for configuring and launching test plans. - `org.junit.platform.launcher.core`: Core support classes for the `Launcher` including the `LauncherFactory` and the `LauncherDiscoveryRequestBuilder`. - `org.junit.platform.launcher.listeners`: Common `TestExecutionListener` implementations and related support classes for the `Launcher`. - `org.junit.platform.launcher.listeners.discovery`: Common `LauncherDiscoveryListener` implementations and factory methods. ### Modules **Requires:** - `org.junit.platform.commons` (transitive): Common APIs and support utilities for the JUnit Platform. - `org.junit.platform.engine` (transitive): Public API for test engines. ### Services **Uses:** - `LauncherDiscoveryListener`: Listener for test discovery events. - `LauncherInterceptor`: Interceptor for test discovery and execution. - `LauncherSessionListener`: Listener for `LauncherSession` lifecycle events. - `PostDiscoveryFilter`: Filter applied after test discovery. - `TestEngine`: Facilitates discovery and execution of tests. - `TestExecutionListener`: Listener for test execution events. ``` -------------------------------- ### Get Started Executions (Java) Source: https://docs.junit.org/current/api/org.junit.platform.testkit/org/junit/platform/testkit/engine/class-use/Executions Retrieves the started `Executions` from an `Executions` object. This method is used to track the initiation of test executions within the JUnit Platform. ```java Executions.started() ``` -------------------------------- ### Implement Global HTTP Server Setup/Teardown with LauncherSessionListener (Java) Source: https://docs.junit.org/current/user-guide This Java code defines a custom LauncherSessionListener that starts an HTTP server before the first test execution and stops it after the last test in a launcher session. It leverages the JUnit Platform's store mechanism to lazily initialize and manage the server lifecycle. Dependencies include JUnit Platform API and JDK's built-in HTTP server. The listener is registered via a service file. ```java package example.session; import static java.net.InetAddress.getLoopbackAddress; import java.io.IOException; import java.io.UncheckedIOException; import java.net.InetSocketAddress; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import com.sun.net.httpserver.HttpServer; import org.junit.platform.engine.support.store.Namespace; import org.junit.platform.engine.support.store.NamespacedHierarchicalStore; import org.junit.platform.launcher.LauncherSession; import org.junit.platform.launcher.LauncherSessionListener; import org.junit.platform.launcher.TestExecutionListener; import org.junit.platform.launcher.TestPlan; public class GlobalSetupTeardownListener implements LauncherSessionListener { @Override public void launcherSessionOpened(LauncherSession session) { // Avoid setup for test discovery by delaying it until tests are about to be executed session.getLauncher().registerTestExecutionListeners(new TestExecutionListener() { @Override public void testPlanExecutionStarted(TestPlan testPlan) { NamespacedHierarchicalStore store = session.getStore(); store.getOrComputeIfAbsent(Namespace.GLOBAL, "httpServer", key -> { InetSocketAddress address = new InetSocketAddress(getLoopbackAddress(), 0); HttpServer server; try { server = HttpServer.create(address, 0); } catch (IOException e) { throw new UncheckedIOException("Failed to start HTTP server", e); } server.createContext("/test", exchange -> { exchange.sendResponseHeaders(204, -1); exchange.close(); }); ExecutorService executorService = Executors.newCachedThreadPool(); server.setExecutor(executorService); server.start(); return new CloseableHttpServer(server, executorService); }); } }); } } ``` -------------------------------- ### Launch JUnit Tests from Console using Java Source: https://docs.junit.org/current/api/org.junit.platform.console/org/junit/platform/console/ConsoleLauncher The `main` method in `ConsoleLauncher` is the entry point for running JUnit tests from the command line. It accepts string arguments to configure and execute the test suite. ```java public static void main(String... args) ``` -------------------------------- ### Get Started Events with JUnit Platform Test Kit Source: https://docs.junit.org/current/api/org.junit.platform.testkit/org/junit/platform/testkit/engine/class-use/Events Retrieves all started events contained within an Events object. This marks the beginning of test execution phases. ```java Events.started() ``` -------------------------------- ### Create New SuiteLauncherDiscoveryRequestBuilder Source: https://docs.junit.org/current/api/org.junit.platform.suite.commons/org/junit/platform/suite/commons/SuiteLauncherDiscoveryRequestBuilder Initiates the creation of a new SuiteLauncherDiscoveryRequestBuilder. This is the starting point for configuring test discovery requests. ```java public static SuiteLauncherDiscoveryRequestBuilder request() ``` -------------------------------- ### Retrieve Start Instant from Execution (Java) Source: https://docs.junit.org/current/api/org.junit.platform.testkit/org/junit/platform/testkit/engine/Execution Gets the `Instant` at which the test execution started. This method is part of the execution metadata and helps in calculating the duration and analyzing the timing of test runs. ```java public Instant getStartInstant() { // Implementation details... return null; } ``` -------------------------------- ### Execute JUnit Tests with Listeners and Summary Source: https://docs.junit.org/current/user-guide/index This code demonstrates how to execute JUnit tests using the Launcher API. It sets up a discovery request, registers a `SummaryGeneratingListener` to capture test execution details, and then executes the tests. The summary of the test execution can be retrieved from the listener afterwards. It utilizes `LauncherDiscoveryRequest`, `SummaryGeneratingListener`, `LauncherSession`, and `TestPlan`. ```java LauncherDiscoveryRequest request = LauncherDiscoveryRequestBuilder.request() .selectors( selectPackage("com.example.mytests"), selectClass(MyTestClass.class) ) .filters( includeClassNamePatterns(".*Tests") ) .build(); SummaryGeneratingListener listener = new SummaryGeneratingListener(); try (LauncherSession session = LauncherFactory.openSession()) { Launcher launcher = session.getLauncher(); // Register a listener of your choice launcher.registerTestExecutionListeners(listener); // Discover tests and build a test plan TestPlan testPlan = launcher.discover(request); // Execute test plan launcher.execute(testPlan); // Alternatively, execute the request directly launcher.execute(request); } TestExecutionSummary summary = listener.getSummary(); // Do something with the summary... ``` -------------------------------- ### Get Started Events in Java Source: https://docs.junit.org/current/api/org.junit.platform.testkit/org/junit/platform/testkit/engine/Events Retrieves a new `Events` object containing only the events that signify the start of a test or test execution phase. This is useful for focusing on the initiation of test activities. ```java import org.junit.platform.testkit.engine.Events; // Assuming 'events' is an instance of Events Events startedEvents = events.started(); ``` -------------------------------- ### Console Launcher Help and Commands Source: https://docs.junit.org/current/user-guide/index Displays the usage information and available commands for the JUnit Console Launcher. This includes options for help, version, disabling ANSI colors, and subcommands like `discover`, `execute`, and `engines`. ```bash Usage: junit [OPTIONS] [COMMAND] Launches the JUnit Platform for test discovery and execution. [@...] One or more argument files containing options. -h, --help Display help information. --version Display version information. --disable-ansi-colors Disable ANSI colors in output (not supported by all terminals). Commands: discover Discover tests execute Execute tests engines List available test engines For more information, please refer to the JUnit User Guide at https://docs.junit.org/1.13.4/user-guide/ ``` -------------------------------- ### Create Launcher Instance with Factory Source: https://docs.junit.org/current/api/index-files/index-12 Demonstrates how to create Launcher instances using the LauncherFactory. This involves either a default creation or providing a custom LauncherConfig. ```java Launcher launcher = LauncherFactory.create(); // Or with custom configuration LauncherConfig config = LauncherConfig.builder().build(); Launcher customLauncher = LauncherFactory.create(config); ``` -------------------------------- ### Get Started Events - Java Source: https://docs.junit.org/current/api/org.junit.platform.testkit/org/junit/platform/testkit/engine/Events Filters and returns a new `Events` object containing only the events that represent the start of a test execution. This method is useful for tracking the initiation of tests. The returned `Events` object is guaranteed not to be null. ```java public Events started() Get the started `Events` contained in this `Events` object. Returns: the filtered `Events`; never `null` ``` -------------------------------- ### Get EngineDiscoveryRequest from InitializationContext (Java) Source: https://docs.junit.org/current/api/org.junit.platform.engine/org/junit/platform/engine/class-use/EngineDiscoveryRequest This Java code retrieves an EngineDiscoveryRequest from an InitializationContext, typically used during the setup phase of test discovery. ```java EngineDiscoveryRequest EngineDiscoveryRequestResolver.InitializationContext.getDiscoveryRequest() ``` -------------------------------- ### Configure JUnit Platform via Console Launcher (Command Line) Source: https://docs.junit.org/current/user-guide Illustrates how to specify configuration parameters when running tests using the JUnit Platform's Console Launcher. The `--config` option allows passing key-value pairs directly from the command line, overriding other configuration sources. ```bash # Example: Setting a configuration parameter for JUnit Jupiter engine java -jar junit-platform-console-standalone.jar \ --select-package com.example.tests \ --config "junit.jupiter.conditions.deactivate=*System*" # Example: Setting multiple configuration parameters java -jar junit-platform-console-standalone.jar \ --select-package com.example.tests \ --config "junit.jupiter.engine.extension.autodetetection.enabled=true" \ --config "junit.jupiter.displayname.generator.default=org.junit.jupiter.api.DisplayNameGenerator.Simple" ``` -------------------------------- ### Get Event Type Source: https://docs.junit.org/current/api/org.junit.platform.testkit/org/junit/platform/testkit/engine/Event Retrieves the `EventType` of this `Event`. The `EventType` indicates the nature of the event, such as execution start, finish, or skip. Requires JUnit 5.4+. ```java @API(status=MAINTAINED, since="1.4") public EventType getType() { // Implementation details not provided in the source text return null; } ``` -------------------------------- ### Open JUnit Launcher Session Source: https://docs.junit.org/current/api/index-files/index-15 Factory method for opening a new `LauncherSession`. It can use the default configuration or a custom `LauncherConfig` for detailed setup. ```java LauncherFactory.openSession() ``` ```java LauncherFactory.openSession(LauncherConfig launcherConfig) ``` -------------------------------- ### Get Event Type (Java) Source: https://docs.junit.org/current/api/org.junit.platform.testkit/org/junit/platform/testkit/engine/Event Retrieves the type of an Event. This method returns the specific type of the event, such as STARTED, FINISHED, or SKIPPED. The return value is never null. ```java public EventType getType() ``` -------------------------------- ### LauncherDiscoveryListener Interface Methods Source: https://docs.junit.org/current/api/org.junit.platform.launcher/org/junit/platform/launcher/LauncherDiscoveryListener This snippet shows the core methods of the LauncherDiscoveryListener interface, including default implementations for starting and finishing launcher and engine discovery. These methods allow observation of the test discovery lifecycle. ```java /** * Called when test discovery is about to be started. * * @param request the request for which discovery is being started */ default void launcherDiscoveryStarted(LauncherDiscoveryRequest request) { // Default implementation } /** * Called when test discovery has finished. * * @param request the request for which discovery has finished */ default void launcherDiscoveryFinished(LauncherDiscoveryRequest request) { // Default implementation } /** * Called when test discovery is about to be started for an engine. * * @param engineId the unique ID of the engine descriptor */ default void engineDiscoveryStarted(UniqueId engineId) { // Default implementation } /** * Called when test discovery has finished for an engine. * Exceptions thrown by implementations of this method will cause the complete test discovery to be aborted. * * @param engineId the unique ID of the engine descriptor * @param result the discovery result of the supplied engine */ default void engineDiscoveryFinished(UniqueId engineId, EngineDiscoveryResult result) { // Default implementation } ``` -------------------------------- ### Get Test Execution Timestamps - JUnit Platform Launcher Source: https://docs.junit.org/current/api/index-files/index-7 Retrieves the timestamps indicating when the test plan started and finished. These timestamps are in milliseconds and are useful for performance analysis and logging. ```java /** * Get the timestamp (in milliseconds) when the test plan finished. */ long getTimeFinished(); /** * Get the timestamp (in milliseconds) when the test plan started. */ long getTimeStarted(); ``` -------------------------------- ### SuiteLauncherDiscoveryRequestBuilder DSL Example Source: https://docs.junit.org/current/api/index-files/index-19 Demonstrates the usage of `SuiteLauncherDiscoveryRequestBuilder` for creating a `LauncherDiscoveryRequest` tailored for suite execution. This builder provides a Domain Specific Language (DSL) for this purpose. ```java LauncherDiscoveryRequest request = SuiteLauncherDiscoveryRequestBuilder.requestForSuite(MySuiteClass.class); ``` -------------------------------- ### Create LauncherConfig Builder in JUnit 5 Source: https://docs.junit.org/current/api/index-files/index-2 Shows how to instantiate a builder for configuring LauncherConfig in JUnit 5. This is used for setting up the test launcher's configuration. ```java import org.junit.platform.launcher.core.LauncherConfig; // ... LauncherConfig.Builder configBuilder = LauncherConfig.builder(); ``` -------------------------------- ### Get Root TestDescriptor from ExecutionRequest Source: https://docs.junit.org/current/api/org.junit.platform.engine/org/junit/platform/engine/class-use/TestDescriptor The ExecutionRequest class in the JUnit Platform provides a method to retrieve the root TestDescriptor. This descriptor represents the starting point for the engine that processes the execution request. ```java TestDescriptor ExecutionRequest.getRootTestDescriptor() ``` -------------------------------- ### Composed Annotation Example in Java Source: https://docs.junit.org/current/api/org.junit.jupiter.params/org/junit/jupiter/params/ParameterizedClass Illustrates how to create a custom composed annotation that inherits the semantics of @ParameterizedClass. This allows for creating reusable configurations for parameterized tests, simplifying test setup. ```java import org.junit.jupiter.params.ParameterizedClass; import org.junit.jupiter.params.provider.CsvSource; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @ParameterizedClass @CsvSource({"1,one", "2,two", "3,three"}) public @interface MyCsvParameterizedTest { } @MyCsvParameterizedTest public class ComposedAnnotationTest { @org.junit.jupiter.params.ParameterizedTest void testWithComposedAnnotation(int number, String text) { System.out.println("Number: " + number + ", Text: " + text); // Assertions } } ``` -------------------------------- ### Opening a LauncherSession with JUnit Platform LauncherFactory Source: https://docs.junit.org/current/api/org.junit.platform.launcher/org/junit/platform/launcher/class-use/LauncherSession Demonstrates how to open a new LauncherSession using the LauncherFactory. It shows variations for using the default configuration or a custom LauncherConfig. These methods are essential for initiating test execution contexts. ```java import org.junit.platform.launcher.LauncherFactory; import org.junit.platform.launcher.LauncherSession; import org.junit.platform.launcher.LauncherConfig; // Using default configuration LauncherSession sessionDefault = LauncherFactory.openSession(); // Using a custom configuration LauncherConfig config = LauncherConfig.builder().build(); // Example configuration LauncherSession sessionCustom = LauncherFactory.openSession(config); ``` -------------------------------- ### JUnit ToolProvider Interface - run Method Source: https://docs.junit.org/current/api/org.junit.platform.console/org/junit/platform/console/ConsoleLauncherToolProvider Demonstrates the signature of the `run` method as defined by the `ToolProvider` interface, which is implemented by `ConsoleLauncherToolProvider`. This method is responsible for executing the tool with provided output and error streams. ```java /** * Runs the tool. * * @param out the standard output stream * @param err the standard error stream * @param args the command line arguments * @return the exit code */ @Override public int run(PrintWriter out, PrintWriter err, String... args); ``` -------------------------------- ### Get JUnit Root Test Descriptor (Java) Source: https://docs.junit.org/current/api/org.junit.platform.engine/org/junit/platform/engine/ExecutionRequest Returns the root TestDescriptor for the engine processing the ExecutionRequest. This descriptor represents the top-level node in the test hierarchy and is the starting point for test discovery and execution. ```java TestDescriptor getRootTestDescriptor() ``` -------------------------------- ### Get JUnit Engine Execution Listener (Java) Source: https://docs.junit.org/current/api/org.junit.platform.engine/org/junit/platform/engine/ExecutionRequest Returns the EngineExecutionListener for the current ExecutionRequest. This listener is crucial for notifying the test framework about various test execution events, such as test discovery, execution start, and completion. ```java EngineExecutionListener getEngineExecutionListener() ``` -------------------------------- ### Create Launcher Instance - Java Source: https://docs.junit.org/current/api/org.junit.platform.launcher/org/junit/platform/launcher/class-use/Launcher Factory methods for creating a new `Launcher` instance. One method uses the default configuration, while another accepts a custom `LauncherConfig`. ```java Launcher launcher = LauncherFactory.create(); LauncherConfig config = LauncherConfig.builder() .build(); // Customize config as needed Launcher launcherWithConfig = LauncherFactory.create(config); ``` -------------------------------- ### Launcher API Endpoints Source: https://docs.junit.org/current/api/org.junit.platform.launcher/org/junit/platform/launcher/Launcher Documentation for the methods available in the Launcher API. ```APIDOC ## POST /registerLauncherDiscoveryListeners ### Description Registers one or more listeners for test discovery events. ### Method POST ### Endpoint /registerLauncherDiscoveryListeners ### Parameters #### Request Body - **listeners** (LauncherDiscoveryListener[]) - Required - The listeners to be notified of test discovery events; never null or empty ### Request Example ```json { "listeners": [ // Array of LauncherDiscoveryListener objects ] } ``` ### Response #### Success Response (200) - **message** (string) - Indicates successful registration. #### Response Example ```json { "message": "Launcher discovery listeners registered successfully." } ``` ## POST /registerTestExecutionListeners ### Description Registers one or more listeners for test execution events. ### Method POST ### Endpoint /registerTestExecutionListeners ### Parameters #### Request Body - **listeners** (TestExecutionListener[]) - Required - The listeners to be notified of test execution events; never null or empty ### Request Example ```json { "listeners": [ // Array of TestExecutionListener objects ] } ``` ### Response #### Success Response (200) - **message** (string) - Indicates successful registration. #### Response Example ```json { "message": "Test execution listeners registered successfully." } ``` ## POST /discover ### Description Discovers tests and builds a `TestPlan` based on the provided `LauncherDiscoveryRequest`. This method queries all registered engines and collects their results. ### Method POST ### Endpoint /discover ### Parameters #### Request Body - **launcherDiscoveryRequest** (LauncherDiscoveryRequest) - Required - The launcher discovery request; never null ### Request Example ```json { "launcherDiscoveryRequest": { // Details of the LauncherDiscoveryRequest object } } ``` ### Response #### Success Response (200) - **testPlan** (TestPlan) - An unmodifiable `TestPlan` containing all resolved identifiers from registered engines. #### Response Example ```json { "testPlan": { // Details of the TestPlan object } } ``` ### API Note This method may be called to generate a preview of the test tree. The resulting `TestPlan` is unmodifiable and may be passed to `execute(TestPlan, TestExecutionListener...)` for execution at most once. ## POST /execute ### Description Executes a `TestPlan` built according to the supplied `LauncherDiscoveryRequest`. This method queries all registered engines, collects their results, and notifies registered listeners about the progress and results of the execution. ### Method POST ### Endpoint /execute ### Parameters #### Request Body - **launcherDiscoveryRequest** (LauncherDiscoveryRequest) - Required - The launcher discovery request; never null - **listeners** (TestExecutionListener[]) - Required - Additional test execution listeners; never null ### Request Example ```json { "launcherDiscoveryRequest": { // Details of the LauncherDiscoveryRequest object }, "listeners": [ // Array of TestExecutionListener objects ] } ``` ### Response #### Success Response (200) - **message** (string) - Indicates successful execution. #### Response Example ```json { "message": "Test execution initiated successfully." } ``` ### API Note Calling this method will cause test discovery to be executed for all registered engines. If the same `LauncherDiscoveryRequest` was previously passed to `discover(LauncherDiscoveryRequest)`, you should instead call `execute(TestPlan, TestExecutionListener...)` and pass the already acquired `TestPlan` to avoid potential performance degradation (e.g., classpath scanning) of running test discovery twice. ## POST /execute_plan ### Description Executes a supplied `TestPlan` and notifies registered listeners about the progress and results of the execution. ### Method POST ### Endpoint /execute_plan ### Parameters #### Request Body - **testPlan** (TestPlan) - Required - The `TestPlan` to execute. - **listeners** (TestExecutionListener[]) - Optional - Additional test execution listeners. ### Request Example ```json { "testPlan": { // Details of the TestPlan object }, "listeners": [ // Array of TestExecutionListener objects ] } ``` ### Response #### Success Response (200) - **message** (string) - Indicates successful execution. #### Response Example ```json { "message": "Test plan execution initiated successfully." } ``` ``` -------------------------------- ### Composed Annotation using @BeforeAll in Java Source: https://docs.junit.org/current/api/org.junit.jupiter.api/org/junit/jupiter/api/BeforeAll This example shows how @BeforeAll can be used as a meta-annotation to create a custom composed annotation in Java. This allows for reusable test setup configurations by inheriting the semantics of @BeforeAll. ```java import org.junit.jupiter.api.BeforeAll; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @BeforeAll public @interface MyCustomBeforeAll { // Inherits all semantics from @BeforeAll } ``` -------------------------------- ### JUnit Platform @BeforeSuite and @AfterSuite Example Source: https://docs.junit.org/current/user-guide/index Shows how to use @BeforeSuite and @AfterSuite annotations on methods within a @Suite-annotated class. These methods execute once before and after all tests in the suite, respectively. This requires the JUnit Platform Suite API. ```java @Suite @SelectPackages("example") class BeforeAndAfterSuiteDemo { @BeforeSuite static void beforeSuite() { // executes before the test suite } @AfterSuite static void afterSuite() { // executes after the test suite } } ``` -------------------------------- ### Get Wrapper Type for Primitive in JUnit Platform Source: https://docs.junit.org/current/api/index-files/index-7 This static utility method in ReflectionUtils returns the corresponding wrapper class for a given primitive type. For example, it would return `Integer.class` for `int.class`. This is useful for reflection-based operations. ```java /** * Get the wrapper type for the supplied primitive type. */ static Class getWrapperType(Class primitiveType); ``` -------------------------------- ### Get First Indexed Parameter Declaration (Java) Source: https://docs.junit.org/current/api/org.junit.jupiter.params/org/junit/jupiter/params/support/ParameterDeclarations Retrieves the first indexed parameter declaration, if one exists. This is useful for quickly accessing the initial parameter in a parameterized setup. It returns an Optional, which may be empty if no indexed declarations are present. ```Java Optional getFirst() Returns the first _indexed_ parameter declaration, if available; never `null`. ``` -------------------------------- ### Java @BeforeEach Annotation Example Source: https://docs.junit.org/current/api/org.junit.jupiter.api/org/junit/jupiter/api/BeforeEach Demonstrates the usage of the @BeforeEach annotation in JUnit 5 for setup methods executed before each test. Methods annotated with @BeforeEach must have a void return type and cannot be static. They can optionally accept parameters resolved by ParameterResolvers. ```java import org.junit.jupiter.api.BeforeEach; public class ExampleTest { @BeforeEach void setUp() { System.out.println("Setting up before each test..."); // Initialize test resources here } @Test void testSomething() { // Test logic System.out.println("Running testSomething..."); } @Test void anotherTest() { // Another test logic System.out.println("Running anotherTest..."); } } ``` -------------------------------- ### Configure JUnit Platform via Console Launcher Source: https://docs.junit.org/current/user-guide/index Shows how to specify configuration parameters when running tests using the JUnit Platform's Console Launcher. This method utilizes command-line arguments to pass custom settings to the test engine, listener, or extensions. It is useful for setting parameters directly from the terminal. ```bash # Specify a single configuration parameter java -jar junit-platform-console-standalone.jar --config key1=value1 # Specify multiple configuration parameters java -jar junit-platform-console-standalone.jar --config key2=value2 --config key3=value3 # Specify a configuration resource file java -jar junit-platform-console-standalone.jar --config-resource /path/to/config.properties ``` -------------------------------- ### Create DefaultJupiterConfiguration with OutputDirectoryProvider Source: https://docs.junit.org/current/api/org.junit.platform.engine/org/junit/platform/engine/reporting/class-use/OutputDirectoryProvider Illustrates the creation of a `DefaultJupiterConfiguration` by passing a `ConfigurationParameters` object and an `OutputDirectoryProvider`. This constructor is used to initialize the configuration with a specific output directory provider. ```java /** * Constructs a new DefaultJupiterConfiguration. * * @param configurationParameters The configuration parameters. * @param outputDirectoryProvider The output directory provider. */ public DefaultJupiterConfiguration(ConfigurationParameters configurationParameters, OutputDirectoryProvider outputDirectoryProvider); ``` -------------------------------- ### Get Test Execution Summary Counts - JUnit Platform Launcher Source: https://docs.junit.org/current/api/index-files/index-7 Provides methods to retrieve various counts from the test execution summary. These include the number of tests aborted, failed, found, skipped, started, succeeded, and the total failure count. ```java /** * Get the number of tests aborted. */ long getTestsAbortedCount(); /** * Get the number of tests that failed. */ long getTestsFailedCount(); /** * Get the number of tests found. */ long getTestsFoundCount(); /** * Get the number of tests skipped. */ long getTestsSkippedCount(); /** * Get the number of tests started. */ long getTestsStartedCount(); /** * Get the number of tests that succeeded. */ long getTestsSucceededCount(); /** * Get the total number of failed containers and failed tests. */ long getTotalFailureCount(); ``` -------------------------------- ### HttpServer Resource Implementation with AutoCloseable Source: https://docs.junit.org/current/user-guide/index This Java code defines a HttpServerResource that implements the AutoCloseable interface. It sets up an HTTP server with an example handler and provides a start method to begin the server and a close method to stop it. This allows for proper resource management within JUnit extensions. ```java class HttpServerResource implements AutoCloseable { private final HttpServer httpServer; HttpServerResource(int port) throws IOException { InetAddress loopbackAddress = InetAddress.getLoopbackAddress(); this.httpServer = HttpServer.create(new InetSocketAddress(loopbackAddress, port), 0); } HttpServer getHttpServer() { return httpServer; } void start() { // Example handler httpServer.createContext("/example", exchange -> { String body = "This is a test"; exchange.sendResponseHeaders(200, body.length()); try (OutputStream os = exchange.getResponseBody()) { os.write(body.getBytes(UTF_8)); } }); httpServer.setExecutor(null); httpServer.start(); } @Override public void close() { httpServer.stop(0); } } ``` -------------------------------- ### Initialize LauncherDiscoveryRequestBuilder (Java) Source: https://docs.junit.org/current/api/org.junit.platform.launcher/org/junit/platform/launcher/core/LauncherDiscoveryRequestBuilder Creates a new instance of the LauncherDiscoveryRequestBuilder. This is the starting point for building a discovery request. It is deprecated and suggests using the `request()` method instead. ```Java @API(status=DEPRECATED, since="1.8") @Deprecated public LauncherDiscoveryRequestBuilder() ``` ```Java public static LauncherDiscoveryRequestBuilder request() ``` -------------------------------- ### SummaryGeneratingListener Constructor Source: https://docs.junit.org/current/api/org.junit.platform.launcher/org/junit/platform/launcher/listeners/SummaryGeneratingListener Initializes a new instance of the SummaryGeneratingListener. ```APIDOC ## SummaryGeneratingListener Constructor ### Description Initializes a new instance of the SummaryGeneratingListener. ### Method `public SummaryGeneratingListener()` ### Endpoint N/A (Constructor) ### Parameters None ### Request Example ```java SummaryGeneratingListener listener = new SummaryGeneratingListener(); ``` ### Response N/A (Constructor) ``` -------------------------------- ### Java HttpServerResource Implementing AutoCloseable Source: https://docs.junit.org/current/user-guide This Java class implements the `AutoCloseable` interface to manage an `HttpServer` resource. It handles server creation, starting with an example handler, and ensures proper shutdown via the `close()` method. This is useful for resources that need to be managed within the JUnit extension lifecycle. ```java class HttpServerResource implements AutoCloseable { private final HttpServer httpServer; HttpServerResource(int port) throws IOException { InetAddress loopbackAddress = InetAddress.getLoopbackAddress(); this.httpServer = HttpServer.create(new InetSocketAddress(loopbackAddress, port), 0); } HttpServer getHttpServer() { return httpServer; } void start() { // Example handler httpServer.createContext("/example", exchange -> { String body = "This is a test"; exchange.sendResponseHeaders(200, body.length()); try (OutputStream os = exchange.getResponseBody()) { os.write(body.getBytes(UTF_8)); } }); httpServer.setExecutor(null); httpServer.start(); } @Override public void close() { httpServer.stop(0); } } ``` -------------------------------- ### Parameterized Test with @CsvSource Custom Delimiters and Quotes Source: https://docs.junit.org/current/user-guide/index Shows how to configure @CsvSource to use custom delimiters (e.g., '|') and quote characters (e.g., '"'). This example also utilizes a text block for the CSV data, includes comments within the text block (lines starting with '#'), and demonstrates custom formatting for readability. ```java import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.CsvSource; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNotEquals; class CsvSourceCustomDelimiterTest { @ParameterizedTest @CsvSource(delimiter = '|', quoteCharacter = '"', textBlock = """ #----------------------------- # FRUIT | RANK #----------------------------- apple | 1 #----------------------------- banana | 2 #----------------------------- "lemon lime" | 0xF1 #----------------------------- strawberry | 700_000 #----------------------------- """) void testWithCsvSource(String fruit, int rank) { // Test logic here assertNotNull(fruit); assertNotEquals(0, rank); } } ``` -------------------------------- ### Create Launcher Instance with Config (Java) Source: https://docs.junit.org/current/api/org.junit.platform.launcher/org/junit/platform/launcher/core/LauncherFactory Factory method for creating a new Launcher using a supplied LauncherConfig. This provides full control over automatic registration and programmatic registration of test engines and listeners. It throws a PreconditionViolationException if the configuration is null or no test engines are detected. ```java @API(status=STABLE, since="1.10") public static Launcher create(LauncherConfig config) throws PreconditionViolationException ``` -------------------------------- ### Use Custom Temp Directory Factory Source: https://docs.junit.org/current/user-guide This snippet demonstrates how to provide a custom factory for creating temporary directories using the `factory` attribute of the @TempDir annotation. The custom factory can control aspects like the parent directory or the file system used. The example factory ensures the directory name starts with the test method name. ```java import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtensionContext; import org.junit.jupiter.api.extension.ParameterContext; import org.junit.jupiter.api.extension.ParameterResolutionException; import org.junit.jupiter.api.extension.support.TypeBasedArgumentsAccessor; import org.junit.jupiter.api.io.TempDir; import org.junit.jupiter.api.io.TempDirFactory; import org.junit.jupiter.api.io.AnnotatedElementContext; import java.io.IOException; import java.lang.reflect.Parameter; import java.nio.file.Files; import java.nio.file.Path; import static org.junit.jupiter.api.Assertions.assertTrue; class TempDirFactoryDemo { @Test void factoryTest(@TempDir(factory = TempDirFactoryDemo.Factory.class) Path tempDir) { assertTrue(tempDir.getFileName().toString().startsWith("factoryTest")); System.out.println("Custom temp dir created: " + tempDir); } static class Factory implements TempDirFactory { @Override public Path createTempDirectory(AnnotatedElementContext elementContext, ExtensionContext extensionContext) throws IOException { String prefix = elementContext.getElement().map(element -> { if (element instanceof Parameter) { return ((Parameter) element).getDeclaringExecutable().getName(); } // Handle other element types if necessary, e.g., Field return "junit-factory"; }).orElse("junit-factory"); // Use Files.createTempDirectory with a custom prefix based on test method name return Files.createTempDirectory(prefix + "-"); } // The close() method is called by the extension after the test. // For this example, we don't need to do anything specific here. @Override public void close() throws IOException { // Cleanup logic if needed, though @TempDir handles directory deletion by default } } } ``` -------------------------------- ### Create JUnit Launcher with Default Configuration Source: https://docs.junit.org/current/api/org.junit.platform.commons/org/junit/platform/commons/class-use/PreconditionViolationException Factory method to create a new Launcher instance using the default LauncherConfig. This is the simplest way to obtain a Launcher. ```java static Launcher LauncherFactory.create() ``` -------------------------------- ### Runtime Configuration Options Source: https://docs.junit.org/current/user-guide/index Options for configuring the classpath and setting runtime parameters for test discovery and execution. These are essential for including necessary libraries and engine dependencies. ```bash # Add a directory to the classpath for engines and dependencies java -jar junit-console.jar --classpath="lib/my-engine.jar:lib/dependency.jar" # Set configuration parameters via a resource file java -jar junit-console.jar --config-resource="junit-config.properties" # Set a specific configuration parameter java -jar junit-console.jar --config="junit.extensions.autodetection.enabled=true" ``` -------------------------------- ### Static Shared Resources Declaration with @ResourceLock in Java Source: https://docs.junit.org/current/user-guide Demonstrates how to declare shared resources statically using the @ResourceLock annotation in JUnit Jupiter. This example shows how to lock the system properties for concurrent execution, ensuring that tests requiring READ or READ_WRITE access to system properties do not conflict when run in parallel. It includes setup and teardown methods to manage system properties. ```java @Execution(CONCURRENT) class StaticSharedResourcesDemo { private Properties backup; @BeforeEach void backup() { backup = new Properties(); backup.putAll(System.getProperties()); } @AfterEach void restore() { System.setProperties(backup); } @Test @ResourceLock(value = SYSTEM_PROPERTIES, mode = READ) void customPropertyIsNotSetByDefault() { assertNull(System.getProperty("my.prop")); } @Test @ResourceLock(value = SYSTEM_PROPERTIES, mode = READ_WRITE) void canSetCustomPropertyToApple() { System.setProperty("my.prop", "apple"); assertEquals("apple", System.getProperty("my.prop")); } @Test @ResourceLock(value = SYSTEM_PROPERTIES, mode = READ_WRITE) void canSetCustomPropertyToBanana() { System.setProperty("my.prop", "banana"); assertEquals("banana", System.getProperty("my.prop")); } } ``` -------------------------------- ### VintageTestEngine Constructor (Java) Source: https://docs.junit.org/current/api/org.junit.vintage.engine/org/junit/vintage/engine/VintageTestEngine Initializes a new instance of the VintageTestEngine. This is the default constructor and does not require any parameters. ```java public VintageTestEngine() ``` -------------------------------- ### Execution Started Listener (Java) Source: https://docs.junit.org/current/api/org.junit.platform.launcher/org/junit/platform/launcher/class-use/TestIdentifier Handles the event when a test or container execution is starting. Implemented by listeners such as LoggingListener and SummaryGeneratingListener, this method receives the TestIdentifier of the test/container that is about to start execution. ```java void executionStarted(TestIdentifier testIdentifier) ``` -------------------------------- ### JUnit 5: Specify Expected Started Events Count Source: https://docs.junit.org/current/api/index-files/index-19 An overload of the `started` method in `EventStatistics` that allows specifying the expected number of `STARTED` events. This is helpful for verifying test counts. ```java EventStatistics.started(long) ``` -------------------------------- ### SuiteTestEngine Constructor Source: https://docs.junit.org/current/api/org.junit.platform.suite.engine/org/junit/platform/suite/engine/SuiteTestEngine Initializes a new instance of the SuiteTestEngine. This constructor is part of the core setup for the test engine. ```java public SuiteTestEngine() ``` -------------------------------- ### Dynamic Shared Resources Declaration with ResourceLocksProvider in Java Source: https://docs.junit.org/current/user-guide Illustrates how to dynamically add shared resources at runtime using a custom implementation of the ResourceLocksProvider interface. This example configures the test class to use dynamic resource locks for system properties, determining the access mode (READ or READ_WRITE) based on the test method name. It includes setup and teardown for managing system properties. ```java @Execution(CONCURRENT) @ResourceLock(providers = DynamicSharedResourcesDemo.Provider.class) class DynamicSharedResourcesDemo { private Properties backup; @BeforeEach void backup() { backup = new Properties(); backup.putAll(System.getProperties()); } @AfterEach void restore() { System.setProperties(backup); } @Test void customPropertyIsNotSetByDefault() { assertNull(System.getProperty("my.prop")); } @Test void canSetCustomPropertyToApple() { System.setProperty("my.prop", "apple"); assertEquals("apple", System.getProperty("my.prop")); } @Test void canSetCustomPropertyToBanana() { System.setProperty("my.prop", "banana"); assertEquals("banana", System.getProperty("my.prop")); } static class Provider implements ResourceLocksProvider { @Override public Set provideForMethod(List> enclosingInstanceTypes, Class testClass, Method testMethod) { ResourceAccessMode mode = testMethod.getName().startsWith("canSet") ? READ_WRITE : READ; return Collections.singleton(new Lock(SYSTEM_PROPERTIES, mode)); } } } ``` -------------------------------- ### Create LauncherConfig.Builder Source: https://docs.junit.org/current/api/org.junit.platform.launcher/org/junit/platform/launcher/core/class-use/LauncherConfig This snippet shows how to create a new instance of the LauncherConfig.Builder using the static builder() method. This builder is the entry point for configuring the LauncherConfig. ```java LauncherConfig.Builder builder = LauncherConfig.builder(); ```