Reputation: 5609
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?
Upvotes: 12
Views: 5170
Reputation: 346240
The best (or at least the most common) way to organize the test code it is to have a separate source folder for the test code, thus keeping it nicely separated. In eclipse, you can add source folders under "Build Path" in the project's properties.
However, it is also a good idea to keep your test classes in the same packages as the classes to be tested (i.e. have the same package hierarchy in the test source folder). This allows you test code to call package private and protected methods, making it much easier to test internal behaviour that should not be exposed in the public API.
Upvotes: 3
Reputation: 80593
It's pretty dead simple:
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.
Upvotes: 8
Reputation: 46878
A simple solution would be to create another source directory specifically for test-related classes. For example, if your main classes live in $PROJECT_ROOT/src
, you can put your test-related classes in $PROJECT_ROOT/src-test
. I don't have Eclipse handy, but I know that you can modify the $PROJECT_ROOT/.classpath
file (it's XML) to include this new directory:
<classpath>
<classpathentry kind="src" path="src"/>
<classpathentry kind="src" path="src-test"/> <!-- ADD THIS ONE -->
...
</classpath>
Now, all your test classes will see the main classes, but they won't be included in your build. I typically make sure that the test class lives in the same package as the class it's testing. That way, any protected
members can be accessed from the test code.
Upvotes: 0