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

前端 未结 7 1793
天命终不由人
天命终不由人 2020-11-29 20:14

I have a bunch of JUnit 3 classes which extend TestCase and would like to automatically migrate them to be JUnit4 tests with annotations such as @Before,

相关标签:
7条回答
  • 2020-11-29 21:13

    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 ;)

    0 讨论(0)
提交回复
热议问题