    <rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:admin="http://webns.net/mvcb/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:content="http://purl.org/rss/1.0/modules/content/">
     <channel>
        <title>ACCU  :: Introducing JUnit</title>
        <link>https://members.accu.org/index.php/articles/1136</link>
        <description>Professionalism in Programming</description>
        <dc:language>en-us</dc:language> 
        <dc:creator>Administrator</dc:creator> 
        <admin:generatorAgent rdf:resource="http://www.xaraya.org" /> 
        <admin:errorReportsTo rdf:resource="mailto:webeditor@accu.org" />
       <sy:updatePeriod>hourly</sy:updatePeriod>
       <sy:updateFrequency>1</sy:updateFrequency>
       <docs>http://backend.userland.com/rss</docs>




<div class="xar-mod-head"><span class="xar-mod-title">Programming Topics + CVu Journal Vol 13, #5 - Oct 2001</span></div>

<table border="0" cellpadding="1" cellspacing="0">
    <tbody>
    <tr>
        <td valign="top">
            Browse in :
       </td>
       <td valign="top">

                                            <a href="https://members.accu.org/index.php/articles/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c13/">Topics</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c65/">Programming</a>
<br />

                                            <a href="https://members.accu.org/index.php/articles/">All</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c76/">Journals</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c77/">CVu</a>

                     &gt;                         <a href="https://members.accu.org/index.php/articles/c118/">135</a>
<br />

                                            <a href="https://members.accu.org/index.php/articles/c65-118/">Any of these categories</a>

                    -                        <a href="https://members.accu.org/index.php/articles/c65+118/">All of these categories</a>
<br />
</td>
   </tr>
   </tbody>
</table>




<div class="xar-error">
   <p>
 <strong>Note:</strong> when you create a new publication type,
the articles module will automatically use the templates
<em>user-display-[publicationtype].xt</em>
and <em>user-summary-[publicationtype].xt</em>.
If those templates do not exist when you try to preview or display a new article,
you'll get this warning :-)  Please place your own templates in themes/<em>yourtheme</em>/modules/articles . The templates will get the extension .xt there. </p>
</div>
<div class="xar-norm xar-standard-box-padding">
   <h1><strong>Title:</strong>&nbsp;Introducing JUnit</h1>
