org.junit.platform.launcher.core.LauncherDiscoveryRequestBuilder Java Examples

The following examples show how to use org.junit.platform.launcher.core.LauncherDiscoveryRequestBuilder. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RunSellContractTests.java    From btdex with GNU General Public License v3.0 6 votes vote down vote up
public static void main(String[] args) {
    LauncherDiscoveryRequest request = LauncherDiscoveryRequestBuilder.request()
            .selectors(
                    selectPackage("btdex.sellContract.dispute"),
                    selectClass(TestTakeRetake.class),
                    selectClass(TestInvalidTakeTake.class),
                    selectClass(TestInvalidTakeReopenWithdraw.class)
            )
            .build();

    Launcher launcher = LauncherFactory.create();
    // Register a listener
    SummaryGeneratingListener listener = new SummaryGeneratingListener();
    launcher.registerTestExecutionListeners(listener);

    //TestPlan testPlan = launcher.discover(request);

    launcher.execute(request);

    TestExecutionSummary summary = listener.getSummary();
    printReport(summary);


}
 
Example #2
Source File: VertxExtensionTest.java    From vertx-junit5 with Apache License 2.0 6 votes vote down vote up
@Test
@DisplayName("⚙️ Check a timeout diagnosis")
void checkTimeoutFailureTestWithIntermediateAsyncVerifier() {
  LauncherDiscoveryRequest request = LauncherDiscoveryRequestBuilder.request()
    .selectors(selectClass(EmbeddedWithARunner.TimingOut.class))
    .build();
  Launcher launcher = LauncherFactory.create();
  SummaryGeneratingListener listener = new SummaryGeneratingListener();
  launcher.registerTestExecutionListeners(listener);
  launcher.execute(request);
  TestExecutionSummary summary = listener.getSummary();
  assertThat(summary.getTestsStartedCount()).isEqualTo(1);
  assertThat(summary.getTestsFailedCount()).isEqualTo(1);
  Throwable exception = summary.getFailures().get(0).getException();
  assertThat(exception)
    .isInstanceOf(TimeoutException.class)
    .hasMessageContaining("checkpoint in file VertxExtensionTest.java");
}
 
Example #3
Source File: RunJUnit5TestsFromJava.java    From tutorials with MIT License 5 votes vote down vote up
public void runAll() {
    LauncherDiscoveryRequest request = LauncherDiscoveryRequestBuilder
      .request()
      .selectors(selectPackage("com.baeldung.runfromjava"))
      .filters(includeClassNamePatterns(".*Test"))
      .build();
    Launcher launcher = LauncherFactory.create();

    TestPlan testPlan = launcher.discover(request);

    launcher.registerTestExecutionListeners(listener);

    launcher.execute(request);
}
 
Example #4
Source File: JUnit5Tests.java    From quickperf with Apache License 2.0 5 votes vote down vote up
public static JUnit5Tests createInstance(Class<?> testClass) {
    SummaryGeneratingListener listener = new SummaryGeneratingListener();
    LauncherDiscoveryRequest request =
            LauncherDiscoveryRequestBuilder.request()
            .selectors(selectClass(testClass))
            .build();
    Launcher launcher = LauncherFactory.create();
    launcher.registerTestExecutionListeners(listener);
    return new JUnit5Tests(launcher, request, listener);
}
 
Example #5
Source File: RunJUnit5TestsFromJava.java    From tutorials with MIT License 5 votes vote down vote up
public void runOne() {
    LauncherDiscoveryRequest request = LauncherDiscoveryRequestBuilder
      .request()
      .selectors(selectClass(FirstUnitTest.class))
      .build();
    Launcher launcher = LauncherFactory.create();
    TestPlan testPlan = launcher.discover(request);

    launcher.registerTestExecutionListeners(listener);
    launcher.execute(request);
}
 
Example #6
Source File: TestLauncher.java    From tutorials with MIT License 5 votes vote down vote up
public static void main(String[] args) {

        //@formatter:off
        LauncherDiscoveryRequest request = LauncherDiscoveryRequestBuilder.request()
                .selectors(selectClass("com.baeldung.EmployeesUnitTest"))
                .configurationParameter("junit.conditions.deactivate", "com.baeldung.extensions.*")
                .configurationParameter("junit.jupiter.extensions.autodetection.enabled", "true")
                .build();
        
        //@formatter:on

        TestPlan plan = LauncherFactory.create()
            .discover(request);
        Launcher launcher = LauncherFactory.create();
        SummaryGeneratingListener summaryGeneratingListener = new SummaryGeneratingListener();
        launcher.execute(request, new TestExecutionListener[] { summaryGeneratingListener });
        launcher.execute(request);

        summaryGeneratingListener.getSummary()
            .printTo(new PrintWriter(System.out));

    }
 
