Classic Logic

Using JUnit with Eclipse

Recently, I set up Eclipse* to work with JUnit, and it took more effort than I anticipated. I’m recording the steps here so that I – or anybody else – can refer to it later if the need arises.

Here’s the environment I used:

OS Debian 9 64-bit
JDK openjdk version “1.8.0_141”
Eclipse Oxygen Release (4.7.0)
JUnit version 4.12
Hamcrest version 1.3

The above packages were at their latest versions when I wrote this article.

I assume you have already installed Eclipse and JDK. Here are the rest of the steps:

This may not work for everyone, but it definitely worked for me.

  1. In Eclipse, create a Java project if you haven’t already done so.
  2. Create the class you want to test.
  3. Right click on your project directory in the package explorer.
  4. Hover your mouse over New, then select JUnit Test Case.
  5. Fill in the necessary information in the dialog that opens up. Be sure to enter the name of the class you want to test (the one you created in step 2) in the Class under test: field.
  6. Click Finish.

You should now have a new Java class populated with stubs for testing functions of the class you created in step 2 above.

Method 2: The Hard Way

  1. Download junit JAR file.
  2. Download hamcrest-core JAR file. This is the step everybody skips and eventually trips up. According to Hamcrest wiki here, “Hamcrest is a framework for writing matcher objects allowing ‘match’ rules to be defined declaratively”. JUnit uses Hamcrest.
  3. Add JUnit and Hamcrest JAR file to your project as external libraries:
  • In Eclipse, create a Java project if you haven’t already done so.

  • Right click on your project directory in the package explorer.

  • Click Properties.

  • Click Java Build Path on the left pane in the window that open up (see screenshot below).

  • Click Libraries tab on the right pane.

  • Click Add External JARs... button on the right. A file explorer should open up. Browse to the location where you saved the JUnit JAR file, and select the JAR file.

  • Click Apply.

    Add JUnit

    Add JUnit

  • Repeat the procedure to add Hamcrest JAR file, and close the window.

  1. You’re done! Start coding!

Further Reading


* I know Eclipse is not the best IDE out there. My pick would be IntelliJ IDEA, but for now I’m stuck with Eclipse due to reasons that are not relevant here.