JUnit recipes: Work around static attributes in classes

Beware of the class loader. I recently had a major testing problem with some code because I didn't take the (sometimes ugly) Java class loading mechanism into account. There was a small class where I wanted to unit test the calculateAge method.

class AgeCalculator {
    public int calculateAge(Person person) {

So I dropped EasyMock into my project and mocked the person class. I was using jMock in the past and could live with methods as strings. With the new JMock 2 syntax this has changed. I still struggle with {{ in JMock expectations and so does my IDE. When IDEA learns to format JMock expectations, I'm back. For now I'm using EasyMock though, sometimes with JMock assertions from the excellent Hamcrest assertion library. Back to the problem at hand . The mock was passed into the AgeCalculator to calculate the age of the person. The problem was the Person class.

class Person {
  private static Configration conf = 
    new DatabaseConfiguration("Person");

Even though I didn't use the Person class, just a mock, the static attributes where initialized and the DatabaseConfiguration tried to load data from the backend. This happens whenever your classloader sees the Person type, even in an interface.

interface Calculator {
    public int calculateAge(Person person);

Using Calculator in mocks will initialize the static attributes in Person. Which contradicted the isolation principle of unit tests and also led to long startups of the database backend. This stopped my efforts to test the AgeCalculator. Time passed.

Then I stumbled upon JMockit. Others have too. The friendly and supportive developers of JMockit have helped (thanks Rogerio) and with a simple line I was saved:


Constructs like the above with static attributes should never be created in the first place (hello all those people who propagate static inialized attributes for singletons to avoid synchronized). But if you have such code in your legay base, JMockit to the rescue.

Thanks for listening.