org.junit.platform.launcher.Launcher Java Examples

The following examples show how to use org.junit.platform.launcher.Launcher. 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: ParallelExecutionSpringExtensionTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@RepeatedTest(10)
void runTestsInParallel() {
	Launcher launcher = LauncherFactory.create();
	SummaryGeneratingListener listener = new SummaryGeneratingListener();
	launcher.registerTestExecutionListeners(listener);

	LauncherDiscoveryRequest request = request()//
			.configurationParameter("junit.jupiter.execution.parallel.enabled", "true")//
			.configurationParameter("junit.jupiter.execution.parallel.config.dynamic.factor", "10")//
			.selectors(selectClass(TestCase.class))//
			.build();

	launcher.execute(request);

	assertEquals(NUM_TESTS, listener.getSummary().getTestsSucceededCount(),
			"number of tests executed successfully");
}
 
Example #2
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 #3
Source File: ParallelExecutionSpringExtensionTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@RepeatedTest(10)
void runTestsInParallel() {
	Launcher launcher = LauncherFactory.create();
	SummaryGeneratingListener listener = new SummaryGeneratingListener();
	launcher.registerTestExecutionListeners(listener);

	LauncherDiscoveryRequest request = request()//
			.configurationParameter("junit.jupiter.execution.parallel.enabled", "true")//
			.configurationParameter("junit.jupiter.execution.parallel.config.dynamic.factor", "10")//
			.selectors(selectClass(TestCase.class))//
			.build();

	launcher.execute(request);

	assertEquals(NUM_TESTS, listener.getSummary().getTestsSucceededCount(),
			"number of tests executed successfully");
}
 
Example #4
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 #5
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 #6
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 #7
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 #8
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 #9
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 #10
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 #11
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 #12
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 #13
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 #14
Source File: JUnit5Tests.java    From quickperf with Apache License 2.0 5 votes vote down vote up
private JUnit5Tests(Launcher launcher
                  , LauncherDiscoveryRequest request
                  , SummaryGeneratingListener listener) {
    this.launcher = launcher;
    this.request = request;
    this.listener = listener;
}
 
Example #15
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 #16
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 #17
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 #18
Source File: FailingBeforeAndAfterMethodsSpringExtensionTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
private void runTestAndAssertCounters(Class<?> testClass) {
	Launcher launcher = LauncherFactory.create();
	ExceptionTrackingListener listener = new ExceptionTrackingListener();
	launcher.registerTestExecutionListeners(listener);

	launcher.execute(request().selectors(selectClass(testClass)).build());
	TestExecutionSummary summary = listener.getSummary();

	String name = testClass.getSimpleName();
	int expectedStartedCount = getExpectedStartedCount(testClass);
	int expectedSucceededCount = getExpectedSucceededCount(testClass);
	int expectedFailedCount = getExpectedFailedCount(testClass);

	// @formatter:off
	assertAll(
		() -> assertEquals(1, summary.getTestsFoundCount(), () -> name + ": tests found"),
		() -> assertEquals(0, summary.getTestsSkippedCount(), () -> name + ": tests skipped"),
		() -> assertEquals(0, summary.getTestsAbortedCount(), () -> name + ": tests aborted"),
		() -> assertEquals(expectedStartedCount, summary.getTestsStartedCount(), () -> name + ": tests started"),
		() -> assertEquals(expectedSucceededCount, summary.getTestsSucceededCount(), () -> name + ": tests succeeded"),
		() -> assertEquals(expectedFailedCount, summary.getTestsFailedCount(), () -> name + ": tests failed")
	);
	// @formatter:on

	// Ensure it was an AssertionFailedError that failed the test and not
	// something else like an error in the @Configuration class, etc.
	if (expectedFailedCount > 0) {
		assertEquals(1, listener.exceptions.size(), "exceptions expected");
		Throwable exception = listener.exceptions.get(0);
		if (!(exception instanceof AssertionFailedError)) {
			throw new AssertionFailedError(
				exception.getClass().getName() + " is not an instance of " + AssertionFailedError.class.getName(),
				exception);
		}
	}
}
 
