I want to test in junit via jdepend whether my package tree
is on a package cycle (i.e. has a direct cyclic dependency). Currently, it isn't (see output below, and jdepend's Eclipse plugin does not find a cycle for tree
). But the assertion below, suggested in jdepend's manual, fails:
// setup.开发者_开发技巧...
JavaPackage p = jdepend.getPackage("tree");
System.out.println(p.getName() + "'s efferent packages: ");
for (Object jp : p.getEfferents()) {
System.out.println(((JavaPackage) jp).getName());
}
assertThat(p.containsCycle(), is(false));
The output is:
tree's efferent packages:
java.util
java.lang
java.lang.reflect
java.util.logging
java.io
org.hamcrest
The reason that the assertion fails is that containsCycle()
recursively calls getEfferents(), puts the resulting packages in a list and returns true
if some package is already in it. So containsCycle()
checks whether there is a reachable package cycle (i.e. whether tree has an indirect cyclic dependency).
But how can I test only direct cyclic dependencies, i.e. whether tree is on a package cycle (and not, that it leads to some other package cycle, e.g. in org.hamcrest)?
The following solution doesn't work in general, but as a workaround:
Instead of checking whether tree has a direct package dependency, you do check indirect package dependency (i.e. whether tree leads to a package cycle) via p.containsCycle()
, but only after the following code:
final PackageFilter filter = new PackageFilter();
jdepend.setFilter(filter);
filter.addPackage("org.hamcrest");
That way, the packages that tree depends upon (see output listed in the question), but that have cycles themselves, are filtered out beforehand.
The downside is that you might have to add packages to the filter if you import new ones. And you have to do different setups for different jdepend-tests, because you do not want to use that filter to compute other metrics, such as the distance from the main sequence, D. Last but not least, if tree -> yourFilteredPackage is part of the direct cycle, it won't get detected :(
精彩评论