In a Maven project, I have test classes and source classes in the same package, but in different physical locations.
.../src/main/java/package/** <-- application code
.../src/test/java/package/** <-- test code
It's no problem to access the source classes in the test classes,
but I would like to run a test runner in the main method and access the AllTest.class
so that I can create jar and execute my tests.
public static void main(String[] args) {
// AllTest not found
Result result = JUnitCore.runClasses(AllTest.class);
for (Failure failure : result.getFailures()) {
System.out.println(failure.toString());
}
System.out.println(result.wasSuccessful());
}
But it doesn't work as I don't have access to the test code. I don't understand since they are in the same package.
Question: how can access test classes from application classes? Alternatively, how can Maven package a fat jar including test classes and execute tests?
You should not access test classes from your application code, but rather create a main (the same main) in the test scope and create an additional artifact for your project.
However, in this additional artifact (jar) you would need to have:
compile
scope)test
scope)Which basically means a fat jar with the addition of test classes (and their dependencies). The Maven Jar Plugin and its
test-jar
goal would not suit this need. The Maven Shade Plugin and itsshadeTestJar
option would not help neither.So, how to create in Maven a fat jar with test classes and external dependencies?
The Maven Assembly Plugin is a perfect candidate in this case.
Here is a minimal POM sample:
The configuration above is setting the main class defined by you in your test classes. But that's not enough.
You also need to create a descriptor file, in the
src\main\assembly
folder anassembly.xml
file with the following content:The configuration above is:
test
scope (which will also take thecompile
scope as well)fileset
to include compiled test classes as part of the packaged fat jarfat-tests
classifier (hence your final file will be something likesampleproject-1.0-SNAPSHOT-fat-tests.jar
).You can then invoke the main as following (from the
target
folder):From such a main, you could also invoke all of your test cases as following:
Example of test suite:
Note: in this case the test suite is only concerning the
AppTest
sample test.Then you could have a main class as following:
The main above would then execute the test suite which will in chain execute all of the configured tests.