Example #19
Source File: FailingBeforeAndAfterMethodsSpringExtensionTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
private void runTestAndAssertCounters(Class<?> testClass) {
	Launcher launcher = LauncherFactory.create();
	ExceptionTrackingListener listener = new ExceptionTrackingListener();
	launcher.registerTestExecutionListeners(listener);

	launcher.execute(request().selectors(selectClass(testClass)).build());
	TestExecutionSummary summary = listener.getSummary();

	String name = testClass.getSimpleName();
	int expectedStartedCount = getExpectedStartedCount(testClass);
	int expectedSucceededCount = getExpectedSucceededCount(testClass);
	int expectedFailedCount = getExpectedFailedCount(testClass);

	// @formatter:off
	assertAll(
		() -> assertEquals(1, summary.getTestsFoundCount(), () -> name + ": tests found"),
		() -> assertEquals(0, summary.getTestsSkippedCount(), () -> name + ": tests skipped"),
		() -> assertEquals(0, summary.getTestsAbortedCount(), () -> name + ": tests aborted"),
		() -> assertEquals(expectedStartedCount, summary.getTestsStartedCount(), () -> name + ": tests started"),
		() -> assertEquals(expectedSucceededCount, summary.getTestsSucceededCount(), () -> name + ": tests succeeded"),
		() -> assertEquals(expectedFailedCount, summary.getTestsFailedCount(), () -> name + ": tests failed")
	);
	// @formatter:on

	// Ensure it was an AssertionFailedError that failed the test and not
	// something else like an error in the @Configuration class, etc.
	if (expectedFailedCount > 0) {
		assertEquals(1, listener.exceptions.size(), "exceptions expected");
		Throwable exception = listener.exceptions.get(0);
		if (!(exception instanceof AssertionFailedError)) {
			throw new AssertionFailedError(
				exception.getClass().getName() + " is not an instance of " + AssertionFailedError.class.getName(),
				exception);
		}
	}
}
 
Example #20
Source File: JUnit5TestRunner.java    From quickperf with Apache License 2.0 5 votes vote down vote up
private static TestExecutionSummary runTestMethod(Class<?> testClass, String methodName) {
    MethodSelector testMethodSelector = selectMethod(testClass, methodName);
    LauncherDiscoveryRequest request = request().selectors(testMethodSelector)
                                      .build();

    SummaryGeneratingListener listener = new SummaryGeneratingListener();

    Launcher launcher = LauncherFactory.create();
    launcher.execute(request, listener);

    return listener.getSummary();
}
 
Example #21
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 #22
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 #23
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 #24
Source File: TestRunner.java    From meghanada-server with GNU General Public License v3.0 4 votes vote down vote up
private void runJUnit(String arg, LauncherDiscoveryRequest request) {
  Stopwatch stopwatch = Stopwatch.createStarted();
  System.out.println(String.format("Running %s", arg));
  System.out.println();

  Launcher launcher = LauncherFactory.create();
  SummaryGeneratingListener listener = new SummaryGeneratingListener();
  launcher.execute(request, listener);
  TestExecutionSummary summary = listener.getSummary();
  this.runCnt += summary.getTestsFoundCount();
  this.failureCnt += summary.getTestsFailedCount();
  this.ignoreCnt += summary.getTestsSkippedCount();
  this.ignoreCnt += summary.getTestsSkippedCount();

  System.out.println();

  if (summary.getTestsFailedCount() > 0) {
    System.out.println(
        String.format(
            "FAIL Tests run: %d, Failures: %d, Ignore: %d, Time elapsed: %s",
            summary.getTestsFoundCount(),
            summary.getTestsFailedCount(),
            summary.getTestsSkippedCount(),
            stopwatch.stop()));
    System.out.println("Failures:");
    for (TestExecutionSummary.Failure failure : summary.getFailures()) {
      System.out.println(failure.getTestIdentifier().getDisplayName());
      failure.getException().printStackTrace();
      System.out.println();
    }
  } else {
    System.out.println(
        String.format(
            "Tests run: %d, Failures: %d, Ignore: %d, Time elapsed: %s",
            summary.getTestsFoundCount(),
            summary.getTestsFailedCount(),
            summary.getTestsSkippedCount(),
            stopwatch.stop()));
    System.out.println("Success");
  }

  System.out.println(Strings.repeat("-", 80));
}
 
Example #25
Source File: JupiterLoadProcessor.java    From zerocode with Apache License 2.0 4 votes vote down vote up
private void registerReportListener(Class<?> testClass, String testMethod, Launcher launcher) {
    ZeroCodeTestReportJupiterListener reportListener =
            new ZeroCodeTestReportJupiterListener(testClass, testMethod );
    launcher.registerTestExecutionListeners(reportListener);
}
 
Example #26
Source File: WireMockExtensionTest.java    From wiremock-extension with MIT License 4 votes vote down vote up
private TestResults launchTests(final Class<?> testClass) {
	final Launcher launcher = LauncherFactory.create();
	final TestResults results = new TestResults();
	launcher.execute(request().selectors(selectClass(testClass)).build(), results);
	return results;
}