Now you’ve done it: you have discovered that creating unit tests is not for that single moment anymore, since testing has become a part of the Maven default build lifecycle. Now you can use these tests over and over again so that it can conform the code still acts as it should. It’s worth to create a lot of unit tests, more than ever.
Although a unit test should test only one single unit (as the name says), there are situations in which you want to use an abstract testcase, for instance to test the contract of an interface. As long as this abstract class is only used in one project, it’s just a straight forward story by adding it to the
src/test/java-folder. But once it covers multiple projects, you want to share these abstract testclasses, which mean you have to create a new project for it.
Now the most important thing you need to understand: These sources must be put under
src/main/java-folder and its depending jars should have the default of compile scope. As weird as this may sound: you’ll give the junit (or other favorite testing framework) dependency the compile scope too, since the main sources depend on it. And these (test)classes can be tested too of course, by creating specific junittests for those files.
I noticed I can generate a test-jar (jar with the testclasses) with the jar-plugin. It contains exactly what I need. Why not use this dependency by adding the test-classifier?
First you have te be aware that all jars, with or without classifier use the same pom.xml. Just check any dependency with source and/or javadoc jars in a repository, you’ll see only one pom.xml. Next thing you have to know is that if you assign a dependency to your project, only the transitive dependencies required at
runtime will be resolved, no matter the scope you give it inside your project. Just think about it: are you interested in all (if any) the dependencies which junit uses to test its classes? Combining these facts makes it not possible to build the right test-classpath. If you really want to, you could add these dependencies by hand, but then you’ll lose the transitive dependency resolution of Maven.