Java – Run JUnit tests from a dependency jar in Eclipse

eclipsejavajunitmavenunit testing

I have some JUnit tests that contained in a .jar that is intended to be used as a library. The library contains some tests that should be run whenever the library is used in another project.

However when I create a new project using the library and run JUnit on it in Eclipse then the tests in the dependency .jar don't run / don't get detected by the JUnit test runner. I get the message:

No tests found with test runner 'JUnit 4'.

Is there a way I can configure the dependency .jar so that the tests will run alongside any tests that might be contained in the main project?

Basically I want the dependency .jar to "export" the tests to whatever projects it is used in.

I'm using Eclipse Juno, JUnit 4.10, and Maven for the dependency management.

EDIT:

The point of this library is to be able to help test projects that use it – i.e. it runs some specialised tests. This is why I want to be able to import the library .jar and have it contribute the extra tests to the importing project.

Best Answer

You can try Maven Surefire.

In some cases it would be useful to have a set of tests that run with various dependency configurations. One way to accomplish this would be to have a single project that contains the unit tests and generates a test jar. Several test configuration projects could then consume the unit tests and run them with different dependency sets. The problem is that there is no easy way to run tests in a dependency jar. The Surefire plugin should have a configuration to allow me to run all or a set of unit tests contained in a dependency jar.

This can be done as follows (Junit 3):

Ensure test jar contains a class which has a static suite() method

import junit.framework.Test;
import junit.framework.TestSuite;

public class AllTests {    
    public static Test suite() 
    { 
        TestSuite suite = new TestSuite( "All Tests"); 
        suite.addTestSuite(TestOne.class); 
        suite.addTestSuite(TestTwo.class); 
        return suite; 
    }    
}

Then in the project using the test-jar dependency: create a TestCase:

package org.melati.example.contacts;
import org.melati.poem.AllExportedTests;
import junit.framework.Test;
import junit.framework.TestCase;

public class PoemTest extends TestCase {    
    public static Test suite() 
    { 
        return AllExportedTests.suite(); 
    }
}

Now the tests will be found.