carlspring
carlspring

Reputation: 32567

How to run a JUnit test programatically and specify a classpath

I am writing a custom tool that executes a set of test classes programmatically using JUnit 5.

When executing these tests, is there a way to define the classpath for the execution? (I have a set of jars that are being provided, as well as some compiled production and test code which I will need to add to the classpath).

I have roughly the following code:

LauncherDiscoveryRequest request = LauncherDiscoveryRequestBuilder.request()
                                                                  .selectors(selectPackage(basePackage))
                                                                  .filters(includeClassNamePatterns(classNamePatterns))
                                                                  .build();

SummaryGeneratingListener listener = new SummaryGeneratingListener();

Launcher launcher = LauncherFactory.create();
launcher.registerTestExecutionListeners(listener);

TestPlan testPlan = launcher.discover(request);

// launcher.execute(request);
launcher.execute(testPlan);

TestExecutionSummary summary = listener.getSummary();
summary.printTo(new PrintWriter(System.out));
summary.printFailuresTo(new PrintWriter(System.out));

What's the correct way to do this?

Upvotes: 1

Views: 842

Answers (1)

Sam Brannen
Sam Brannen

Reputation: 31177

When building the request you can select classpath roots via org.junit.platform.engine.discovery.ClasspathRootSelector.

Upvotes: 0

Related Questions