O'Reilly logo

Eclipse IDE Pocket Guide by Ed Burnette

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 5. Unit Testing with JUnit

JUnit is a regression testing framework written by Kent Beck and Erich Gamma. Since Erich is the project leader for Eclipse’s Java toolkit, it’s only natural that JUnit is well integrated into the IDE.

A Simple Factorial Demo

To try out unit testing in Eclipse, first create a project called Factorial containing a class called Factorial. Inside that class, create a factorial() method as follows:

	           public class Factorial {
		public static double factorial(int x) {
			if (x == 0)
				return 1.0;
			return x + factorial(x - 1);
		}
	}

Tip

If you notice the nasty little error in this code, ignore it for now. That’s part of the demonstration!

Creating Test Cases

To test this class, you’ll need to create a test case for it. A test case is a class that extends the JUnit TestCase class and contains test methods that exercise your code. To create a test case, right-click on Factorial.java in the Package Explorer and select New JUnit Test Case.

Tip

If you get a dialog offering to add the JUnit library to the build path, select Yes.

A dialog window will come up with the name of the test case (FactorialTest) already filled in, along with the name of the class being tested. Click Next to show the Test Methods dialog, select the factorial(int) method, and click Finish to generate the test case. Eclipse will then generate some code for you, similar to the following:

	           public class FactorialTest extends TestCase {
		public void testFactorial() {
		}
	}

Now, all you need to do is supply the contents ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required