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.
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.
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.
Using Annotations to identify tests allows a path to also extend this to use more task focused annotations. For example, one can target what JUnit already offers such as Categories.
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?