Platinum Partner
java,frameworks

Using an Aspect ITD in Unit Tests

A while back, I wrote a class that would allow me to programmatically change logger levels from inside a test. Here‘s the idea: invariably if you are doing TDD, you are adding logging statements as you go to fix your broken tests. Generally, you have two choices: go into your XML configuration file and just universally set the log level to debug, or you will find that you will end up doing info level messages while you are developing, intending to backtrack and change those to debugs when you are done. The global debug is a bad idea because it produces a huge amount of crud, everything from the AST Hibernate is building to Spring‘s setup of all its beans, etc. I like a console when I am working on tests that has almost nothing else in it.

The class I wrote uses a Stack so that it can restore the levels of each logger it changes. So let‘s say we are working on a class called Visitor, we have to change the level of that to DEBUG, then when the test is over, it can restore it to whatever level it was set to before. Anyway, to make this work, I had to:

  1. Add an instance of the class (LoggerLevelStack).
  2. Set the levels I wanted in a @Before method.
  3. Call revertAll() from an @After method.

It‘s not that this is that much work, but it is kind of a nuisance.

So I was doing some other stuff with Aspects the other day and realized that I could do this as an ITD: the pointcut is all classes that have names ending in Test, and of course the steps are down to 1: just set the level.

This is the aspect:

Notice that declare parents is used to essentially bolt a marker interface onto all the tests, then the ITD references are through said interface. I like this, it's simple and clean, and all you need to know is in one place.

The other good news in doing this is that the AspectJ plugin now recognizes ITDs: no warning/error markers and code completion even works (and the cross references pane works great). Nice job on this stuff. [After turning on AJDT, code completion in regular Java contexts started doing some really weird things, so not sure the plugin is totally out of the doghouse yet. I plan to make a screencast the next time it happens using the new Snow Leopard video recorder.]

From http://www.jroller.com/robwilliams

{{ tag }}, {{tag}},

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}
{{ parent.authors[0].realName || parent.author}}

{{ parent.authors[0].tagline || parent.tagline }}

{{ parent.views }} ViewsClicks
Tweet

{{parent.nComments}}