views:

48

answers:

2

Are there any automated tools to find class dependencies when writing unit tests.

An example to show what I mean:

We want to write unit tests for class ToBeTested. So I will write some tests to verify the expected behaviour of the class. Now I still dont know if there are class depencies as in ToBeTested probably uses lots of other classes. This is important to know because we will want to break those dependencies or at least make sure they are safe(tested already).

Best way to find dependencies I found so far is using eclemma which gives me a list of classes with code that run during test.

But know im typing those classes down manually, is there any easier/automated way to get these classes and even use this list in my java programs.

Edit: Sorry, I am using eclipse and java.

+2  A: 

Since unit testing is (almost always) whitebox testing, you can simply look at the source code of the class being tested to see its dependencies.

A list of dependencies produced by some automated tool may sound good in theory, but in my experience it would not help much anyway - you need to go through the dependencies one by one, determine which are the real, important ones from the point of view of the current test, then set them up / mock them properly for your unit test. This part can't be automated (and I doubt it will ever be).

The simplest and best way (for me) to achieve this is to start running your test with the simplest obvious test fixture, i.e. typically ToBeTested tested = new ToBeTested(). If that succeeds, I add call(s) to the desired method(s) on the object. If that succeeds as well (i.e. no exceptions are thrown runtime), I add asserts. If (when) any of these steps fail, I look into / debug the code to see what went wrong, and extend the test fixture to cover that.

In the best case (TDD on your own code, being developed freshly) this process is of course much simpler, since the class is designed from the start to be testable, thus it has the minimal number of dependencies, and you already know these. In the worst case (writing unit tests for legacy code) this can be a painful, but rewarding process of exploration and possibly refactoring, taking several hours to create the first working test. But the next will be much easier, and after the 3rd I almost always start producing more tests like a conveyor belt.

Péter Török
+2  A: 

Yes, one is JDepend, which analyzes package dependencies. We used this to automatically detect cyclical dependencies among packages. I don't know how easy it would be to check dependencies of the test itself.

More detail on use of JDepend with unit tests is at http://www.clarkware.com/software/JDepend.html#junit.

There is also a corresponding Eclipse plug-in for visualization of dependencies.

Andy Thomas-Cramer
nice, but looks like this is for packages only. Im more interested in classes
Skiy