    <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  :: Test Driven Development of C# User Interfaces</title>
        <link>http://accu.org/index.php/journals/856</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>


        <h2>Journal Articles</h2>


<div class="xar-mod-head"><span class="xar-mod-title">CVu Journal Vol 17, #6 - Dec 2005 + Design of applications and programs</span></div>

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

                                            <a href="http://accu.org/index.php/journals/">All</a>

                     &gt;                         <a href="http://accu.org/index.php/journals/c76/">Journals</a>

                     &gt;                         <a href="http://accu.org/index.php/journals/c77/">CVu</a>

                     &gt;                         <a href="http://accu.org/index.php/journals/c93/">176</a>
                    (12)
<br />

                                            <a href="http://accu.org/index.php/journals/">All</a>

                     &gt;                         <a href="http://accu.org/index.php/journals/c13/">Topics</a>

                     &gt;                         <a href="http://accu.org/index.php/journals/c67/">Design</a>
                    (168)
<br />

                                            <a href="http://accu.org/index.php/journals/c93-67/">Any of these categories</a>

                    -                        <a href="http://accu.org/index.php/journals/c93+67/">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;Test Driven Development of C# User Interfaces</h1>
<p><strong>Author:</strong>&nbsp;Administrator</p>
<p>
<strong>Date:</strong> 02 December 2005 06:00:00 +00:00 or Fri, 02 December 2005 06:00:00 +00:00</p>
<p><strong>Summary:</strong>&nbsp;<p>In my last article I discussed the values in the Agile Manifesto and what they mean to mean. There are many practices that can be used to make yourself more agile. Short iterations, the planning game, pair programming, and refactoring are a few of the practices present in eXtreme programming. The practice of most value to me, and the practice that many recommend to use as a starting point, is Test Driven Development - TDD.</p></p>
<p><strong>Body:</strong>&nbsp;<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e20" id=
"d0e20"></a>Introduction</h2>
</div>
<p>In my last article I discussed the values in the Agile Manifesto
and what they mean to mean. There are many practices that can be
used to make yourself more agile. Short iterations, the planning
game, pair programming, and refactoring are a few of the practices
present in eXtreme programming. The practice of most value to me,
and the practice that many recommend to use as a starting point, is
Test Driven Development - TDD.</p>
<p>Once you have mastered test driven development there is a good
chance you, like me, will wonder how you ever developed without it.
That is a bold claim, and a fair response would be &quot;Why?&quot;. Below, I
tell you why I find it difficult, or at least very uncomfortable,
to develop without <span class="bold"><b>automated unit
tests</b></span> - to me it would be like coming to work naked. But
first you might want to know what Test Driven Development is. This
tutorial should give you a step towards understanding and mastering
test driven development - particularly in the arena of C# user
interfaces.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e30" id="d0e30"></a>What is
TDD?</h2>
</div>
<p>Test Driven Development is an iterative cycle in which you
incrementally build the functionality required. Briefly the cycle
(or at least my cycle) is:</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>Decide what requirement or part of a requirement to satisfy
next.</p>
</li>
<li>
<p>Write an <span class="bold"><b>automated</b></span> test for the
requirement.</p>
</li>
<li>
<p>Write the code so that and all other tests past.</p>
</li>
<li>
<p>Refactor the code so that it is of good design and quality and
all the tests still pass.</p>
</li>
</ul>
</div>
<p>After completing the tutorial I hope you will see that there are
finer grained steps to the cycle, e.g:</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p>Write test.</p>
</li>
<li>
<p>Compile test - test probably won't compile.</p>
</li>
<li>
<p>Add skeleton so test compiles.</p>
</li>
<li>
<p>Run test - test will fail.</p>
</li>
<li>
<p>Use dummy values to that the test passes.</p>
</li>
<li>
<p>Add real code so the test pasts.</p>
</li>
</ul>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e72" id="d0e72"></a>Why Use
TDD?</h2>
</div>
<p>There are many angles to the advantages of TDD. Here are my
reasons:</p>
<div class="itemizedlist">
<ul type="disc">
<li>
<p><span class="bold"><b>Confidence and progress.</b></span> With
each little new test that runs you are making progress. And after
the short period it takes to run all the test, you know that all
the progress you have made so far is still there. Contrast this
will manual testing - with each improvement if you wanted the same
confidence you would have to manually repeat all the tests. This
would take too long. So most people would only test the part they
have change, and perhaps a little more, and hope that they don't
break anything. </p>
</li>
<li>
<p><span class="bold"><b>Code quality.</b></span> When making the
test pass, you don't have to worry about code standards, variable
names, object structures, readability, re-use, patterns, etc. You
only care about getting code that works - doing the simplest thing
to make the test pass. When all the tests are running, you can then
look for opportunities to improve the design, readability etc of
the code knowing that the tests will prove that you haven't broken
anything. Without automated unit tests improvements to the design
and readability of code require manual re-run of the tests. Most
people will shy away from this sticking to their first solution.
The result is code that evolves in to a pile of uncontrolled
spaghetti.</p>
</li>
<li>
<p><span class="bold"><b>Progress again.</b></span> It becomes
easier to know where you are up to by putting in a test that fails
explaining what you were doing, and it becomes easier to decide
what to do next.</p>
</li>
<li>
<p><span class="bold"><b>Good design.</b></span> I have found that
a natural by-product of TDD is simple useful classes - probably
because they are easier to test.</p>
</li>
<li>
<p><span class="bold"><b>Planning.</b></span> As each requirement
is satisfied you have a measure of how much you have done, how fast
you are going, and when you can expect to finish.</p>
</li>
<li>
<p><span class="bold"><b>You know when you are done!</b></span>
When there are no more tests to write you are finished - time to
celebrate.</p>
</li>
</ul>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e108" id="d0e108"></a>The Unit Test
Harness</h2>
</div>
<p>Testing code using automated tests requires an automated unit
test harness of some form. This tutorial was tested using NUnit
2.1.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e113" id="d0e113"></a>Reading the
Article</h2>
</div>
<p>For each block of code that is introduced there are a few
interesting discussion points identified thus {1}. I would suggest
that these are ignored during the first reading.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e118" id="d0e118"></a>The
Requirements</h2>
</div>
<p>The problem is stolen from an article by Bill Wake that appeared
in Extreme Programming Installed [<a href=
"#Jeffries-">Jeffries-</a>].</p>
<p>We have bibliographic data with author, title, and year of
publication. Our goal is to write a system that can search that
information for values we specify. A Paper prototype has produced
an interface something like Figure 1 on the following page.</p>
<div class="figure"><a name="d0e128" id="d0e128"></a>
<div class="mediaobject c3"><img src="/var/uploads/journals/resources/drawing1.png"
align="middle" alt="Prototype Interface"></div>
<p class="title c4">Figure 1. Prototype Interface</p>
</div>
<p>The user will enter text to search for and click the Find
button. Any document that contains that text in the Author, Title
or Year will be displayed.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e136" id="d0e136"></a>The
Context</h2>
</div>
<p>When developing software it is usual for many to produce and
test the 'model' first and in isolation. In brief the model is the
part of the application that provides the functionality. The model
for this UI has already been produced - the interface for the model
(placed in <tt class="filename">model.cs</tt>) is:</p>
<pre class="programlisting">
using System;
namespace TDD_in_C_Sharp
{
  public interface ISearcher // {2}
  {
    IResult Find(Query q);
  }

  public class Query // {3}
  {
    private string theQuery;
    public Query(String s) { theQuery = s;}
    virtual public String Value // {1}
    { 
      get { return theQuery;}
    }
  }

  public interface IResult 
  {
    int Count();
    IDocument Item(int i);
  }

  public interface IDocument 
  {
    String Author();
    String Title();
    String Year();
  }
}
</pre>
<p>This should compile defining our interface with the rest of the
system.</p>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e148" id="d0e148"></a>Interesting
Points</h3>
</div>
<div class="orderedlist">
<ol type="1">
<li>
<p>I use virtual on all operations of a concrete class.
Unfortunately, the default for C# is that functions aren't virtual.
However, I know of very few reasons for having non virtual
functions.</p>
</li>
<li>
<p>The model has largely been defined as interfaces rather than
classes. There are many potential reasons for this. From a TDD
perspective it is because it allows us to use mock objects. When
testing a component it is likely that the component will use other
components. However, we often don't want to rely on those other
components for our tests to run - we'd rather test our component in
isolation. The use of interfaces means that in our tests we can
substitute the real components with mock ones that we have
programmed to supply data and behave as we'd like.</p>
</li>
<li>
<p>Here one of the objects (Query) is so simple that we haven't
bothered creating and interface and mocking it (we don't think that
is likely to bite us in the future).</p>
</li>
</ol>
</div>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e161" id="d0e161"></a>Test Widget
Existance</h2>
</div>
<p>The requirements prototyped a screen design. A first test is to
ensure the key controls are on the form: a label, a query field, a
table and a button. There may be other components on the form but
we don't care about them.[<a href="#Jeffries-">Jeffries-</a>]</p>
<p>In TDD, after establishing what requirement to test, you write a
test, and here it is - place in a new file (<tt class=
"filename">TestSearchForm.cs</tt>) but in the same name space.
Note: you will have to add a reference to <tt class=
"filename">NUnit.Framework.dll</tt>.</p>
<pre class="programlisting">
using System;
using NUnit.Framework;

