Wednesday, April 1, 2009

Unit tests to check against cyclic dependencies

Some sample code to write a unit test which checks the project for cyclic dependencies. It is using a paramerized Test class, where each package is passed to the constructor of the test object. It uses jdepend  to  analyse the project based on the compiled class files located in the directory 'target/classes'.


@RunWith(Parameterized.class)
public class JDependTest {

     private static JDepend jdepend = null;
     private static Collection packages = null;
     private JavaPackage pack1 = null;

     @Parameterized.Parameters
     public static Collection data() throws IOException {
         Collection result = new ArrayList();
        jdepend = new JDepend();
        jdepend.addDirectory("target/classes");
        packages = jdepend.analyze();
        for (Object p : packages) {
            result.add(new Object[]{p});
        }
        return result;
     }
     
    public JDependTest(JavaPackage pack) {
        pack1 = pack;
    }
    @Test
    public void cycleTest() {
        assertFalse(pack1.getName() + " failed", pack1.containsCycle());
    }
}

This is the output in Netbeans. It could be improved by adding the cycles which have been detected, but that can also be seen in the jdepend report.

No comments:

Post a Comment