Time for action – writing a simple JUnit test case

This section explains how to write and run a simple JUnit case in Eclipse.

  1. Create a new Java project called com.packtpub.e4.junit.example.
  2. Create a class called MathUtil in com.packtpub.e4.junit.example.
  3. Create a public static method called isOdd() that takes an int value, and returns a boolean value if it is an odd number (using value % 2 == 1).
  4. Create a new class called MathUtilTest in the package com.packtpub.e4.junit.example.
  5. Create a method called testOdd() with an annotation @Test, which is how JUnit 4 signifies that this method is a test case.
  6. Click on the quick-fix saying Add JUnit 4 library to the build path, or edit the build path manually to point to Eclipse's plugins/org.junit_4.*.jar file.
  7. Implement the testOdd() method as follows:
    assertTrue(MathUtil.isOdd(3));
    assertFalse(MathUtil.isOdd(4));
  8. Add a static import to org.junit.Assert.* to fix the compile-time errors.
  9. Right-click on the project and go to Run As | JUnit Test, and the JUnit test view should be shown with a green test result:
    Time for action – writing a simple JUnit test case
  10. Verify that the test works, by modifying the isOdd() method to return false and re-run it—a red-colored test-failure text should be seen instead.

What just happened?

The example project demonstrated how JUnit tests are written and executed in Eclipse. The example works for both OSGi and non-OSGi projects, provided JUnit can be resolved and executed accordingly.

Remember to annotate the test methods with @Test, otherwise they won't run. It can sometimes be helpful to write a method that knowingly fails at first, and then run the tests, just to confirm it's actually being run. There's nothing more useless than a green test bar with tests that are never run, but would fail when they are run.

It is also possible to re-run tests from the JUnit view; the green play button allows all tests to be re-run, while the one with a red cross allows just the tests that have failed to be re-executed (shown as disabled in the previous example).

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset