Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use JUnit with Eclipse

I am a long time user of Eclipse but a novice when it comes to JUnit. I have lots of java projects and I want to start writing test cases around the methods in those projects. I'm just wondering the best way to set up the Eclipse environment for this purpose. Let's assume I have a typical project with a typical src directory in a specified package. How do I attach test cases to that project. Some concerns: 1. I don't want the test cases to be part of any build that I create on the project. 2. I want to refer to the clases in the test-suite.

Do I set up a separate test directory under the package I want to test? Do I have a separate test package? What is the best way to do this?

like image 675
Elliott Avatar asked Sep 04 '11 23:09

Elliott


People also ask

How do I import JUnit tests into Eclipse?

Under the "Libraries" tab, click "Add Library", "JUnit", "Next", select "JUnit 4", and click "Finish". Import the homework files into the src folder.

Does Eclipse include JUnit?

In Eclipse, you create a JUnit test case by selecting in the main window menubar File -> New -> JUnit Test Case. Once you clicked on the item, a big dialog should pop out. In the pop up you can choose the JUnit version (4 is the one we use) and the package and class name of your test case.

Is JUnit pre installed in Eclipse?

Open eclipse → right click on project and click on property > Build Path > Configure Build Path and add the junit-4.10. jar in the libraries using the button Add External Jar. We assume that your Eclipse has inbuilt JUnit plugin.


1 Answers

It's pretty dead simple:

  • Drag or otherwise place the JUnit jar file into your lib folder, then modify your projects build settings to include it.
  • Create another source folder under your project called 'test'
  • Create your test packages underneath the 'test' source folder. Best practice is to mimic the package names of your application.
  • Create your test classes inside of the test packages. Best practices is to mimic your application classes that require testing, but append Test at the end of the name. So for example in your main application you might have a myapp.service.PrintService and as a corresponding test you would have myapp.service.PrintServiceTest
  • Extend each test class from junit.framework.TestCase
  • Run your test classes using TestRunner.

When you build your application's deployment bundle just exclude the 'test' source folder. Now, if you want really drop dead easy test integration then use Maven to setup your project. It bakes in all the best practices for you right off the bat.

like image 180
Perception Avatar answered Oct 11 '22 13:10

Perception