<p><strong>Author:</strong>&nbsp;</p>
<p>
<strong>Date:</strong> 03 October 2001 13:15:47 +01:00 or Wed, 03 October 2001 13:15:47 +01:00</p>
<p><strong>Summary:</strong>&nbsp;<p>This article is based on an overview that I wrote to help introduce developers on a pilot project to unit testing. It covers the strategic reasons for using unit tests and the tactics of writing a unit test harness using the freely available JUnit framework to minimise the work involved.</p></p>
<p><strong>Body:</strong>&nbsp;<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e20" id="d0e20"></a></h2>
</div>
<p>One of the interesting things about software development is that
there is always something new to discover. And while the JUnit test
framework isn't new in &quot;internet time&quot; it is fairly new to me -
partly because I've only recently joined an organisation that works
primarily in Java.</p>
<p>Looking at test harnesses that I wrote prior to investigating
JUnit there is a striking similarity to the structure of the JUnit
framework - the main difference being that my test harnesses
classes had repetitive segments of &quot;boiler plate&quot; code in addition
to the tests themselves. I had been thinking of ways to factor out
this code into a unit test framework - but my embryonic design did
not reach the level of evolution of JUnit. I'd like to think that
JUnit is where I'd have reached after I'd &quot;thrown one away&quot;
[<a href="#Brooks">Brooks</a>].</p>
<p>This article is based on an overview that I wrote to help
introduce developers on a pilot project to unit testing. It covers
the strategic reasons for using unit tests and the tactics of
writing a unit test harness using the freely available JUnit
framework to minimise the work involved. It does not cover all the
options for using JUnit. More details and JUnit itself are
available from the JUnit website at <a href="http://www.junit.org/"
target="_top">http://www.junit.org/</a>.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e34" id="d0e34"></a>What is a unit
test for?</h2>
</div>
<p>A unit test exercises &quot;a unit&quot; of production code in isolation
from the full system and checks that the results are as expected.
The size of &quot;a unit&quot; to be tested depends on the size of a set of
coherent functionality and in practice varies between a class and a
package. The purpose is to identify bugs in the code being tested
prior to integrating the code into the rest of the system. JUnit
supports writing unit tests in Java for Java code.</p>
<p>The reason for identifying bugs before integration is that it is
far easier (i.e. quicker and cheaper) to identify and correct
problems (and demonstrate that the solution works) in
isolation.</p>
<p>This provides benefits both prior to the initial integration of
a piece and before integrating subsequent changes. If one needs to
change existing code the fact that the unit test still passes the
resulting code makes one more confident that the change doesn't
break anything. And the better the unit test the more confident one
can be - ideally the test should be updated to include the new
functionality prior to making the change (of course it then fails
until the change has been completed).</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e43" id="d0e43"></a>Who writes a
unit test and when?</h2>
</div>
<p>There are several schools of thought on this, all with merit.
The approach most likely to identify problems is for the unit test
and the production code to be developed independently against the
specification. This is the most likely to pick up misinterpretation
of, or ambiguities in, the specification. However, it is also the
most costly - two developers need to be involved, and there are
intimate dependencies between their work (even minor changes to a
method interface are disruptive).</p>
<p>An approach that has proved more popular recently - and is
promoted as part of &quot;Extreme Programming&quot; [XP] is to develop the
interface, the test harness, and the implementation. (In roughly
that order - although some parts of the implementation may be
completed before unrelated parts of the test harness). Actually,
since XP also promotes &quot;pair programming&quot; this also involves two
developers (although as they work together co-ordination isn't an
issue). Regardless of the adoption of other XP practices this
unit-testing regime is valid.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e50" id="d0e50"></a>What goes into
a test harness?</h2>
</div>
<p>Regardless of who writes the unit test or when, it should be
focused on exercising the code most at risk of being in error. (The
number of errors likely to be detected by exercising typical
&quot;<tt class="literal">setName()/getName()</tt>&quot; methods doesn't
usually justify writing a test for them).</p>
<p>If the design documentation contains usage scenarios for the
objects being tested then these are a good source of tests.
However, scenarios are often not written out explicitly where they
are readily apparent from other aspects of the design - if this is
the case then appropriate tests should be equally apparent.</p>
<p>Another good source of test cases is problems found in
production code after integration, the usage that manifests the
problem is often worth encapsulating into a test case.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e62" id="d0e62"></a>What is JUnit
for?</h2>
</div>
<p>The preceding discussion shows why we need test harnesses, but
why use JUnit?</p>
<p>A piece of test code cannot be run in isolation, it needs to be
part of a runtime environment. Also, it is desirable to automate
the running of unit tests - such as periodically running all the
test harnesses in the system to prove that nothing is broken. For
this unit tests need to meet certain criteria: a successful test
shouldn't need manual checking, a failed test should deliver
adequate documentation for diagnosis.</p>
<p>The running of tests, recording of results and reporting of
errors is common to all tests, and JUnit provides precisely this
functionality. All that the test developer needs to write is the
test code itself - and (despite some advertising that I've seen)
there is no avoiding that!</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e71" id="d0e71"></a>An Example</h2>
</div>
<p>The simplest possible JUnit test case looks something like
this:</p>
<pre class="programlisting">
import junit.framework.TestCase;
public class Test extends TestCase {
  public Test(String name) {
    super(name);
  }
  public void testSimpleTest() {
// Test Code goes here
  }
}
</pre>
<p>OK, I lied - not only is it necessary to write the test code, it
is also necessary to write a simple constructor. But the above is
enough to allow us to compile and run the test. The command lines
for compiling and running the test are similar to the
following:</p>
<pre class="programlisting">
javac -classpath &quot;.;../junit/junit.jar&quot; Test.java
java -classpath &quot;.;../junit/junit.jar&quot; junit.textui.TestRunner Test
</pre>
<p>The JUnit <tt class="literal">TestRunner</tt> returns a report
similar to the following:</p>
<pre class="programlisting">
.
Time: 0
OK (1 tests)
</pre>
<p>The test class can easily be extended by adding further tests,
for example:</p>
<pre class="programlisting">
public void testHelloWorld()
{
  String hello = &quot;Hello&quot;;  
  String world = &quot;world&quot;;  
  assertEquals(&quot;Hello world&quot;, hello+world);
}
</pre>
<p>This test code makes use of <tt class=
"literal">assertEquals</tt> - one of a number of assertion methods
provided by the JUnit interface <tt class="literal">Assert</tt>.
There are overloaded variants of <tt class=
"literal">assertEquals</tt> to deal with various types of
parameter, including the base types, containers, and <tt class=
"literal">String</tt>s - if the two parameters are equal then it
simply returns, otherwise it throws an unchecked exception used
within the framework to report on the error.</p>
<p>The result of all this is that when the above test is executed
(in the same way), the results would show the failure of the test
as follows:</p>
<pre class="programlisting">
..F
Time: 0.01
There was 1 failure:
1) testHelloWorld(Test) &quot;expected:Hello world but was:Helloworld&quot;
FAILURES!!!
Tests run: 2,  Failures: 1,  Errors: 0
</pre></div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e111" id="d0e111"></a>Working with
JUnit</h2>
</div>
<p>In the working practices I introduced it is the responsibility
of each developer to ensure that JUnit test classes are submitted
to support every piece of work. The piece of work is not complete
until the test code is provided and Unit Testing has been performed
satisfactorily. (Exceptions are made for some pieces of work, such
as user interface components - these are tested visually.)</p>
<p>This approach is, of course, a compromise between complete trust
in developers and independently verifying all work done. It may not
work in all environments or with all developers. However, the
situation I was faced with is common (far too common) in our
industry: that of developers under pressure to deliver and lacking
adequate support from the organisation for maintaining a
&quot;professional standard&quot; of code. We all know the results: slapdash
code that barely compiles, long sessions debugging (or rewriting)
code that was &quot;finished&quot; long ago...</p>
<p>Adopting JUnit has made the process of introducing test
harnesses easier than my previous experiences. Naturally there are
other variables (management support is a big one). But I'm sure
that the effectiveness with which the JUnit design separates
&quot;framework&quot; from the specific test is a major factor. Another
factor is its integration with &quot;Ant&quot; (<a href=
"http://jakarta.apache.org/" target=
"_top">http://jakarta.apache.org/</a>) - however, Ant is the
subject of another article.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e123" id=
"d0e123"></a>Conclusions</h2>
</div>
<p>So, apart from &quot;I wish I'd written it first&quot;, what do I think of
JUnit? It is easy to use, easy to introduce into a project, and
does its job.</p>
<p>In the pilot project the use of unit tests has had a very
visible effect on both the scheduling (tasks rarely overrun because
of the need to debug &quot;finished&quot; code already in the project
codebase) and morale (development tasks have clearly delimited
boundaries).</p>
</div>
<div class="bibliography">
<div class="titlepage">
<h2><a name="d0e130" id="d0e130"></a>References</h2>
</div>
<div class="bibliomixed"><a name="Brooks" id="Brooks"></a>
<p class="bibliomixed">[Brooks] &quot;<span class="citetitle"><i class=
"citetitle">The Mythical Man-Month</i></span>&quot; 1975</p>
</div>
</div>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
