Chapter 3. Organizing and building JUnit tests

 

This chapter covers

  • Deciding where to place production code and test code
  • Dealing with duplicate test code
  • Organizing special case tests
  • Building tests in various development environments

Once you understand the fundamentals of writing JUnit tests, the next step is to begin writing them. Once you open your favorite Java editor and begin writing test code, you need to decide into which package you should place the test code. Although this decision seems simple enough, there is a considerable difference between placing your test code in the same package as your production code[1] or in a different package. For that reason, we offer a few recipes to help you decide which to do.

1 We will use the terms production code and test code to differentiate the code that implements your system from the code that tests your system.

After deciding on a package for your tests, you can only type two words (public class) before you come to the class name of your new test. At this point you need to decide how to organize your tests into test case classes. Many tutorials on JUnit suggest writing one TestCase class per production class; however, those authors generally mean that to be a simple guideline for programmers just starting out. As you write your tests, the names you choose can tell you when it may be time to move tests into a new fixture. We provide a few recipes that describe when to reorganize your test code.

A place to start

3.1. Place test classes in the same package as production code

3.2. Create a separate source tree for test code

3.3. Separate test packages from production code packages

3.4. Factor out a test fixture

3.5. Factor out a test fixture hierarchy

3.6. Introduce a Base Test Case

3.7. Move special case tests to a separate test fixture

3.8. Build tests from the command line

3.9. Build tests using Ant

3.10. Build tests using Eclipse

sitemap