namespace TDD_in_C_Sharp
{
  [TestFixture]
  public class UI_Tests
  {
    [Test]
    public void WidgetsPresent() 
    { 
      SearchForm form = new SearchForm();
      Assertion.AssertNotNull(form.searchLabel);
      Assertion.AssertNotNull(form.queryField);
      Assertion.AssertNotNull(form.findButton);
      Assertion.AssertNotNull(form.resultTable);
    }
  }
}
</pre>
<p>This does not compile because we have not created the form {2}.
So create a form as outlined above giving the controls the names
used in the tests (e.g. <tt class="varname">searchLabel</tt>). Try
to compile. The compilation fails because the tests do not have
access to the controls. Make the access internal by modifying the
<tt class="classname">SearchForm</tt> class as follows {4}:</p>
<pre class="programlisting">
public class SearchForm : System.Windows.Forms.Form
{
  internal System.Windows.Forms.Label searchLabel; // {4}
  internal System.Windows.Forms.TextBox queryField;
  internal System.Windows.Forms.Button findButton;
  internal 
     System.Windows.Forms.DataGrid resultTable; //{3}
 ... 
</pre>
<p>Run your test with NUnit - it should pass.</p>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e191" id="d0e191"></a>Interesting
Points</h3>
</div>
<div class="orderedlist">
<ol type="1">
<li>
<p>We could test the tab order and a few other things (e.g.
enablement and visibility) that is simple to do especially if you
have a AssertFunction to do it for you.</p>
</li>
<li>
<p>We have created the test without creating the object being
tested - defining the names of the widgets on the form. Thus this
code will not compile. In practice the two are created at the same
time. The order is not that important. The advantage of doing the
test first is that you only write enough of the search panel to get
it to compile so that you can run the test. A disadvantage is that
you can't take advantage of intellisense.</p>
</li>
<li>
<p>In my first implementation I used a list view for the table. I
did this because it was easy. A principle of TDD is to <span class=
"bold"><b>do the simplest thing that could possibly
work</b></span>. Once you have got your tests running you can
consider better ways of working. Later I replaced the list view
with the datagrid. Further, you often don't know what the simplest
thing is. This means you are going to have to take a diversion to
do some investigating - an activity often referred to as a
spike.</p>
</li>
<li>
<p>Defining the accessibility to be internal means that the object,
in this case controls, are visible to clients within this assembly.
If we wanted to move the test code into a separate assembly, we
would have to alter the accessibility or access the controls in
some other way.</p>
</li>
</ol>
</div>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e210" id="d0e210"></a>Test Initial
Values</h2>
</div>
<p>Here we are going to test that the controls are given the
correct initial values {1}{2}. Add a new test to the test
fixture:</p>
<pre class="programlisting">
[Test]
public void InitialContents() 
{
  SearchForm form  = new SearchForm();
  Assertion.AssertEquals(&quot;Search:&quot;, form.searchLabel.Text );
  Assertion.AssertEquals(&quot;&quot;, form.queryField.Text);
  Assertion.AssertEquals(&quot;Find&quot;,
                          form.findButton.Text);
  Assertion.Assert(
    &quot;Table starts empty&quot;,
    ((DataTable)(form.resultTable.DataSource))
     .Rows.Count == 0);
}
</pre>
<p>This code requires a reference to <tt class=
"classname">System.Data</tt>. It also fails because there is no
<tt class="classname">DataTable</tt> so create one in the form's
constructor:</p>
<pre class="programlisting">
public SearchForm()
{
  //
  // Required for Windows Form Designer support
  //
  InitializeComponent();

  this.resultTable.DataSource = new DataTable();
}
</pre>
<p>The cast in the test smells {3}. It is used to get the code
working and is necessary because <tt class=
"classname">DataSource</tt> is of type <tt class=
"classname">Object</tt> - time to refactor to make it beautiful -
readable - we'll do this by providing the <tt class=
"classname">DataTable</tt> as a property - hiding the ugliness.
Change the test first:</p>
<pre class="programlisting">
[Test]
public void InitialContents() 
{
  SearchForm form  = new SearchForm();
  Assertion.AssertEquals(&quot;Search:&quot;,
                          form.searchLabel.Text );
  Assertion.AssertEquals(&quot;&quot;, form.queryField.Text);
  Assertion.AssertEquals(&quot;Find&quot;,
                          form.findButton.Text);
  Assertion.Assert(
    &quot;Table starts empty&quot;, 
    form.ResultTableAsDataTable().Rows.Count == 0);
}
</pre>
<p>And then add a method to the form to supply the <tt class=
"varname">resultTable</tt> as a <tt class=
"classname">DataTable</tt>:</p>
<pre class="programlisting">
internal DataTable ResultTableAsDataTable()
{
  return  (DataTable) resultTable.DataSource;
}
</pre>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e250" id="d0e250"></a>Interesting
Points</h3>
</div>
<div class="orderedlist">
<ol type="1">
<li>
<p>Some people believe that automated unit testing of user
interfaces is difficult. The approach taken here is to treat the
User Interface as an object and test its behaviour as you would any
other.</p>
</li>
<li>
<p>The volume of test that you write in each iteration depends on,
amongst other things, confidence in what you are doing and personal
style. For example, whether or not controls are present on a form
and their initial values could be tested together if your prepared
to risk of going faster I normally prefer to take very small steps
and build up a consistent momentum.</p>
</li>
<li>
<p>The concept of foul smelling (offensive) code is an interesting
one. It might be hard to read, hard to write or something else
might be wrong with it. Either way your instinct tells you that it
can be improved and made to smell good. Improving bad smelling code
is part of the process of refactoring. That is, improving the code
to make is easier to read, easier to extend, easier to maintain,
and to remove duplication. Well written code just feels good!</p>
</li>
</ol>
</div>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e263" id="d0e263"></a>Connect
Search Form to a Searcher</h2>
</div>
<p>So far we have created a form for displaying the search result,
and checked its initial values. Now we want to attach the Form to
objects and test the form's behaviour to be tested in more detail.
First we will test the forms ability to attach to a searcher - any
object implements the <tt class="classname">ISearcher</tt>
interface. For our tests we will create an object that implements
the <tt class="classname">ISearcher</tt> interface - <tt class=
"classname">TestSearcher</tt> {1}.</p>
<p>As ever we'll start by writing a test describing how we expect
to be able to set and get the Form's Searcher.</p>
<pre class="programlisting">
[Test]
public void SearcherSetup() 
{ 
  ISearcher s = new TestSearcher();
  SearchForm form = new SearchForm(); 
  Assertion.Assert (&quot;Searcher not set&quot;,
                    form.Searcher != s); 
  form.Searcher = s; 
  Assertion.Assert(&quot;Searcher now set&quot;,
                   form.Searcher == s); // [3]
}
</pre>
<p>This won't compile because we don't yet have a <tt class=
"classname">TestSearcher</tt> and form doesn't have a Searcher
property. So we implement a Skeleton <tt class=
"classname">TestSearcher</tt>. This in turn requires an <tt class=
"classname">IResult</tt>. This in turn requires an <tt class=
"classname">IDocument</tt>. So we'll implement skeletons for all of
these. We'll create them in a separate file (<tt class=
"filename">mockmodel.cs</tt>) to keep the mock components
separate:</p>
<pre class="programlisting">
public class TestSearcher: ISearcher 
{ 
  public virtual IResult Find(Query q) 
  { 
    int count = 0; 
    try {count = Convert.ToInt32(q.Value);} 
    catch (Exception ignored) {} 

    return new TestResult(count); 
  } 

