Time for action – writing a simple JUnit 4 test case

This part explains how to write and run a simple JUnit 4 test 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 and returns a boolean if it is an odd number (using value % 2 == 1).
  4. Create a new class called MathUtilTest in a package com.packtpub.e4.junit.example.
  5. Create a method called testOdd with an annotation @Test, which is the way JUnit 4 signifies that this method is a test case.
  6. Click on the quick-fix to Add JUnit 4 library to the build path, or edit the build path manually to point to Eclipse's plugins/org.junit_4.*.jar.
  7. Implement the testOdd method as follows:
    assertTrue(MathUtil.isOdd(3));
    assertFalse(MathUtil.isOdd(4));
  8. Add an import static of org.junit.Assert.* to fix the compiler errors.
  9. Right-click on the project and choose Run As | JUnit Test, and the JUnit test view should be shown with a green test result:
    Time for action – writing a simple JUnit 4 test case
  10. Verify that the test works by modifying the isOdd method to return false and re-running—a red test failure 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 that JUnit can be resolved and executed accordingly.

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

It is also possible to re-run tests from the JUnit view; the green run button allows all tests to be re-run, whilst the one with a red cross allows just the tests that have failed to be re-executed (shown as disabled in the previous example). It's also possible to re-run just a single test by right-clicking on the method in the JUnit view and selecting Run.

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

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