Example #7
Source File: TesterRunner.java    From pro with GNU General Public License v3.0 5 votes vote down vote up
private static int launchJUnitPlatform(TestConf testConf) {
  var moduleName = testConf.moduleName();
  var moduleNameAndVersion = testConf.moduleNameAndVersion();
  var parallel = testConf.parallel();
  var includeTags = testConf.includeTags();
  var excludeTags = testConf.excludeTags();

  // Create Launcher API entry point
  // https://junit.org/junit5/docs/current/user-guide/#launcher-api
  var builder = LauncherDiscoveryRequestBuilder.request();

  // Select from...
  var packages = testConf.packages();
  if (packages.isEmpty()) {
    builder.selectors(selectModule(moduleName));
  } else {
    builder.selectors(packages.stream().map(DiscoverySelectors::selectPackage).collect(toUnmodifiableList()));  
  }

  // Apply filters...
  if (!includeTags.isEmpty()) {
    builder.filters(TagFilter.includeTags(includeTags));
  }
  if (!excludeTags.isEmpty()) {
    builder.filters(TagFilter.excludeTags(excludeTags));
  }

  // Fine-tune configuration...
  builder.configurationParameter("junit.jupiter.execution.parallel.enabled", Boolean.toString(parallel));

  var launcher = LauncherFactory.create();
  var launcherDiscoveryRequest = builder.build();
  var summaryGeneratingListener = new SummaryGeneratingListener();
  var xmlReportsWritingListener = new LegacyXmlReportGeneratingListener(testConf.reportPath().resolve(moduleName), new PrintWriter(System.out));
  launcher.registerTestExecutionListeners(summaryGeneratingListener);
  launcher.registerTestExecutionListeners(xmlReportsWritingListener);
  var startTimeMillis = System.currentTimeMillis();
  launcher.execute(launcherDiscoveryRequest);
  var duration = System.currentTimeMillis() - startTimeMillis;
  var summary = summaryGeneratingListener.getSummary();
  
  // DEBUG
  //summary.printTo(new PrintWriter(System.out));
  
  var success = summary.getTestsFailedCount() == 0 && summary.getTestsAbortedCount() == 0 &&
                summary.getContainersFailedCount() == 0 && summary.getContainersAbortedCount() == 0;
  if (success) {
    var succeeded = summary.getTestsSucceededCount();
    System.out.printf("[tester] Successfully tested %s: %d tests in %d ms%n", moduleNameAndVersion, succeeded, duration);
  } else {
    var writer = new PrintWriter(System.err);
    summary.printTo(writer);
    summary.printFailuresTo(writer);
  }
  return success? 0: 1;
}
 
Example #8
Source File: JunitRunner.java    From vespa with Apache License 2.0 5 votes vote down vote up
public String executeTests(List<Class<?>> testClasses) {
    LauncherDiscoveryRequest discoveryRequest = LauncherDiscoveryRequestBuilder.request()
            .selectors(
                    testClasses.stream().map(DiscoverySelectors::selectClass).collect(Collectors.toList())
            )
            .build();

    var launcherConfig = LauncherConfig.builder()
            .addTestEngines(new JupiterTestEngine())

            .build();
    Launcher launcher = LauncherFactory.create(launcherConfig);

    // Create log listener:
    var logLines = new ArrayList<String>();
    var logListener = LoggingListener.forBiConsumer((t, m) -> log(logLines, m.get(), t));
    // Create a summary listener:
    var summaryListener = new SummaryGeneratingListener();
    launcher.registerTestExecutionListeners(logListener, summaryListener);

    // Execute request
    launcher.execute(discoveryRequest);

    var report = summaryListener.getSummary();

    return createJsonTestReport(report, logLines);
}
 
