views:

3970

answers:

4

Is there anything out there (for Java specifically) that allow you to automatically test the behavior of an interface? As an example, let's say I have a bunch of tests for the Comparable interface, that should apply to anything that implements Comparable. What I'd like is to be able to include "ComparableTests" automatically in the test fixtures for any of my classes which implement Comparable. Bonus points if this would work with generic interfaces.

I know the .NET framework mbUnit has something similar, and when you're using something like TestNG's generator functions you could set up a test fixture for Comparable and have the generator create an instance of each of your classes that implement Comparable. But I'd rather have it be automatic, and located at the test fixture for each of my classes (since I'll already have them around for testing other parts of that class).

Clarification: I could definitely build something like this. I was asking if there was anything out there that already enabled this.

A: 

In .NET it would be pretty simple to set up a method that looks through an assembly and identifies each class's inheritance/implementation hierarchy. I'm sure you could do it in Java, too, if you research the Java reflection API.

You could then create an array of ITargetInterfaces and call a test method on each one.

SoloBold
A: 

One way would be to search through the jar file for all the .class files (or search through the classes directory), use the Class.forName() method to load the class file and check MyInterface.class.isAssignableFrom(myClass).

This wouldn't deal easily public inner static classes (you could parse the class file name), but would never work with private inner classes or anonymous inner classes.

Aaron
This might prove very difficult since complex factories might be used to instantiate specific implementations of the interface.
p3t0r
+1  A: 

Based on your last paragraph, what you're trying to do is inject some 'extra methods' into unit testing since you're already testing a specific class. I do not know of a testing harness that allows you to attach tests based on the hierarchy of a class.

However, with your own suggestion of using TestNG for building something similar, I think you might be very close. You could very well incorporate some base code that adds your class to a list of 'default test classes', which are in turn tested if they implement a specific interface.

Still, regarding the general case, I think you're out of luck, since the Java type system is one-way, you can only (easily) find out what interfaces a class implements, not the other way around. Furthermore, the problem is 'where to stop looking': if you have a test that checks all your comparable implementers, do you want it to check the validity of String's one too, since that is in your Java environment?

Angelo
+1  A: 

Try this http://www.xmlizer.biz/java/classloader/ClassList.java

nicktmro