This part explains how to write and run a simple JUnit 4 test case in Eclipse.
com.packtpub.e4.junit.example
.MathUtil
in com.packtpub.e4.junit.example
.public static
method called isOdd
that takes an int
and returns a boolean
if it is an odd number (using value % 2 == 1
).MathUtilTest
in a package com.packtpub.e4.junit.example
.testOdd
with an annotation @Test
, which is the way JUnit 4 signifies that this method is a test case.plugins/org.junit_4.*.jar
.testOdd
method as follows:assertTrue(MathUtil.isOdd(3)); assertFalse(MathUtil.isOdd(4));
import static
of org.junit.Assert.*
to fix the compiler errors.isOdd
method to return false
and re-running—a red test failure 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 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.
18.119.160.154