Example #9
Source File: JupiterLoadProcessor.java    From zerocode with Apache License 2.0 5 votes vote down vote up
private Runnable createJupiterRunnable(Class<?> testClass, String testMethod) {
    return () -> {

        LOGGER.info(Thread.currentThread().getName() + "\n - Parallel Junit5 test- *Start-Time = " + now());

        final LauncherDiscoveryRequest request = LauncherDiscoveryRequestBuilder.request()
                .selectors(selectMethod(testClass, testMethod))
                .build();
        final Launcher launcher = LauncherFactory.create();

        // -------------------------
        // Register Report listener
        // -------------------------
        registerReportListener(testClass, testMethod, launcher);

        // ------------------------------
        // Register Test-Summary listener
        // ------------------------------
        final SummaryGeneratingListener summaryListener = new SummaryGeneratingListener();
        launcher.registerTestExecutionListeners(summaryListener);

        launcher.execute(request);
        LOGGER.info(Thread.currentThread().getName() + "\n   - Parallel Junit5 test- *End-Time = " + now());

        updatePassFailCount(summaryListener);

    };
}
 
Example #10
Source File: VertxExtensionTest.java    From vertx-junit5 with Apache License 2.0 5 votes vote down vote up
@Test
@DisplayName("⚙️ Check a test failure with an intermediate async result verifier")
void checkFailureTestWithIntermediateAsyncVerifier() {
  LauncherDiscoveryRequest request = LauncherDiscoveryRequestBuilder.request()
    .selectors(selectClass(FailureWithIntermediateAsyncVerifierTest.class))
    .build();
  Launcher launcher = LauncherFactory.create();
  SummaryGeneratingListener listener = new SummaryGeneratingListener();
  launcher.registerTestExecutionListeners(listener);
  launcher.execute(request);
  TestExecutionSummary summary = listener.getSummary();
  assertThat(summary.getTestsStartedCount()).isEqualTo(1);
  assertThat(summary.getTestsFailedCount()).isEqualTo(1);
  assertThat(summary.getFailures().get(0).getException()).isInstanceOf(AssertionError.class);
}
 
Example #11
Source File: VertxExtensionTest.java    From vertx-junit5 with Apache License 2.0 5 votes vote down vote up
@Test
@DisplayName("⚙️ Check a failure in the test method body rather than in a callback")
void checkDirectFailure() {
  LauncherDiscoveryRequest request = LauncherDiscoveryRequestBuilder.request()
    .selectors(selectClass(DirectFailureTest.class))
    .build();
  Launcher launcher = LauncherFactory.create();
  SummaryGeneratingListener listener = new SummaryGeneratingListener();
  launcher.registerTestExecutionListeners(listener);
  launcher.execute(request);
  TestExecutionSummary summary = listener.getSummary();
  assertThat(summary.getTestsStartedCount()).isEqualTo(1);
  assertThat(summary.getTestsFailedCount()).isEqualTo(1);
  assertThat(summary.getFailures().get(0).getException()).isInstanceOf(RuntimeException.class);
}
 
Example #12
Source File: VertxExtensionTest.java    From vertx-junit5 with Apache License 2.0 5 votes vote down vote up
@Test
@DisplayName("⚙️ Check a test failure")
void checkFailureTest() {
  LauncherDiscoveryRequest request = LauncherDiscoveryRequestBuilder.request()
    .selectors(selectClass(FailureTest.class))
    .build();
  Launcher launcher = LauncherFactory.create();
  SummaryGeneratingListener listener = new SummaryGeneratingListener();
  launcher.registerTestExecutionListeners(listener);
  launcher.execute(request);
  TestExecutionSummary summary = listener.getSummary();
  assertThat(summary.getTestsStartedCount()).isEqualTo(1);
  assertThat(summary.getTestsFailedCount()).isEqualTo(1);
  assertThat(summary.getFailures().get(0).getException()).isInstanceOf(AssertionError.class);
}
 
Example #13
Source File: TestHelper.java    From sbt-jupiter-interface with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new test plan helper for a specific test class.
 *
 * @param testClass The name of the test class.
 * @return A new test helper instance.
 */
public static TestHelper of(String testClass) {

    LauncherDiscoveryRequest request = LauncherDiscoveryRequestBuilder.request()
            .selectors(selectClass(testClass))
            .build();

    final TestPlan testPlan = LauncherFactory.create().discover(request);

    return new TestHelper(testPlan);
}
 
Example #14
Source File: JupiterTestCollector.java    From sbt-jupiter-interface with Apache License 2.0 5 votes vote down vote up
/**
 * Executes a JUnit Jupiter test discovery and collects the result.
 *
 * @return The result of discovered tests.
 */
