Tuesday, May 3, 2011

Make the Eclipse JUnit Test Suite wizard work for JUnit-4

Background.
I recently got back into Java being inspired by the growth of the Android platform and Java's close link to it. I needed a refresher tutorial on Java and Eclipse and found "Eclipse and Java for Total Beginners" which after getting over my pride and reviewing the first couple of lessons is just what I needed. This very well thought out and produced tutorial also gives an excellent introduction to "Test Driven Development". Another benefit.

The Problem.
The tutorial is based based on JUnit-3. I installed the more up-to-date JUnit-4 and the Eclipse "JUnit Test Suite" wizard BLEW UP! :..)... I googled "eclipse JUnit 4 Test Suite wizard problem" and concluded that it seems to be well known, so I thought I'd publish my work-around here.

The Work-Around. 
The specific variable names in the work-around are based on the tutorial code. You can see what the tutorial recommended by going to Lesson- 8 at about 10min:50sec. Here is the work-around:

-in Package Explorer View TotalBeginner/test rclick org.totalbeginner.tutorial
    new.other.Java.JUnit.JUnitTestSuite
        wizard dialog comes up
            -next, press Finish to select default of (BookTest, PersonTest)
                creates a new class AllTests
-*** wizard will say ***:  
    Warning: No test classes selected
    *** because i use JUnit-4 Wizard needs JUnit-3 ***
    -click Finish anyway
-Fix wizard generated code
    1. delete everything from the wizard code 
        EXCEPT the package definition in this case:
            package org.totalbeginner.tutorial;
    2. put in something like the following code 
        2.1 here's the code:
            @RunWith(Suite.class)
            @Suite.SuiteClasses(value={BookTest.class, PersonTest.class})
            public class AllTests {}
        2.2 Change/Add to the example "BookTest.class" & "PersonTest.class" items,
            appropriate items for your situation. 
        2.3 use eclipse quickfix to create appropriate import statements
            -click in error code marked with red squiggly underline
            -ctl-1 for quick fix
            -select suggestion that generates the appropriate import
            -continue until no more errors 
            -for this example 2 imports were generated:
                import org.junit.runner.RunWith;
                import org.junit.runners.Suite;

2 comments:

  1. Thanks! I had just got stuck on the end of Lesson 08, and this helped me sort it out.

    ReplyDelete
  2. I have just put the code for Junit based test suite as downloadable java application which can be configured in Eclipse or NetBeans

    ReplyDelete