Home > Blockchain >  How to get TestClass in main method in maven project?
How to get TestClass in main method in maven project?

Time:05-19

I have Junit5Runner class which starts Junit5 test programmatically. It's not a maven project now, it's a simple java project with no any framework. I need to switch to maven project, but in a maven project test classes are located inside test folder and aren't accessable from src folder.

How can I get access to test class from test folder in the main class from src folder?

Here is my Junit5Runner code.

Here I get access to CalculatorTest class.

public class Junit5Runner {
    SummaryGeneratingListener listener = new SummaryGeneratingListener();

    public void runOne() {
        LauncherDiscoveryRequest request = LauncherDiscoveryRequestBuilder.request()
                .selectors(selectClass(CalculatorTest.class)) //I NEED TO GET THIS CLASS FROM TEST FOLDER
                .build();
        Launcher launcher = LauncherFactory.create();
        TestPlan testPlan = launcher.discover(request);
        launcher.registerTestExecutionListeners(listener);
        launcher.execute(request);
    }

    public static void main(String[] args) {
        final Junit5Runner runner = new Junit5Runner();
        runner.runOne();
        TestExecutionSummary summary = runner.listener.getSummary();
        for (TestExecutionSummary.Failure failure : summary.getFailures()) {
            System.out.println(failure.getTestIdentifier().getDisplayName());
            System.out.println(failure.getException());
        }
    }
}

CodePudding user response:

The simplest solution is to put your production code int src/main/java/<package> and your unit tests into src/test/java/<packageName> and name your unit tests like *Test.java. If you follow that you can execute your unit tests (assumed you have added the appropriate dependencies for JUnit Jupiter in your pom file) via

mvn clean test

Full setup for JUnit Jupiter and example project can be found here.

  • Related