private Result collectTests0() {

    Set<Path> classPathRoots = new HashSet<>();
    classPathRoots.add(Paths.get(classDirectory.getAbsolutePath()));

    LauncherDiscoveryRequest request = LauncherDiscoveryRequestBuilder.request()
            .selectors(selectClasspathRoots(classPathRoots))
            .selectors(selectDirectory(classDirectory))
            .build();

    TestPlan testPlan = LauncherFactory.create().discover(request);

    Result result = new Result();

    for (TestIdentifier rootIdentifier : testPlan.getRoots()) {

        for (TestIdentifier identifier : testPlan.getChildren(rootIdentifier)) {

            String fqn = fullyQualifiedName(identifier);
            Selector selector = new SuiteSelector();

            Item item = new Item();
            item.fullyQualifiedClassName = fqn;
            item.selectors.add(selector);
            item.explicit = false;

            result.discoveredTests.add(item);
        }
    }

    return result;
}
 
Example #15
Source File: LauncherApiExample.java    From Mastering-Software-Testing-with-JUnit-5 with MIT License 5 votes vote down vote up
@SuppressWarnings("unused")
public static void main(String[] args) {
    // Discover and filter tests
    LauncherDiscoveryRequest request = LauncherDiscoveryRequestBuilder
            .request()
            .selectors(selectPackage("io.github.bonigarcia"),
                    selectClass(DummyTest.class))
            .filters(includeClassNamePatterns(".*Test")).build();

    Launcher launcher = LauncherFactory.create();
    TestPlan plan = launcher.discover(request);

    // Executing tests
    TestExecutionListener listener = new SummaryGeneratingListener();
    launcher.registerTestExecutionListeners(listener);

    launcher.execute(request, listener);
}
 
Example #16
Source File: ExtensionTester.java    From junit5-extensions with MIT License 5 votes vote down vote up
public static TestPlanExecutionReport runTests(Class<?> clazz) {
  Launcher launcher = LauncherFactory.create();
  LauncherDiscoveryRequest request = LauncherDiscoveryRequestBuilder.request()
      .selectors(selectClass(clazz))
      .build();

  ExecutionReportListener listener = new ExecutionReportListener().addClassToSkip(clazz);
  launcher.execute(request, listener);
  return listener.getReport();
}
 
Example #17
Source File: AllureJunitPlatformTest.java    From allure-java with Apache License 2.0 5 votes vote down vote up
@Step("Run classes {classes}")
private AllureResults runClasses(final Class<?>... classes) {
    final AllureResultsWriterStub writerStub = new AllureResultsWriterStub();
    final AllureLifecycle lifecycle = new AllureLifecycle(writerStub);

    final ClassSelector[] classSelectors = Stream.of(classes)
            .map(DiscoverySelectors::selectClass)
            .toArray(ClassSelector[]::new);

    final LauncherDiscoveryRequest request = LauncherDiscoveryRequestBuilder.request()
            .selectors(classSelectors)
            .build();

    final LauncherConfig config = LauncherConfig.builder()
            .enableTestExecutionListenerAutoRegistration(false)
            .addTestExecutionListeners(new AllureJunitPlatform(lifecycle))
            .build();
    final Launcher launcher = LauncherFactory.create(config);

    final AllureLifecycle defaultLifecycle = Allure.getLifecycle();
    try {
        Allure.setLifecycle(lifecycle);
        StepsAspects.setLifecycle(lifecycle);
        AttachmentsAspects.setLifecycle(lifecycle);
        launcher.execute(request);
        return writerStub;
    } finally {
        Allure.setLifecycle(defaultLifecycle);
        StepsAspects.setLifecycle(defaultLifecycle);
        AttachmentsAspects.setLifecycle(defaultLifecycle);
    }
}
 
