Test First

Having a good suite of tests is important—so important, that many developers advocate writing the tests for new code before a single line of the code itself! This is called test driven development, or TDD for short. Such tests represent the requirements that your code must satisfy in order to be considered correct.

To see how Eclipse makes TDD simple, keep the unit test you just created, but delete the Factorial.java file (select it in the Package Explorer and press Delete). The editor for the FactorialTest class will shown an error immediately because the Factorial class is not defined anymore. This simulates the state you would be in if you had written your test class first.

Put the text cursor on the first line that has an error and press Ctrl+1 (Edit → Quick Fix). Select the "Create class 'Factorial'" option and press Enter. When the New Java Class dialog appears, press Enter to accept the defaults.

Now, go back to the FactorialTest editor and note that the compiler complains that there is no factorial(int) method. Press Ctrl+1 to create one.

Unfortunately, the current version of Eclipse is not always smart enough to figure out the right return type, so you may need to change the generated return type to be a double. Use a dummy return value (0.0) for now. At this point, Factorial.java should look something like this:

	           public static double factorial(int i) {
		return 0.0;
	}

Tip

Of course, this is not the right way to calculate a factorial, but all you want to do at this ...

Get Eclipse IDE Pocket Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.