Like all "good" solutions, this one begins with a problem. Specifically, a problem that I had executing my unit tests within Eclipse.

Usually, running JUnit tests is quite easy in Eclipse. If you have a JUnit test class, you can simply right click on it and Run As » JUnit Test. If you have an entire package full of test classes or indeed, an entire folder full of test packages, just do the same: Run As » JUnit Test.

The trouble starts when you have packages that contain a mix of test and non-test classes and further, a src/test/java folder that contains a mix of test and non-test packages. There is literally no way in Eclipse to selectively choose the test classes to execute! If you find one, let me know and I'll happily retract the rest of this post :-)

When using Ant, it is trivial to pick and choose which tests to run by passing a suitably constructed fileset to the junit task's batchtest property.

Now I could launch the corresponding Ant test task from within Eclipse but it doesn't integrate well (i.e., not at all!) with Eclipse's JUnit view. Instead, what I want is to be able to select my test classes like above and then launch & monitor them as I normally do in Eclipse.

So then, here are the requirements:

Be able to specify test classes to run.

Be able to launch using Run As » JUnit Test.

If you look at the junit ant task above, you'd notice that the way in which we declared the set of test classes is quite nice. It allows use of wildcards which provides great flexibility in selecting resources. Wouldn't it be nice to reuse the same syntax in our new JUnit runner? It would be and that's what we'll do! But first, let's focus on building the list of test classes.

JUnit provides a Suite class that acts as a test Runner for a specified set of classes. All we have to do is pass it a list of classes we want executed as tests and it'll do the rest. Let's look at some code:

/** * Discovers all JUnit tests as per config and runs them in a suite. */@RunWith(AllTests.class)publicclassAllTestsextendsSuite{publicAllTests(finalClass<?>clazz)throwsInitializationError{super(clazz,findTestClasses());}privatestaticClass<?>[]findTestClasses()throwsInitializationError{// The following Resource Locations are configured using Ant fileset syntaxString[]resourceLocations=newString[]{"classpath*:**/cache/objects/*.class","classpath*:**/config/*.class","classpath*:**/util/*.class","classpath*:**/test/TestFoo.class","classpath*:**/test/TestBar.class","classpath*:**/test/TestBaz.class"};try{// Restrict search to this base packageStringbasePackage="net.antrix";TestClassesPatternResolverresolver=newTestClassesPatternResolver(basePackage,Arrays.asList(resourceLocations));List<Class<?>>classes=resolver.getClasses();returnclasses.toArray(newClass[classes.size()]);}catch(Exceptione){List<Throwable>errors=newArrayList<Throwable>();errors.add(e);thrownewInitializationError(errors);}}}

The AllTests class is quite simple. We extend the JUnit Suite class and pass our list of classes to the Suite constructor. The list of classes is constructed using a list of strings passed to a TestClassesPatternResolver. Clearly, this TestClassesPatternResolver is taking the list of Strings in our "wildcard" format and returning the actual list of classes that match the specified patterns. Let's look at the implementation of this resolver class.

classTestClassesPatternResolver{privatefinalList<Class<?>>_classes=newArrayList<Class<?>>();privatefinalString_basePackage;privatefinalResourcePatternResolver_resourcePatternResolver=newPathMatchingResourcePatternResolver();publicTestClassesPatternResolver(StringbasePackage,List<String>resourceLocations)throwsIOException,ClassNotFoundException{this._basePackage=basePackage;for(StringresourceLocation:resourceLocations){_classes.addAll(resolveClassesFromResourcePatterns(resourceLocation));}}publicList<Class<?>>getClasses(){return_classes;}privateCollection<Class<?>>resolveClassesFromResourcePatterns(Stringpattern)throwsIOException,ClassNotFoundException{Collection<Class<?>>classes=newArrayList<Class<?>>();if(ResourcePatternUtils.isUrl(pattern)){Resource[]resources=_resourcePatternResolver.getResources(pattern);for(Resourceresource:resources){URLurl=resource.getURL();System.out.println("Resolving Class Name for URL: "+url.toString());StringclassName=resolveClassFromPath(url.toString());System.out.println("Finding methods in Class Name: "+className);if(className!=null&&className.length()>0){Class<?>klass=Class.forName(className);for(Methodmethod:klass.getDeclaredMethods()){// If at least one method is annotated with the JUnit// @Test annotation, we include the class as a Test Class.if(method.getAnnotation(org.junit.Test.class)!=null){System.out.println("Found @Test method "+method.getName()+" in class "+klass.getName());classes.add(klass);break;}}}}}returnclasses;}privateStringresolveClassFromPath(Stringurl){StringclassUrl=ClassUtils.convertResourcePathToClassName(url);intbegin=classUrl.indexOf(this._basePackage);if(begin<0)returnnull;returnclassUrl.substring(begin,classUrl.indexOf(".class"));}}

Again, most of what is happening above should be quite obvious. All of the heavy lifting is done by the awkardly named Spring class PathMatchingResourcePatternResolver as well as the Spring provided utility classes ResourcePatternUtils & ClassUtils. This does bring in a Spring dependency but since the project already uses Spring - not a deal breaker.

With the above two classes included in my project, I can now simply right click on the AllTests.java class in the Eclipse Package Explorer and Run As » JUnit Test. Mission accomplished!