2

For running all my test classes automatically, I look for all class files inside a dedicated directory, convert the path to a package name and check if this class implements the given interface:

try {
    Class<? > myTestClass = Class.forName( constructedClassName );
    if( myTestClass.isInstance( MyTestInterface.class ) ) {
        testCollection.add( myTestClass );
    }
}
catch( Error e ) {
    // ignore, no valid test class
}

Today I ran into an ugly bug (see this SO question) using this technique.

Question:

How can I collect all my test classes without having to ignore Errors that can occur with classes I'm not interested in?

Community
  • 1
  • 1
tangens
  • 39,095
  • 19
  • 120
  • 139
  • 1
    See http://stackoverflow.com/questions/435890/find-java-classes-implementing-an-interface. – Michael Myers Feb 05 '10 at 22:49
  • What `Errors` are you getting with this code? Is it possible to do some validation on `constructedClassName` before calling `forName`? – Michael Myers Feb 05 '10 at 22:58
  • Just use JUnit 4 and Eclipse or IntelliJ Idea will automatically find all tests and run them. – Denis Tulskiy Feb 05 '10 at 23:03
  • @piligrim: These classes aren't unit tests. They are integration tests, that start up the whole system and feed it with input and check the output. The tests have to run automatically without an IDE. – tangens Feb 05 '10 at 23:07

2 Answers2

1

How can I collect all my test classes without having to ignore Errors that can occur with classes I'm not interested in?

You've kind of painted yourself into a corner here ...

What I'd do is one (or more) of the following:

  • fix the offending classes so that they do load

  • put the classes into different directories, create lists of names, or use pattern matching to discriminate between the classes that you do / don't want to add to testCollection

And log the Errors of course!! Maybe log them somewhere different, but if you do that leave a loud message in the main log that tells someone where to look for details.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
1

What good is a class that does not load? Why not just fix them first? Wouldn't you have to fix them at some point?

Mihir Mathuria
  • 6,479
  • 1
  • 22
  • 15