Monday, August 6, 2007

Unit testing

After a couple of years of unit testing I still haven't found an elegant way to make sure that a method calls another method. For example I want to test method x that calls method y. Method y ensures a business rule, for example it checks whether certain reserved characters are not present in a string that is passed as parameter. I can do some litmus tests against x, indirectly testing whether it calls y. However this gives not a 100% guarantee. In fact, it introduces an extra dependency. If the business rule change, y changes and i've to update some tests of x...
Another approach is of course to use mocks. However this requires interfaces, factories/ioc, etc. A lot of overhead for a simple test.

A futuristic alternative is to define an aspect that checks that at least one method called from x is y. Admittedly, I've no idea how to implement this, but it won't be easy / flexible to do in a TDD manner.

Another desperate attempt; if y would throw an exception in case of failure, you could check the stacktrace. Obivously, still brittle.

So the question remains how to solve this. It gives me an unpleasant feeling that such a basic problem is not yet solved. Perhaps someone else has a bright idea.

2 comments:

Anonymous said...

Languages that support MOP (meta object protocol) like Groovy might be able to intercept the call to the business routine...

Stephan Westen said...

Use jmockit:

https://jmockit.dev.java.net/