  public virtual Query makeQuery(String s) 
  {
    return new Query(s);
  }
}
</pre>
<p>And add a Searcher property to our search form [<a href=
"#Gamma-">Gamma-</a>]:</p>
<pre class="programlisting">
private ISearcher mySearcher;
public virtual ISearcher Searcher
{
  get { return mySearcher; }
  set {mySearcher = value; }
}
</pre>
<p>The test now runs and passes. So we are able to attach a
searcher to the form but the form doesn't do much.</p>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e309" id="d0e309"></a>Interesting
Points</h3>
</div>
<div class="orderedlist">
<ol type="1">
<li>
<p>We could use a proper <tt class="classname">ISearcher</tt>.
However, we wouldn't have control of the behaviour of the searcher
and we don't want to rely on it for our tests to pass. Instead we
create an implementation of the interface (a mock object) solely
for our testing purposes.</p>
</li>
<li>
<p>We want to the ability to associate a Searcher (<tt class=
"classname">ISearch</tt>) with our form. There are two ways of
doing it. The Searcher could be supplied as the object is created
and/or after the fact and thus allowing it to be changed. I have
chosen to allow it to be changed as it makes for an easier tutorial
- as ever we do the simplest thing first.</p>
</li>
<li>
<p>The test uses equality. Here equality uses the identity of the
object, i.e. if they are the same object they are equal. An
alternative is to use some definition based on the contents. E.g.
is they contain the same particular values they are considered
equal.</p>
</li>
</ol>
</div>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e328" id="d0e328"></a>Mock the
Searcher</h2>
</div>
<p>The next thing to do is populate the form from a Searcher - an
Object that supplies the <tt class="classname">ISearcher</tt>
interface. So we'll create a test searcher that implements
<tt class="classname">ISearcher</tt>. The string used in making a
search will be an integer that we'll use to tell us how many items
to return. We'll name the items <tt class="varname">a0</tt> (for
first author), <tt class="varname">t1</tt> (second title), etc.</p>
<p>Before implementing <tt class="classname">TestSearcher</tt> we
will, of course, write a test to test our <tt class=
"classname">TestSearcher</tt>.</p>
<pre class="programlisting">
[Test]
public void Searcher() 
{ 
Assertion.AssertEquals(new Query(&quot;1&quot;).Value, &quot;1&quot;);
// {1} 
  IDocument doc = new TestDocument(1);
  Assertion.AssertEquals(&quot;y1&quot;, doc.Year());

  IResult result = new TestResult(2); 
  Assertion.Assert(result.Count() == 2); 
  Assertion.AssertEquals(&quot;a0&quot;,
                         result.Item(0).Author());
  TestSearcher searcher = new TestSearcher(); 
  result = searcher.Find(searcher.makeQuery(&quot;2&quot;));
  Assertion.Assert(&quot;Result has 2 items&quot;,
                   result.Count() == 2); 
  Assertion.AssertEquals(&quot;y1&quot;,
                         result.Item(1).Year());
}
</pre>
<p>This fails to compile because <tt class=
"classname">TestDocument</tt> and <tt class=
"classname">TestResult</tt> don't have a constructor that takes a
single parameter (The integer will be used to name the documents).
And the classes (<tt class="classname">TestSeacher</tt> <tt class=
"classname">TestResult</tt> and <tt class=
"classname">TestDocument</tt>) have no implementation. So we'll
provide these:</p>
<pre class="programlisting">
public class TestSearcher: ISearcher 
{ 
  public virtual IResult Find(Query q) 
  { 
    int count = 0; 
    try {count = Convert.ToInt32(q.Value);} 
    catch (Exception ignored) {} 
    return new TestResult(count); 
  } 
  public virtual Query makeQuery(String s) 
  {
    return new Query(s);
  }
}

