Refactoring JUnit 3.8 to 4.0 when hierarchy extends TestCase

Problem:

I want to start writing tests in JUnit 4.0, but I have a lot of tests in JUnit 3.8.  I can’t just start writing tests in 4.0, because I rely on common setup/assertions in my custom superclass which extends TestCase. (Which means JUnit will only look for 3.8 style tests)

Solution:

Create one or more new classes to contain static method equivalents that you need.  The new code can use static imports to get these methods.  The original abstract class can delegate to them.

Limitations:

Some frameworks require you extend a certain class.  Until the framework provides a non-JUnit 3.8 dependency, there’s not much you can do here.  You can still use this approach for tests that don’t require that special framework.

UML for refactoring:

Sample code:

package com.javaranch.asserts;

import static com.javaranch.asserts.JavaRanchTestUtil.*;
import junit.framework.*;

public abstract class AbstractJavaRanchTestCase extends TestCase {
   @Override
   public void setUp() throws Exception {
      super.setUp();
      setUp_propertyConfiguration();
   }
}

Conclusion:

I’ve done this refactoring enough times that is second nature by now.  This blog post documents the refactoring since I’m not finding it on the web.

What other problems/sticky situations have you encountered when mixing JUnit 3.8 and 4.0 code?

Leave a Reply

Your email address will not be published. Required fields are marked *