A simple classpath scanner implementation that searches for classes having any method annotated with @Test or @RunWith. Spring Framework’s scanner utility is used to do this.
Many tools and dev environments support the search and invocation of JUnit tests. Some just search for Java files that end in ‘Test’, others search for files that actually contain tests. I think the latter is more accurate and useful.
Use case
One obvious one is programmatically creating test suits. The JUnit 4 approach of an annotation with a list of test classes is just plain wrong. With the code below a JUnit 3 type of test suite can be created.
Implementation
In the code below, Spring’s ClassPathScanningCandidateComponentProvider is used to scan the classpath. A custom TypeFilter is used to test each method of found classes for the annotations, and if found, the class is added to a list. This is available as a Gist.
I got the idea for this from Classpath Scanning: Hidden Spring Gems.
As I mentioned, this is a simple approach. If you look at other’s such as in Eclipse, the scanners are more robust.
How would this be done without using Spring’s scanner support?
Links
- Classpath Scanning: Hidden Spring Gems
- org.eclipse.jdt.internal.junit.launcher.JUnit4TestFinder
- Java Code Examples for … ClassPathScanningCandidateComponentProvider
- How do I programmatically run all the JUnit tests in my Java application?
Clik here to view.