public class TestResult: IResult 
{ 
  int count; 
  public TestResult(int n) {count = n;} 
  public virtual int Count() {return count;} 
  public virtual IDocument Item(int i) 
     {return new TestDocument(i);}
} 

public class TestDocument: IDocument 
{ 
  int count; 
  public TestDocument(int n) {count = n;} 
  public virtual String Author() 
     {return &quot;a&quot; + count;}
  public virtual String Title() 
     {return &quot;t&quot; + count;} 
  public virtual String Year() {return &quot;y&quot; + count;} 
} 
</pre>
<p>Run the test and it should pass.</p>
<p>Now we can test the display of the search results. When testing
objects that can take a number of values it is usually a good idea
to test that it works with 0,1 and lots. Let's start with zero.</p>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e378" id="d0e378"></a>Interesting
Points</h3>
</div>
<div class="orderedlist">
<ol type="1">
<li>
<p>Several of the tests use <tt class=
"function">AssertEquals()</tt> rather than <tt class=
"function">Assert()</tt>. This is because the former can tell you
what values weren't equal when the test fails.</p>
</li>
</ol>
</div>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e391" id="d0e391"></a>Test 0</h2>
</div>
<p>Here is the code for the test where the number of items found by
the test is zero.</p>
<pre class="programlisting">
[Test]
public void InitialContents() 
{
  SearchForm form  = new SearchForm();
  Assertion.AssertEquals(&quot;Search:&quot;,
                         form.searchLabel.Text );
  Assertion.AssertEquals(&quot;&quot;, form.queryField.Text);
  Assertion.AssertEquals(&quot;Find&quot;,
                         form.findButton.Text);
  Assertion.Assert(&quot;Table starts empty&quot;,
                   form.ResultTableAsDataTable()
                   .Rows.Count == 0); // [1]
}
</pre>
<p>This doesn't compile because we don't have a <tt class=
"methodname">findButton_Click()</tt> method on the form. So add an
empty one.</p>
<pre class="programlisting">
private void findButton_Click(object sender, System.EventArgs e)
{
}
</pre>
<p>This doesn't compile either, <tt class=
"methodname">findButton_Click</tt> is not visible. So declare it as
internal so that the test class can see it.... And the tests
pass.</p>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e410" id="d0e410"></a>Interesting
Points</h3>
</div>
<div class="orderedlist">
<ol type="1">
<li>
<p>For the initial state there is a choice of having a table that
contains no rows or no table at all. We have used the former.</p>
</li>
</ol>
</div>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e417" id="d0e417"></a>Test 1</h2>
</div>
<pre class="programlisting">
[Test]
public void InitialContents() 
{
  SearchForm form  = new SearchForm();
  Assertion.AssertEquals(&quot;Search:&quot;,
                         form.searchLabel.Text );
  Assertion.AssertEquals(&quot;&quot;, form.queryField.Text);
  Assertion.AssertEquals(&quot;Find&quot;,
                         form.findButton.Text);
  Assertion.Assert(&quot;Table starts empty&quot;, 
     form.ResultTableAsDataTable().Rows.Count == 0);
}
</pre>
<p>The test fails because <tt class=
"methodname">findButton_Click()</tt> has no implementation.</p>
<p>When the button is clicked, the string in the text field is
translated into a query and the searcher finds a result for display
in the table. However, there is a type mis-match: the Searcher
gives us an <tt class="classname">IResult</tt>, but the display
table needs a <tt class="classname">DataSource</tt>.</p>
<p>Thus, we need something to adapt the <tt class=
"classname">IResult</tt> output to the <tt class=
"classname">DataSource</tt> needed. To achieve this we will create
an <tt class="classname">Adapter</tt> class that is given an
<tt class="classname">IResult</tt> and provides the <tt class=
"classname">DataTable</tt> interface. {1}</p>
<p>At this point I was tempted to write a test for the adapter but,
doing the simplest possible thing, the adapter only has to do
enough to satisfy the buttons needs so instead we'll start by
implementing the button as if the adapter existed. In the form:</p>
<pre class="programlisting">
internal void 
findButton_Click(object sender, System.EventArgs e)
{
  Query q = new Query(queryField.Text);
  resultTable.DataSource = new DataTableAdapter
     (Searcher.Find(q));
}
</pre>
<p>And to make it compile we'll stub the class placed class in its
own file (<tt class="filename">DataTableAdaptor.cs</tt>).</p>
<pre class="programlisting">
using System;
using System.Data;
namespace TDD_in_C_Sharp
{
  public class DataTableAdapter :  DataTable
  {
    public DataTableAdapter(IResult theResult)
    {
    }
  }
}
</pre>
<p>The test fails as we need to implement the constructor:</p>
<pre class="programlisting">
public DataTableAdapter(IResult theResult)
{
  this.Columns.Add(&quot;Author&quot;);
  this.Columns.Add(&quot;Title&quot;);
  this.Columns.Add(&quot;Year&quot;);
  for (int index=0; index &lt; theResult.Count();
       index++)
  {
    IDocument doc = theResult.Item(index);
    DataRow newRow = this.NewRow();
    newRow[&quot;Author&quot;] =
       theResult.Item(index).Author();
    newRow[&quot;Title&quot;] = theResult.Item(index).Title();
    newRow[&quot;Year&quot;] = theResult.Item(index).Year();
    this.Rows.Add(newRow);
  }
}
</pre>
<p>Test1 now passes. And so does test N:</p>
<pre class="programlisting">
[Test]
public void TestN() 
{
  ISearcher searcher = new TestSearcher();
  SearchForm form = new SearchForm(); 
  form.Searcher = new TestSearcher(); 
  form.queryField.Text=&quot;5&quot;; 
  form.findButton_Click(form.findButton ,
     new System.EventArgs ()); 
  Assertion.Assert(&quot;5-row result&quot;,
     form.ResultTableAsDataTable().Rows.Count == 5); 
  Assertion.AssertEquals(&quot;a0&quot;,
     form.ResultTableAsDataTable().Rows[0][0] );
  Assertion.AssertEquals(&quot;t3&quot;, 
     form.ResultTableAsDataTable().Rows[3][1] );
  Assertion.AssertEquals(&quot;y4&quot;, 
     form.ResultTableAsDataTable().Rows[4][2] );
}
</pre>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e471" id="d0e471"></a>Interesting
Points</h3>
</div>
<div class="orderedlist">
<ol type="1">
<li>
<p>Adapter is a design pattern described in more detail in
<i class="citetitle">Design Patterns</i> [<a href=
"#Gamma-">Gamma-</a>]</p>
</li>
</ol>
</div>
</div>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e484" id="d0e484"></a>Test For Left
Overs</h2>
</div>
<p>After running one search we want to make sure that the results
aren't present in any subsequent search.</p>
<pre class="programlisting">
public void LeftOvers() 
{ 
  ISearcher searcher = new TestSearcher();
  SearchForm form = new SearchForm(); 
  form.Searcher = new TestSearcher(); 
  form.queryField.Text=&quot;5&quot;; 
  form.findButton_Click(form.findButton,
     new System.EventArgs()); 
Assertion.Assert(form.ResultTableAsDataTable()
     .Rows.Count == 5); 
  form.queryField.Text=&quot;3&quot;; 
  form.findButton_Click(form.findButton ,
     new System.EventArgs()); 
  Assertion.Assert(form.ResultTableAsDataTable()
     .Rows.Count == 3); 
}
</pre>
<p>This test passes.</p>
</div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e493" id="d0e493"></a>Test the User
Interface</h2>
</div>
<p>Some times you might want to test some aspects of the appearance
of the user interface. For example, the relative position of
controls or overlapping controls. I haven't yet found it necessary
considering that aspect to be part of functional testing. It is,
however, useful to test the tab order:</p>
<pre class="programlisting">
[Test]
public void TabOrder()
{
  SearchForm form = new SearchForm(); 
  NUnit.Forms.FormAssertions.AssertTabOrder(form,
    &quot;queryField,findButton,resultTable&quot;);
}
</pre></div>
<div class="sect1" lang="en">
<div class="titlepage">
<h2><a name="d0e500" id="d0e500"></a>Refactoring -
Improving the Design</h2>
</div>
<p>We have got our application working - GREAT! Quality developers
would now work hard to improve the design - if possible.</p>
<p>The design metaphor used mirrored that used by Bill Wake in his
original article. It has given a basis for TDD of C# (and .net)
user interfaces. However, it is frequently stated that UI layer
should be very thin. What does this mean? Is the design so far thin
enough?</p>
<p>The Humble dialog [<a href="#dialog">dialog</a>] article argues
that the behaviour of the dialog (or Form) should be placed in an
intermediate 'Smart' object. The Smart object knows what should be
displayed and tells the form to display it. It knows how to respond
to events such as button clicks and the form should ask it to take
the appropriate response to a click. The form then becomes a set of
properties defining what to display, and a set of event handlers
that delegate to the Smart object. Testing involves driving this
smart object with Mock UI objects.</p>
<p>Martin Fowler suggests a similar approach in his article
<i class="citetitle">Model View Presenter</i>. Back in 1994 Phran
Ryder, in his MSc Thesis, used a similar approach in which he
referred to the smart object as the view-controller.</p>
<div class="sect2" lang="en">
<div class="titlepage">
<h3><a name="d0e517" id="d0e517"></a>What Are the
Pros and Cons of this Approach?</h3>
</div>
<div class="variablelist">
<dl>
<dt><span class="term">Cons</span></dt>
<dd>
<div class="orderedlist">
<ol type="1">
<li>
<p>It makes it more difficult to take advantage of the ADO set of
objects. Microsoft's ADO controls and classes can make it easier to
rapidly create an application. Such applications are to a great
extent the Smart GUI described in Domain Driven Design [<a href=
"#Evans">Evans</a>].</p>
</li>
<li>
<p>When the application is simple why go to the trouble of adding
another layer.</p>
</li>
</ol>
</div>
</dd>
<dt><span class="term">Pros</span></dt>
<dd>
<div class="orderedlist">
<ol type="1">
<li>
<p>The idea that forms should be properties and delegating event
handlers makes it easy to see whether the form is doing anything it
shouldn't. It is be important that the form only contains behaviour
that is relevant to its responsibilities.</p>
</li>
<li>
<p>Decouples the form and the model. Without the smart object, the
form could be coupled to many parts of its model. The smart object
would deal with all that coupling. Splitting the form into two
would be easy. But if you wanted to split the form in two you could
create the intermediate object at that point.</p>
</li>
</ol>
</div>
</dd>
</dl>
</div>
<p>So have we got anything in our form that should not be
there?</p>
<div class="orderedlist">
<ol type="1">
<li>
<p>We have a <tt class="classname">mySearcher</tt> bound to the
model - the form need not know about searchers.</p>
</li>
<li>
<p>We have code binding the data source to an ADO object in this
case a dataTable.</p>
</li>
<li>
<p>We have a Find button code to perform the query and bind the ADO
result to the data source - this code could be moved to the smart
object.</p>
</li>
<li>
<p>All the initialisation code is created by .net. Can't do much
about this.</p>
</li>
</ol>
</div>
<p>So there are a few opportunities for improvement....</p>
</div>
</div>
<div class="bibliography">
<div class="titlepage">
<h2><a name="d0e566" id="d0e566"></a>References</h2>
</div>
<div class="bibliomixed"><a name="Jeffries-" id="Jeffries-"></a>
<p class="bibliomixed">[Jeffries-] <span class=
"citetitle"><i class="citetitle">Extreme Programming
Installed</i></span>. Ron Jeffries, Ann Anderson, Chet Hendrickson.
Addison Wesley 2001. ISBN: 0-201-70842-6</p>
</div>
<div class="bibliomixed"><a name="Gamma-" id="Gamma-"></a>
<p class="bibliomixed">[Gamma-] <span class="citetitle"><i class=
"citetitle">Design Patterns:Elements of Reusable Object-Oriented
Software</i></span>. Eric Gamma, Richard Helm, Ralph Johnson, John
Vlissides. Addison-Wesley 1995. ISBN: 0 201 63361 2</p>
</div>
<div class="bibliomixed"><a name="dialog" id="dialog"></a>
<p class="bibliomixed">[dialog] <span class="bibliomisc"><a href=
"http://www.objectmentor.com/resources/articles/ThHumbleDialog.pdf"
target=
"_top">http://www.objectmentor.com/resources/articles/ThHumbleDialog.pdf</a></span></p>
</div>
<div class="bibliomixed"><a name="Evans" id="Evans"></a>
<p class="bibliomixed">[Evans] <span class="citetitle"><i class=
"citetitle">Domain-Driven Design: Tackling Complexity in the Heart
of Software</i></span>. Eric Evans. Addison-Wesley 2004 .ISBN: 0
321 12521 5</p>
</div>
</div>
</p>
<p><strong>Notes:</strong>&nbsp;</p>
<p><em>More fields may be available via dynamicdata ..</em></p>
</div>
</channel>
</rss>
