Technology: jUnit

Overview

Modern software development (particularly following agile methods like Scrum or XP) is test-driven. This means, that before (or at least immediately after) a piece of code (a method, a class) is written, the according test has to be written. This test is part of a complete test-suite, that eventually tests the whole application. These tests can be executed automatically and will report any undesired behaviour.

Using an appropriate test-strategy is crucial for developing robust software by multiple reasons:

  • The test can be seen as the specification of the functionality. Writing tests hand-in-hand with the implementation ensures a stable specification
  • Manual testing is unreliable: first, it is awkward (actually impossible) to test larger portions of code manually (and hence it is not done) and secondly, in a team-development setup, one single developer can have difficulties in testing other parts of the application, having lack of knowledge of the implementation details of other parts
  • Fine-grained automatically executed unit-tests not only give you confidence for your own code, but allow to detect, whether changes in your part of the code broke some other dependent code written by other developers (and vice versa).

The paradigma of Test Driven Development involves repeatedly first writing a test case and then implementing only the code necessary to pass the test. With such an automated test (a TestCase) you can rapidly get feedback and don't have to manually test every aspect of your software when you change only one module.

The now defacto-standard testing framework for Java is jUnit. jUnit makes writing a test really easy. Each test case is a class extending TestCase. Each testcases has a setUp() and a tearDown() function and one or many testXXX() functions. When running the unit test:

  • the TestCase is instantiated
  • the setUp() function is called
  • the next testXXX() function is called
  • the tearDown() function is called
  • If there is another testXXX() function, go back to the second step until all functions have been called

To see jUnit in action, you have a look at the Sourcecode of the unit tests in the basic example.

Reference

The official jUnit page can be found at http://www.junit.org.

To get started, have a look at the great tutorial at: http://junit.sourceforge.net/doc/testinfected/testing.htm.

TestDriven Development is also explain in great detail in C2s Pattern Wiki at: http://c2.com/cgi/wiki?TestDrivenDevelopment.