Example #18
Source File: AllureJunit5Test.java    From allure-java with Apache License 2.0 5 votes vote down vote up
@Step("Run classes {classes}")
private AllureResults runClasses(final Class<?>... classes) {
    final AllureResultsWriterStub writerStub = new AllureResultsWriterStub();
    final AllureLifecycle lifecycle = new AllureLifecycle(writerStub);

    final ClassSelector[] classSelectors = Stream.of(classes)
            .map(DiscoverySelectors::selectClass)
            .toArray(ClassSelector[]::new);

    final LauncherDiscoveryRequest request = LauncherDiscoveryRequestBuilder.request()
            .configurationParameter("junit.jupiter.extensions.autodetection.enabled", "true")
            .selectors(classSelectors)
            .build();

    final LauncherConfig config = LauncherConfig.builder()
            .enableTestExecutionListenerAutoRegistration(false)
            .addTestExecutionListeners(new AllureJunitPlatform(lifecycle))
            .build();
    final Launcher launcher = LauncherFactory.create(config);

    final AllureLifecycle defaultLifecycle = Allure.getLifecycle();
    try {
        Allure.setLifecycle(lifecycle);
        StepsAspects.setLifecycle(lifecycle);
        AttachmentsAspects.setLifecycle(lifecycle);
        launcher.execute(request);
        return writerStub;
    } finally {
        Allure.setLifecycle(defaultLifecycle);
        StepsAspects.setLifecycle(defaultLifecycle);
        AttachmentsAspects.setLifecycle(defaultLifecycle);
    }
}
 
Example #19
Source File: JupiterRunner.java    From sbt-jupiter-interface with Apache License 2.0 4 votes vote down vote up
Task[] execute() {

            String testSuiteName = taskDef.fullyQualifiedName();

            Configuration configuration = new Configuration(testSuiteName, loggers, options);
            Dispatcher dispatcher = new Dispatcher(configuration, eventHandler);

            SummaryPrintingTestListener summaryListener = new SummaryPrintingTestListener(configuration);
            TestExecutionListener outputCapturingListener = new OutputCapturingTestListener(
                    configuration, systemStreamPair);

            JupiterTestListener testListener = configuration.getTestListener();

            try
            {
                LauncherDiscoveryRequestBuilder builder = LauncherDiscoveryRequestBuilder.request();
                builder.selectors(testSelector(testSuiteName));
                builder.filters(testFilters(dispatcher));

                Launcher launcher = LauncherFactory.create();

                launcher.registerTestExecutionListeners(dispatcher);
                launcher.registerTestExecutionListeners(outputCapturingListener);
                launcher.registerTestExecutionListeners(summaryListener);
                launcher.registerTestExecutionListeners(testListener);

                configuration.createRunListener(testClassLoader)
                        .ifPresent(launcher::registerTestExecutionListeners);

                launcher.execute(builder.build(), new TestExecutionListener[0]);

                return new Task[0];
            }
            catch (Throwable t) {
                dispatcher.executionFailed(testSuiteName, t);
                t.printStackTrace();
                return new Task[0];
            }
        }
 
Example #20
Source File: JkTestSelection.java    From jeka with Apache License 2.0 4 votes vote down vote up
public JkUnaryOperator<LauncherDiscoveryRequestBuilder> getDiscoveryConfigurer() {
    return discoveryConfigurer;
}
 
Example #21
Source File: LauncherApiExample.java    From mastering-junit5 with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unused")
public static void main(String[] args) {
    // Discover and filter tests
    LauncherDiscoveryRequest request = LauncherDiscoveryRequestBuilder
            .request()
            .selectors(selectPackage("io.github.bonigarcia"),
                    selectClass(DummyTest.class))
            .filters(includeClassNamePatterns(".*Test")).build();

    Launcher launcher = LauncherFactory.create();
    TestPlan plan = launcher.discover(request);

    // Executing tests
    TestExecutionListener listener = new SummaryGeneratingListener();
    launcher.registerTestExecutionListeners(listener);

    launcher.execute(request, listener);
}
 
Example #22
Source File: JkTestSelection.java    From jeka with Apache License 2.0 2 votes vote down vote up
/**
 * Set a native Junit-platform configurer to build the {@link org.junit.platform.launcher.LauncherDiscoveryRequest}
 * passed to Junit-platform. The configurer will apply on a builder instance created from
 * patterns, tags and class root dirs defined in this instance.
 * <pre>
 *     <code>
 *         setDiscoveryConfigurer(classpath, builder -> builder
 *                 .filters(
 *                         ClassNameFilter.includeClassNamePatterns(ClassNameFilter.STANDARD_INCLUDE_PATTERN)
 *                 )
 *                 .selectors(DiscoverySelectors.selectMethod("mytest.MyTest#toto"))
 *                 .configurationParameter("run.it", "false")
 *         );
 *     </code>
 * </pre>
 */
public JkTestSelection<T> setDiscoveryConfigurer(JkUnaryOperator<LauncherDiscoveryRequestBuilder> discoveryConfigurer) {
    this.discoveryConfigurer = discoveryConfigurer;
    return this;
}