DekGenius.com
Previous Section  < Day Day Up >  Next Section

Recipe 5.1 Installing JUnit

5.1.1 Problem

You want to install JUnit so that you can use it in Eclipse.

5.1.2 Solution

Add junit.jar to your project's classpath.

5.1.3 Discussion

In Eclipse 2.1.x and in the current versions of Eclipse 3.0, you can find junit.jar in eclipse/plugins/org.junit_3.8.1/junit.jar.

If you're going to be using JUnit regularly, it helps to create a new classpath variable; I named mine JUNIT. Select Window Preferences Java Classpath Variables, and click the New button to open the New Variable Entry dialog; now enter the name of the new variable—JUNIT—and the path to junit.jar.

You also can let Eclipse know where JUnit's source code is; this is a useful step for debugging, giving Eclipse access to a JAR file's code so that it can display it as needed. Note that this is an optional step because you don't need to see the JUnit code. To create a new variable for the JUnit source, which we'll call JUNIT_SRC, connect that variable to eclipse/plugins/org.eclipse.jdt.source_x.y.z/src/org.junit_3.8.1/junitsrc.zip, where x.y.z is your version of Eclipse. Then right-click your project, click Properties, click the Java Build Path node and the Libraries tab, and then expand the node for the JUNIT entry, as shown in Figure 5-1.

Figure 5-1. Making source code accessible to Eclipse
figs/ecb_0501.gif


When you expand a JAR file's node, you can specify where to find the associated source code and Javadoc. To use JUNIT_SRC for the source code here, select "Source attachment" in the expanded node, and click Edit to open the Source Attachment Configuration dialog. Click the Variable button, double-click JUNIT_SRC, and click OK to close this dialog. You can see the results in Figure 5-2, in which we've made the source for JUnit accessible to Eclipse. Click OK to close the Properties dialog.

Figure 5-2. Connecting source code to a .jar file
figs/ecb_0502.gif


This is the way you're supposed to do things—i.e., adding junit.jar to the build path yourself. But it turns out that if you don't do it this way, you haven't lost much. As soon as you try to build a JUnit test case, the JUnit plug-in will ask you if you want to add junit.jar to the build path automatically if you haven't already done so. In this case, the plug-in will do all the work for you.


5.1.4 See Also

Recipe 4.11 on using .jar and .class files; Recipe 5.2 on testing an application with JUnit; the JUnit section of the Java Extreme Programming Cookbook (O'Reilly).

    Previous Section  < Day Day Up >  Next Section