10 Differences Between JUnit 3.x and JUnit 4.x and why you should move to JUnit 4.x platform.

There is a great change from JUnit 3.x to JUnit 4.x. The JUnit Annotations in 4.x make unit testing pretty simpler and quicker now. In this article, I will try to cover 10 different JUnit features to show why you or your company should migrate from using JUnit 3.x to JUnit 4.x.

1. No more setUp() and tearDown() methods.

The methods setUp() and tearDown() methods can now be replaced with annotations @Before and @After and you can name your method as you would like. In Junit 3.x, if you wanted to do initialization and clean up before and after each test run, you had to write methods with specific names as below:

Intialization:

public void setUp () {
   //Your Code Here

}

CleanUp:

public void tearDown() {
   //Your Code Here
}


You no longer need to follow the naming convention in Junit 4.x, as long as you use annotation tags @before to do initialization and @after to do clean up.

Intialization:

@before
public void myOwnInitializationMethod () {
   //Your Code Here

}

CleanUp:

@after
public void myOwnCleanupMethod() {
   //Your Code Here
}

2. You don’t need to name your method to start with the word test.

In Junit 3.x, the jUnit methods had to be specifically named. They needed to begin with the word test in order for JUnit to run that as a test case.

Junit 3.x:

public void testMyMethod() {
   //Your Code Here
}


JUnit 4.x:

@Test
public void myMethod() {
  //Your Code Here
}

3. You don’t need write your test class to extend junit.framework.TestCase

jUnit 3.x:

public class MyTestClass extends TestCase {
  // Your Methods Here

}


jUnit 4.x:

@TestClass
public class MyTestClass {
   //Your Methods Here
}

4. JUnit 4 adds ability to do one time setup and one time tear down.

If you wanted to do one time setup (intialization at the beginning of the class load) and one time tear down (cleaning up after all your test cases have been run), you can now do that with @BeforeClass and @AfterClass annotations.

@BeforeClass
public void mySomeMethod() {
//This method is run one time before any of your test cases are run.
}
@AfterClass
public void mySomeClenaUpMethod {
//This method is run one time after all your test cases have been run
}

5. JUnit 4 allows static import of the assert classes.

6. You can ingnore a test case with @Ignore annotation

@Ignore
public void doNotRunThisTest() {

}
1
<!--INFOLINKS_ON-->
<h2>7. Enforcing Timeout</h2>
You can time limit your test cases by providing timeout value. If the test case does not complete within that time, JUnit reports this as a failure.
<!--INFOLINKS_OFF-->
1
@Test(timeout=50)
public void runThisTestWithin50ms() {
}

8. JUnit Test Suite

Running Junits as a suite is now simpler. See the tutorial on running JUnit 4.0 test suite at:
http://sanjaal.com/java/tag/junit-test-suite-tutorial/



9. Expecting Exception:

Junit 4.x allows you to expect exceptions in your unit test. So, if you are expecting NullpointerException, here is what your code would look like:

@Test(expected=NullPointerException.class)
public void testMyMethodForNullPointer() {
 //Your piece of code that throws null pointer exception
}



10. Parameterized Testing:

With JUnit 4.x, you can run the same tests with multiple parameters using some annotations. To write parameterized testing, you can put class level annotation @RunWith(Parameterized.class) to tell JUnit to run parameterized testing. Then inside your class, you can use annotation @Parameters to tell JUnit a list of collections to use as parameters. The constructor will know how to initialize your parameters.

@RunWith(value=Parameterized.class)
public class ParameterizedTest {

   private String myFirstParam;
   private String mySecondParam;

   @Parameters
   public static Collection paramsValues {
       return Arrays.asList( new Object[][] {
                            { "1", "1" },
                            { "11", "11" },
                            { "12", "12" },
                            { "13", "13" },
                            { "16", "16" },
                            });
   }

   public ParameterizedTest(String paramOne, String paramTwo) {
       this.myFirstParam = paramOne;
       this.mySecondParam = paramTwo;
   }

   @Test
   public void testParams() {
       Assert.assertEquals(myFirstParam, mySecondParam);
   }
}

Originally posted 2013-01-17 17:30:55.

Share

15 Best Practices for Unit Testing Your Java Code Using Junit

Disclaim and Credit:

The exerpt is from a book Java Development with Ant, by Erik Hatcher and Steve Loughran, published by Manning Publications Company. The credit goes to the authors of the book and the publishers.

The following are the best practices for unit testing.

  1. Test everything that could possibly break. This is an XP maxim and it holds.
  2. A well-written test is hard to pass. If all your tests pass the first time, you are probably not testing vigorously enough.
  3. Add a new test case for every bug you find.
  4. When a test case fails, track down the problem by writing more tests, before going to the debugger. The more tests you have, the better.
  5. Test invalid parameters to every method, rather than just valid data. Robust software needs to recognize and handle invalid data, and the tests that pass using incorrect data are often the most informative.
  6. Clear previous test results before running new tests; delete and recreate the test results and reports directories.
  7. Set haltonfailure=”false” on to allow reporting or other steps to occur before the build fails. Capture the failure/error status in a single Ant property using errorProperty and failureProperty.
  8. Pick a unique naming convention for test cases: *Test.java. Then you can use with Ant’s pattern matching facility to run only the files that
    match the naming convention. This helps you avoid attempting to run helper or base classes.
  9. Separate test code from production code. Give them each their own unique directory tree with the same package naming structure. This lets tests live in the same package as the objects they test, while still keeping them separate during a build.
  10. Capture results using the XML formatter: .
  11. Use , which generates fantastic color enhanced reports to quickly access detailed failure information.
  12. Fail the build if an error or failure occurred:
  13. Use informative names for tests. It is better to know that testDocumentLoad failed, rather than test17 failed, especially when the test suddenly breaks four months after someone in the team wrote it.
  14. Try to test only one thing per test method. If testDocumentLoad fails and this test method contains only one possible point of failure, it is easier to track down the bug than to try and find out which one line out of twenty the failure occurred on.
  15. Utilize the testing up-to-date technique. Design builds to work as subcomponents, and be sensitive to build inefficiencies doing unnecessary work.
Blog Widget by LinkWithin

Originally posted 2012-04-14 20:06:37.

Share