This section explains how to write and run a simple JUnit case in Eclipse.
com.packtpub.e4.junit.example
.MathUtil
in com.packtpub.e4.junit.example
.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
).MathUtilTest
in the package com.packtpub.e4.junit.example
.testOdd()
with an annotation @Test
, which is how JUnit 4 signifies that this method is a test case.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.testOdd()
method as follows:assertTrue(MathUtil.isOdd(3)); assertFalse(MathUtil.isOdd(4));
static import
to org.junit.Assert.*
to fix the compile-time errors.isOdd()
method to return false
and re-run it—a red-colored test-failure text should be seen instead.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).