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:

OSDebian 9 64-bit
JDKopenjdk version “1.8.0_141”
EclipseOxygen Release (4.7.0)
JUnitversion 4.12
Hamcrestversion 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:
  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.