Best way to automagically migrate tests from JUnit 3 to JUnit 4?

In my opinion, it cannot be that hard. So let’s try it:

0. Imports

You need to import three annotations:

import org.junit.After;
import org.junit.Before;
import org.junit.Test;`

After you’ve made the next few changes, you won’t need import junit.framework.TestCase;.

1. Annotate test* Methods

All methods beginning with public void test must be preceded by the @Test annotation.
This task is easy with a regex.

2. Annotate SetUp and TearDown methods

Eclipse generates following setUp() method:

@Override
protected void setUp() throws Exception { }

Must be replaced by:

@Before
public void setUp() throws Exception { }

Same for tearDown():

@Override
protected void tearDown() throws Exception { }

replaced by

@After
public void tearDown() throws Exception { }

3. Get rid of extends TestCase

Remove exactly one occurence per file of the string

" extends TestCase"

4. Remove main methods?

Probably it’s necessary to remove/refactor existing main methods that will execute the test.

5. Convert suite() method to @RunWithClass

According to saua’s comment, there must be a conversion of the suite() method. Thanks, saua!

@RunWith(Suite.class)
@Suite.SuiteClasses({
  TestDog.class
  TestCat.class
  TestAardvark.class
})

Conclusion

I think, it’s done very easy via a set of regular expressions, even if it will kill my brain 😉

Leave a Comment