<?xml version="1.0" encoding="utf-8"?>
<rss xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:pingback="http://madskills.com/public/xml/rss/module/pingback/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:dc="http://purl.org/dc/elements/1.1/" version="2.0">
  <channel>
    <title>TJ Solutions - WEWLC</title>
    <link>http://www.tjsolutions.nl/</link>
    <description />
    <language>en-us</language>
    <copyright>Tijmen van de Kamp, Tom de Koning</copyright>
    <lastBuildDate>Tue, 15 Sep 2009 20:31:59 GMT</lastBuildDate>
    <generator>newtelligence dasBlog 2.3.9074.18820</generator>
    <managingEditor>blog@tjsolutions.nl</managingEditor>
    <webMaster>blog@tjsolutions.nl</webMaster>
    <item>
      <trackback:ping>http://www.tjsolutions.nl/Trackback.aspx?guid=d5fbb2c1-e30f-42b1-9abb-3706503c33e2</trackback:ping>
      <pingback:server>http://www.tjsolutions.nl/pingback.aspx</pingback:server>
      <pingback:target>http://www.tjsolutions.nl/PermaLink,guid,d5fbb2c1-e30f-42b1-9abb-3706503c33e2.aspx</pingback:target>
      <dc:creator>Tom</dc:creator>
      <wfw:comment>http://www.tjsolutions.nl/CommentView,guid,d5fbb2c1-e30f-42b1-9abb-3706503c33e2.aspx</wfw:comment>
      <wfw:commentRss>http://www.tjsolutions.nl/SyndicationService.asmx/GetEntryCommentsRss?guid=d5fbb2c1-e30f-42b1-9abb-3706503c33e2</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
This is the third posting in the <a href="http://www.tjsolutions.nl/2009/06/01/AnnouncingTheSeriesWorkingWithLegacyCode.aspx" target="_blank">WEWLC-series</a>. 
</p>
        <p>
 
</p>
        <p>
Other posts are:
</p>
        <p>
          <a href="http://www.tjsolutions.nl/2009/09/14/WEWLCICantGetThisClassIntoATestHarness.aspx" target="_blank">I
Can't Get This Class into a Test Harness</a>
        </p>
        <p>
          <a href="http://www.tjsolutions.nl/2009/09/12/WEWLCIDontHaveMuchTimeAndIHaveToChangeIt.aspx" target="_blank">I
don't have much time and I have to change it</a>
        </p>
        <p>
          <a href="http://www.tjsolutions.nl/2009/09/12/WEWLCAssumptions.aspx" target="_blank">Assumptions
on the reader</a>
        </p>
        <p>
 
</p>
        <p>
"Getting tests in place to make changes can be a bit of a problem. If you can instantiate
your class separately in a test harness, consider yourself lucky." 
</p>
        <p>
Instantiating a class should not be hard, if you do have issues have a look at <a href="http://www.tjsolutions.nl/2009/09/14/WEWLCICantGetThisClassIntoATestHarness.aspx" target="_blank">I
Can't Get This Class into a Test Harness</a>. That should take care of most of your
problems. 
</p>
        <p>
But instantiating is often just the first part of all the hurdles to take. The second
part is writing a test for the methods inside. 
</p>
        <p>
 
</p>
        <p>
Fortunately, in most cases, the amount of work that we have to do to write tests for
methods isn't as drastic. Here are some of the problems that we can run into.<a name="ch10index03"></a><a name="ch10index04"></a><a name="ch10index05"></a></p>
        <ul>
          <li>
            <p>
The method may be private
</p>
          </li>
          <li>
            <p>
The method may be hard to call because it has parameters that are hard to construct
</p>
          </li>
          <li>
            <p>
The method might have bad side effects (modifying a database, writing to the file
system etc)
</p>
          </li>
        </ul>
        <p>
          <strong>
          </strong>
        </p>
        <p>
          <strong>The Case of the Hidden Method</strong>
        </p>
        <p>
If we need to write a test for a private method we need to make it public. There are
some tricks in getting visibility on the method in your tests but I don't recommend
it. First of all, if there is a need for private method odds are that what you need
is a another collaborator. 
</p>
        <p>
This is of course a rather fundamental discussion. If you do care about keeping the
method invisible to callers you can make it protected. Once it is protected you can
derive a test class and add a public method that will simply call the protected method
in the base class.
</p>
        <p>
In most cases I would recommend moving the method to a separate class and inject it
into the constructor of the class that interacts with it. Once there is a need to
alter the behavior of a private method it is obviously doing something important,
hence, it should be under test.
</p>
        <p>
 
</p>
        <p>
          <strong>The Case of the "Helpful" Language Feature </strong>
        </p>
        <p>
Michael Feather is referring to sealed classes that don't have constructor. How do
you test interaction code that takes such a class as a parameter in a method? Let's
have a look at an example:
</p>
        <pre class="code">
          <span style="color: blue">public class </span>
          <span style="color: #2b91af">StreamHelper </span>{ <span style="color: blue">const
int </span>MIN_LEN = 4; <span style="color: blue">public </span><span style="color: #2b91af">IList </span>GetStreams(<span style="color: #2b91af">HttpFileCollection </span>files)
{ <span style="color: blue">var </span>list = <span style="color: blue">new </span><span style="color: #2b91af">List</span>&lt;<span style="color: #2b91af">Stream</span>&gt;(); <span style="color: blue">foreach </span>(<span style="color: blue">string </span>name <span style="color: blue">in </span>files)
{ <span style="color: #2b91af">HttpPostedFile </span>file = files[name]; <span style="color: blue">if </span>((file.FileName.EndsWith(<span style="color: #a31515">".txt"</span>)
&amp;&amp; file.ContentLength &gt; MIN_LEN)) { list.Add(file.InputStream); } } <span style="color: blue">return </span>list;
} }</pre>
        <a href="http://11011.net/software/vspaste">
        </a>
        <p>
According to <a href="http://msdn.microsoft.com/en-us/library/system.web.httpfilecollection.aspx" target="_blank">MSDN</a>,
the HttpFileCollection provides access to and organizes files uploaded by a client.
Since this class is sealed and only has an internal constructor, how can you test
this method?
</p>
        <p>
Turns out that HttpFileCollection derives from NameObjectCollectionBase which has
a parameterless constructor which is protected. If we thus derive from NameObjectCollectionBase,
implement the indexer required and change the signature of the GetStreams method a
bit to take our custom class instead of the HttpFileCollection we should be able to
get going. 
</p>
        <p>
 
</p>
        <p>
Please note, this is going to be a hefty refactoring. Right, lets get down to it.
First let's create a fixture for our tests:
</p>
        <pre class="code">[<span style="color: #2b91af">TestFixture</span>] <span style="color: blue">public
class </span><span style="color: #2b91af">HttpCollectionTests </span>{ [<span style="color: #2b91af">Test</span>] <span style="color: blue">public
void </span>can_instantiate_a_derived_class_from_NameObjectCollectionBase() { <span style="color: blue">var </span>customHttpFileCollection
= <span style="color: blue">new </span><span style="color: #2b91af">CustomHttpFileCollection</span>(); <span style="color: blue">var </span>collectionBase
= customHttpFileCollection <span style="color: blue">as </span><span style="color: #2b91af">NameObjectCollectionBase</span>;
collectionBase.ShouldNotBeNull(); } }</pre>
        <a href="http://11011.net/software/vspaste">
        </a>
        <p>
 
</p>
        <p>
This means deriving from NameObjectCollectionBase
</p>
        <pre class="code">
          <span style="color: blue">public class </span>
          <span style="color: #2b91af">CustomHttpFileCollection </span>: <span style="color: #2b91af">NameObjectCollectionBase </span>{
}</pre>
        <p>
The next test is to be able to call GetStreams() in StreamHelper. Rather than changing
the existing method we are going to create a new method with the same name, but different
signature so that we can call it with our new CustomerHttpFileCollection:
</p>
        <pre class="code">[<span style="color: #2b91af">Test</span>] <span style="color: blue">public
void </span>can_use_the_custom_class() { <span style="color: blue">var </span>collection
= <span style="color: blue">new </span><span style="color: #2b91af">CustomHttpFileCollection</span>(); <span style="color: blue">new </span><span style="color: #2b91af">StreamHelper</span>().GetStreams(collection);
}</pre>
        <pre class="code">
          <span style="color: blue">public </span>
          <span style="color: #2b91af">IList</span>&lt;<span style="color: #2b91af">Stream</span>&gt;
GetStreams(<span style="color: #2b91af">CustomHttpFileCollection </span>files) { <span style="color: blue">var </span>list
= <span style="color: blue">new </span><span style="color: #2b91af">List</span>&lt;<span style="color: #2b91af">Stream</span>&gt;(); <span style="color: blue">foreach </span>(<span style="color: blue">string </span>name <span style="color: blue">in </span>files)
{ <span style="color: #2b91af">HttpPostedFile </span>file = files[name]; <span style="color: blue">if </span>((file.FileName.EndsWith(<span style="color: #a31515">".txt"</span>)
&amp;&amp; file.ContentLength &gt; MIN_LEN)) { list.Add(file.InputStream); } } <span style="color: blue">return </span>list;
}</pre>
        <p>
          <a href="http://11011.net/software/vspaste">
          </a>This means implementing the indexer
used in GetStreams() in our custom class. Luckily Resharper knows what to do and we
can use ALT-ENTER to generate the code. Next to the indexer we will also need an IList
to store the files and a method to add them to the internal collection:
</p>
        <pre class="code">
          <span style="color: blue">public class </span>
          <span style="color: #2b91af">CustomHttpFileCollection </span>: <span style="color: #2b91af">NameObjectCollectionBase </span>{ <span style="color: blue">public </span><span style="color: #2b91af">HttpPostedFile </span><span style="color: blue">this</span>[<span style="color: blue">string </span>name]
{ <span style="color: blue">get </span>{ <span style="color: blue">return </span>httpPostedFiles.Where(s
=&gt; s.FileName == name).FirstOrDefault(); } } }</pre>
        <p>
This poses a bit of an issue; we can instantiate a HttpPostedFile so how are we going
to populate an internal collection? Since this one is sealed, does not have a suitable
base class and has no constructors we need to be creative. We need a custom implementation
of the HttpPostedFile. First we create an interface, then define the same members
on the interface as are in the HttpPostedFile class. Once that is done we can change
the signature of the indexer to IHttpPostedFile and add some logic to store and add
the files to the collection class, like so:
</p>
        <pre class="code">
          <span style="color: blue">public class </span>
          <span style="color: #2b91af">CustomHttpFileCollection </span>: <span style="color: #2b91af">NameObjectCollectionBase </span>{ <span style="color: blue">readonly </span><span style="color: #2b91af">IList</span>&lt;<span style="color: #2b91af">IHttpPostedFile</span>&gt;
httpPostedFiles = <span style="color: blue">new </span><span style="color: #2b91af">List</span>&lt;<span style="color: #2b91af">IHttpPostedFile</span>&gt;(); <span style="color: blue">public </span><span style="color: #2b91af">IHttpPostedFile </span><span style="color: blue">this</span>[<span style="color: blue">string </span>name]
{ <span style="color: blue">get </span>{ <span style="color: blue">return </span>httpPostedFiles.Where(s
=&gt; s.FileName == name).FirstOrDefault(); } } <span style="color: blue">public void </span>AddHttpPostedFile(<span style="color: #2b91af">IHttpPostedFile </span>file)
{ httpPostedFiles.Add(file); } }</pre>
        <pre class="code">
          <span style="color: blue">public interface </span>
          <span style="color: #2b91af">IHttpPostedFile </span>{ <span style="color: blue">int </span>ContentLength
{ <span style="color: blue">get</span>; } <span style="color: blue">string </span>ContentType
{ <span style="color: blue">get</span>; } <span style="color: blue">string </span>FileName
{ <span style="color: blue">get</span>; } <span style="color: #2b91af">Stream </span>InputStream
{ <span style="color: blue">get</span>; } }</pre>
        <p>
Change the HttpPostedFile to the new IHttpPostedFile in GetStreams():
</p>
        <pre class="code">
          <span style="color: blue">public </span>
          <span style="color: #2b91af">IList</span>&lt;<span style="color: #2b91af">Stream</span>&gt;
GetStreams(<span style="color: #2b91af">CustomHttpFileCollection </span>files) { <span style="color: blue">var </span>list
= <span style="color: blue">new </span><span style="color: #2b91af">List</span>&lt;<span style="color: #2b91af">Stream</span>&gt;(); <span style="color: blue">foreach </span>(<span style="color: blue">string </span>name <span style="color: blue">in </span>files)
{ <span style="color: #2b91af">IHttpPostedFile </span>file = files[name]; <span style="color: blue">if </span>((file.FileName.EndsWith(<span style="color: #a31515">".txt"</span>)
&amp;&amp; file.ContentLength &gt; MIN_LEN)) { list.Add(file.InputStream); } } <span style="color: blue">return </span>list;
}</pre>
        <a href="http://11011.net/software/vspaste">
        </a>
        <pre class="code"> </pre>
        <a href="http://11011.net/software/vspaste">
        </a>
        <p>
Now that we have set up the collection, let's write a test to see if it all works
</p>
        <pre class="code">
          <span style="color: #2b91af">Stream </span>GetStream() { <span style="color: blue">const
string </span>s = <span style="color: #a31515">"hello world"</span>; <span style="color: blue">var </span>memoryStream
= <span style="color: blue">new </span><span style="color: #2b91af">MemoryStream</span>(System.Text.<span style="color: #2b91af">Encoding</span>.Default.GetBytes(s)); <span style="color: blue">return </span>memoryStream;
}</pre>
        <a href="http://11011.net/software/vspaste">
        </a>
        <a href="http://11011.net/software/vspaste">
        </a>
        <pre class="code">[<span style="color: #2b91af">Test</span>] <span style="color: blue">public
void </span>can_use_the_customcollection_to_test_the_StreamHelper_class() { <span style="color: blue">var </span>collection
= <span style="color: blue">new </span><span style="color: #2b91af">CustomHttpFileCollection</span>(); <span style="color: blue">var </span>httpPostedFile
= <span style="color: #2b91af">MockRepository</span>.GenerateMock&lt;<span style="color: #2b91af">IHttpPostedFile</span>&gt;();
httpPostedFile.Stub(s =&gt; s.InputStream).Return(GetStream()); httpPostedFile.Stub(s
=&gt; s.FileName).Return(<span style="color: #a31515">"somefilename.txt"</span>);
httpPostedFile.Stub(s =&gt; s.ContentLength).Return(5); collection.AddHttpPostedFile(httpPostedFile); <span style="color: #2b91af">IList</span>&lt;<span style="color: #2b91af">Stream</span>&gt;
streams = <span style="color: blue">new </span><span style="color: #2b91af">StreamHelper</span>().GetStreams(collection);
streams.Count.ShouldEqual(1); }</pre>
        <p>
When we execute this test a lot is happening. First I create a mock of the IHttpPostedFile
interface so that I can stub the properties. This allows me to test the method without
having an actual implementation of the interface. Not that it would have complicated
things tremendously, but it's a nice technique.
</p>
        <p>
I also use a convenient helper method to get me a stream. This will come in handy
later when I want to verify the outcome of the GetStreams() method.
</p>
        <p>
Let's execute and:
</p>
        <p>
 
</p>
        <p>
------ Test started: Assembly: Koning.WEWLC.Tests.dll ------ 
</p>
        <p>
TestCase 'Koning.WEWLC.Tests.HttpCollectionTests.can_use_the_customcollection_to_test_the_StreamHelper_class' 
<br />
failed: 
<br />
  Expected: 1 
<br />
  But was:  0 
<br />
    at Machine.Specifications.NUnitShouldExtensionMethods.ShouldEqual(Object
actual, Object expected) 
<br />
    C:\Dev\Personal\WEWLC\Koning.WEWLC\Koning.WEWLC.Tests\Tests\HttpCollectionTests.cs(59,0):
at Koning.WEWLC.Tests.HttpCollectionTests.can_use_the_customcollection_to_test_the_StreamHelper_class() 
</p>
        <p>
0 passed, 1 failed, 0 skipped, took 1.37 seconds. 
</p>
        <p>
 
</p>
        <p>
Why is this happening? My bad, I didn't implement GetEnumerator() on the custom collection
class. This is easily fixed however:
</p>
        <pre class="code">
          <span style="color: blue">public class </span>
          <span style="color: #2b91af">CustomHttpFileCollection </span>: <span style="color: #2b91af">NameObjectCollectionBase</span>, <span style="color: #2b91af">IEnumerable </span>{ <span style="color: blue">readonly </span><span style="color: #2b91af">IList</span>&lt;<span style="color: #2b91af">IHttpPostedFile</span>&gt;
httpPostedFiles = <span style="color: blue">new </span><span style="color: #2b91af">List</span>&lt;<span style="color: #2b91af">IHttpPostedFile</span>&gt;(); <span style="color: blue">public </span><span style="color: #2b91af">IHttpPostedFile </span><span style="color: blue">this</span>[<span style="color: blue">string </span>name]
{ <span style="color: blue">get </span>{ <span style="color: blue">return </span>httpPostedFiles.Where(s
=&gt; s.FileName == name).FirstOrDefault(); } } <span style="color: blue">public new </span><span style="color: #2b91af">IEnumerator</span>&lt;<span style="color: blue">string</span>&gt;
GetEnumerator() { <span style="color: blue">return </span>httpPostedFiles.Select(s
=&gt; s.FileName).GetEnumerator(); } <span style="color: #2b91af">IEnumerator IEnumerable</span>.GetEnumerator()
{ <span style="color: blue">return </span>GetEnumerator(); } <span style="color: blue">public
void </span>AddHttpPostedFile(<span style="color: #2b91af">IHttpPostedFile </span>file)
{ httpPostedFiles.Add(file); } }</pre>
        <a href="http://11011.net/software/vspaste">
        </a>
        <p>
I'm using some Linq goodness to get to the filenames and iterate over that. Next up
is refining our test and run it again:
</p>
        <pre class="code">[<span style="color: #2b91af">Test</span>] <span style="color: blue">public
void </span>can_use_the_customcollection_to_test_the_StreamHelper_class() { <span style="color: blue">var </span>collection
= <span style="color: blue">new </span><span style="color: #2b91af">CustomHttpFileCollection</span>(); <span style="color: blue">var </span>httpPostedFile
= <span style="color: #2b91af">MockRepository</span>.GenerateMock&lt;<span style="color: #2b91af">IHttpPostedFile</span>&gt;();
httpPostedFile.Stub(s =&gt; s.InputStream).Return(GetStream()); httpPostedFile.Stub(s
=&gt; s.FileName).Return(<span style="color: #a31515">"somefilename.txt"</span>);
httpPostedFile.Stub(s =&gt; s.ContentLength).Return(5); collection.AddHttpPostedFile(httpPostedFile); <span style="color: #2b91af">IList</span>&lt;<span style="color: #2b91af">Stream</span>&gt;
streams = <span style="color: blue">new </span><span style="color: #2b91af">StreamHelper</span>().GetStreams(collection);
streams.Count.ShouldEqual(1); streams.First().Length.ShouldBeGreaterThan(0); <span style="color: blue">new </span><span style="color: #2b91af">StreamReader</span>(streams.First()).ReadLine().ShouldContain(<span style="color: #a31515">"hello
world"</span>); }</pre>
        <p>
------ Test started: Assembly: Koning.WEWLC.Tests.dll ------ 
</p>
        <p>
1 passed, 0 failed, 0 skipped, took 1.48 seconds. 
</p>
        <p>
 
</p>
        <p>
Now note that when using the GetStreams() method one would have to transform the items
in HttpPostedFileCollection to the IHttpPostedFile interface before using it. 
</p>
        <p>
 
</p>
        <p>
 
</p>
        <p>
          <strong>The Case of the Undetectable Side Effect</strong>
        </p>
        <p>
Every so often you encounter code that just makes you mumble WTF way more than is
healthy for any sane developer. In most cases things just happen everywhere. When
the code is performing a query, it's also updating some other pieces, altering the
file system a bit and lastly setting a whole bunch of other objects in an invalid
state.
</p>
        <p>
I wouldn't recommend getting the debugger up and running to see what's going on. Most
of the time it consumes a lot of time and keeps the frustration really high.
</p>
        <p>
What this kind of code is lacking is proper Command Query Separation (CQS). From the
WEWLC book "It's a is a design principle first described by Bertrand Meyer. Simply
put, it is this: A method should be a command or a query, but not both. A command
is a method that can modify the state of the object but that doesn't return a value.
A query is a method that returns a value but that does not modify the object."
</p>
        <p>
 
</p>
        <p>
You should always strive to adhere to this principle. It will make your code easier
to read and more importantly, easier to skip when reading. When I encounter code that
does not adhere to CQS I always split it up in several smaller methods, break out
objects etc etc. Once that is done, testing immediately becomes easier on the class.
</p>
        <p>
It's a matter of subclassing and overriding any behavior that is unwanted so that
the method you like to test can be tested in isolation. 
</p>
        <p>
 
</p>
        <p>
And with the Undetectable side effect covered we end the I can't get this class into
a test harness chapter of WEWLC. Hope you enjoyed reading. Drop a line in the comments
for feedback, or ideas.
</p>
        <img width="0" height="0" src="http://www.tjsolutions.nl/aggbug.ashx?id=d5fbb2c1-e30f-42b1-9abb-3706503c33e2" />
      </body>
      <title>WEWLC - I Can't Run This Method in a Test Harness</title>
      <guid isPermaLink="false">http://www.tjsolutions.nl/PermaLink,guid,d5fbb2c1-e30f-42b1-9abb-3706503c33e2.aspx</guid>
      <link>http://www.tjsolutions.nl/2009/09/15/WEWLCICantRunThisMethodInATestHarness.aspx</link>
      <pubDate>Tue, 15 Sep 2009 20:31:59 GMT</pubDate>
      <description>&lt;p&gt;
This is the third posting in the &lt;a href="http://www.tjsolutions.nl/2009/06/01/AnnouncingTheSeriesWorkingWithLegacyCode.aspx" target="_blank"&gt;WEWLC-series&lt;/a&gt;. 
&lt;/p&gt;
&lt;p&gt;
&amp;#160;
&lt;/p&gt;
&lt;p&gt;
Other posts are:
&lt;/p&gt;
&lt;p&gt;
&lt;a href="http://www.tjsolutions.nl/2009/09/14/WEWLCICantGetThisClassIntoATestHarness.aspx" target="_blank"&gt;I
Can't Get This Class into a Test Harness&lt;/a&gt;
&lt;/p&gt;
&lt;p&gt;
&lt;a href="http://www.tjsolutions.nl/2009/09/12/WEWLCIDontHaveMuchTimeAndIHaveToChangeIt.aspx" target="_blank"&gt;I
don't have much time and I have to change it&lt;/a&gt;
&lt;/p&gt;
&lt;p&gt;
&lt;a href="http://www.tjsolutions.nl/2009/09/12/WEWLCAssumptions.aspx" target="_blank"&gt;Assumptions
on the reader&lt;/a&gt;
&lt;/p&gt;
&lt;p&gt;
&amp;#160;
&lt;/p&gt;
&lt;p&gt;
"Getting tests in place to make changes can be a bit of a problem. If you can instantiate
your class separately in a test harness, consider yourself lucky." 
&lt;/p&gt;
&lt;p&gt;
Instantiating a class should not be hard, if you do have issues have a look at &lt;a href="http://www.tjsolutions.nl/2009/09/14/WEWLCICantGetThisClassIntoATestHarness.aspx" target="_blank"&gt;I
Can't Get This Class into a Test Harness&lt;/a&gt;. That should take care of most of your
problems. 
&lt;/p&gt;
&lt;p&gt;
But instantiating is often just the first part of all the hurdles to take. The second
part is writing a test for the methods inside. 
&lt;/p&gt;
&lt;p&gt;
&amp;#160;
&lt;/p&gt;
&lt;p&gt;
Fortunately, in most cases, the amount of work that we have to do to write tests for
methods isn't as drastic. Here are some of the problems that we can run into.&lt;a name="ch10index03"&gt;&lt;/a&gt;&lt;a name="ch10index04"&gt;&lt;/a&gt;&lt;a name="ch10index05"&gt;&lt;/a&gt;
&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;
The method may be private
&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;
The method may be hard to call because it has parameters that are hard to construct
&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;
The method might have bad side effects (modifying a database, writing to the file
system etc)
&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;
&lt;strong&gt;&lt;/strong&gt;
&lt;/p&gt;
&lt;p&gt;
&lt;strong&gt;The Case of the Hidden Method&lt;/strong&gt;
&lt;/p&gt;
&lt;p&gt;
If we need to write a test for a private method we need to make it public. There are
some tricks in getting visibility on the method in your tests but I don't recommend
it. First of all, if there is a need for private method odds are that what you need
is a another collaborator. 
&lt;/p&gt;
&lt;p&gt;
This is of course a rather fundamental discussion. If you do care about keeping the
method invisible to callers you can make it protected. Once it is protected you can
derive a test class and add a public method that will simply call the protected method
in the base class.
&lt;/p&gt;
&lt;p&gt;
In most cases I would recommend moving the method to a separate class and inject it
into the constructor of the class that interacts with it. Once there is a need to
alter the behavior of a private method it is obviously doing something important,
hence, it should be under test.
&lt;/p&gt;
&lt;p&gt;
&amp;#160;
&lt;/p&gt;
&lt;p&gt;
&lt;strong&gt;The Case of the &amp;quot;Helpful&amp;quot; Language Feature &lt;/strong&gt;
&lt;/p&gt;
&lt;p&gt;
Michael Feather is referring to sealed classes that don't have constructor. How do
you test interaction code that takes such a class as a parameter in a method? Let's
have a look at an example:
&lt;/p&gt;
&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;StreamHelper &lt;/span&gt;{ &lt;span style="color: blue"&gt;const
int &lt;/span&gt;MIN_LEN = 4; &lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IList &lt;/span&gt;GetStreams(&lt;span style="color: #2b91af"&gt;HttpFileCollection &lt;/span&gt;files)
{ &lt;span style="color: blue"&gt;var &lt;/span&gt;list = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Stream&lt;/span&gt;&amp;gt;(); &lt;span style="color: blue"&gt;foreach &lt;/span&gt;(&lt;span style="color: blue"&gt;string &lt;/span&gt;name &lt;span style="color: blue"&gt;in &lt;/span&gt;files)
{ &lt;span style="color: #2b91af"&gt;HttpPostedFile &lt;/span&gt;file = files[name]; &lt;span style="color: blue"&gt;if &lt;/span&gt;((file.FileName.EndsWith(&lt;span style="color: #a31515"&gt;&amp;quot;.txt&amp;quot;&lt;/span&gt;)
&amp;amp;&amp;amp; file.ContentLength &amp;gt; MIN_LEN)) { list.Add(file.InputStream); } } &lt;span style="color: blue"&gt;return &lt;/span&gt;list;
} }&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt; 
&lt;p&gt;
According to &lt;a href="http://msdn.microsoft.com/en-us/library/system.web.httpfilecollection.aspx" target="_blank"&gt;MSDN&lt;/a&gt;,
the HttpFileCollection provides access to and organizes files uploaded by a client.
Since this class is sealed and only has an internal constructor, how can you test
this method?
&lt;/p&gt;
&lt;p&gt;
Turns out that HttpFileCollection derives from NameObjectCollectionBase which has
a parameterless constructor which is protected. If we thus derive from NameObjectCollectionBase,
implement the indexer required and change the signature of the GetStreams method a
bit to take our custom class instead of the HttpFileCollection we should be able to
get going. 
&lt;/p&gt;
&lt;p&gt;
&amp;#160;
&lt;/p&gt;
&lt;p&gt;
Please note, this is going to be a hefty refactoring. Right, lets get down to it.
First let's create a fixture for our tests:
&lt;/p&gt;
&lt;pre class="code"&gt;[&lt;span style="color: #2b91af"&gt;TestFixture&lt;/span&gt;] &lt;span style="color: blue"&gt;public
class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;HttpCollectionTests &lt;/span&gt;{ [&lt;span style="color: #2b91af"&gt;Test&lt;/span&gt;] &lt;span style="color: blue"&gt;public
void &lt;/span&gt;can_instantiate_a_derived_class_from_NameObjectCollectionBase() { &lt;span style="color: blue"&gt;var &lt;/span&gt;customHttpFileCollection
= &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;CustomHttpFileCollection&lt;/span&gt;(); &lt;span style="color: blue"&gt;var &lt;/span&gt;collectionBase
= customHttpFileCollection &lt;span style="color: blue"&gt;as &lt;/span&gt;&lt;span style="color: #2b91af"&gt;NameObjectCollectionBase&lt;/span&gt;;
collectionBase.ShouldNotBeNull(); } }&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt; 
&lt;p&gt;
&amp;#160;
&lt;/p&gt;
&lt;p&gt;
This means deriving from NameObjectCollectionBase
&lt;/p&gt;
&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;CustomHttpFileCollection &lt;/span&gt;: &lt;span style="color: #2b91af"&gt;NameObjectCollectionBase &lt;/span&gt;{
}&lt;/pre&gt;
&lt;p&gt;
The next test is to be able to call GetStreams() in StreamHelper. Rather than changing
the existing method we are going to create a new method with the same name, but different
signature so that we can call it with our new CustomerHttpFileCollection:
&lt;/p&gt;
&lt;pre class="code"&gt;[&lt;span style="color: #2b91af"&gt;Test&lt;/span&gt;] &lt;span style="color: blue"&gt;public
void &lt;/span&gt;can_use_the_custom_class() { &lt;span style="color: blue"&gt;var &lt;/span&gt;collection
= &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;CustomHttpFileCollection&lt;/span&gt;(); &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;StreamHelper&lt;/span&gt;().GetStreams(collection);
}&lt;/pre&gt;
&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IList&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Stream&lt;/span&gt;&amp;gt;
GetStreams(&lt;span style="color: #2b91af"&gt;CustomHttpFileCollection &lt;/span&gt;files) { &lt;span style="color: blue"&gt;var &lt;/span&gt;list
= &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Stream&lt;/span&gt;&amp;gt;(); &lt;span style="color: blue"&gt;foreach &lt;/span&gt;(&lt;span style="color: blue"&gt;string &lt;/span&gt;name &lt;span style="color: blue"&gt;in &lt;/span&gt;files)
{ &lt;span style="color: #2b91af"&gt;HttpPostedFile &lt;/span&gt;file = files[name]; &lt;span style="color: blue"&gt;if &lt;/span&gt;((file.FileName.EndsWith(&lt;span style="color: #a31515"&gt;&amp;quot;.txt&amp;quot;&lt;/span&gt;)
&amp;amp;&amp;amp; file.ContentLength &amp;gt; MIN_LEN)) { list.Add(file.InputStream); } } &lt;span style="color: blue"&gt;return &lt;/span&gt;list;
}&lt;/pre&gt;
&lt;p&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;This means implementing the indexer
used in GetStreams() in our custom class. Luckily Resharper knows what to do and we
can use ALT-ENTER to generate the code. Next to the indexer we will also need an IList
to store the files and a method to add them to the internal collection:
&lt;/p&gt;
&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;CustomHttpFileCollection &lt;/span&gt;: &lt;span style="color: #2b91af"&gt;NameObjectCollectionBase &lt;/span&gt;{ &lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;HttpPostedFile &lt;/span&gt;&lt;span style="color: blue"&gt;this&lt;/span&gt;[&lt;span style="color: blue"&gt;string &lt;/span&gt;name]
{ &lt;span style="color: blue"&gt;get &lt;/span&gt;{ &lt;span style="color: blue"&gt;return &lt;/span&gt;httpPostedFiles.Where(s
=&amp;gt; s.FileName == name).FirstOrDefault(); } } }&lt;/pre&gt;
&lt;p&gt;
This poses a bit of an issue; we can instantiate a HttpPostedFile so how are we going
to populate an internal collection? Since this one is sealed, does not have a suitable
base class and has no constructors we need to be creative. We need a custom implementation
of the HttpPostedFile. First we create an interface, then define the same members
on the interface as are in the HttpPostedFile class. Once that is done we can change
the signature of the indexer to IHttpPostedFile and add some logic to store and add
the files to the collection class, like so:
&lt;/p&gt;
&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;CustomHttpFileCollection &lt;/span&gt;: &lt;span style="color: #2b91af"&gt;NameObjectCollectionBase &lt;/span&gt;{ &lt;span style="color: blue"&gt;readonly &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IList&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;IHttpPostedFile&lt;/span&gt;&amp;gt;
httpPostedFiles = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;IHttpPostedFile&lt;/span&gt;&amp;gt;(); &lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IHttpPostedFile &lt;/span&gt;&lt;span style="color: blue"&gt;this&lt;/span&gt;[&lt;span style="color: blue"&gt;string &lt;/span&gt;name]
{ &lt;span style="color: blue"&gt;get &lt;/span&gt;{ &lt;span style="color: blue"&gt;return &lt;/span&gt;httpPostedFiles.Where(s
=&amp;gt; s.FileName == name).FirstOrDefault(); } } &lt;span style="color: blue"&gt;public void &lt;/span&gt;AddHttpPostedFile(&lt;span style="color: #2b91af"&gt;IHttpPostedFile &lt;/span&gt;file)
{ httpPostedFiles.Add(file); } }&lt;/pre&gt;
&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public interface &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IHttpPostedFile &lt;/span&gt;{ &lt;span style="color: blue"&gt;int &lt;/span&gt;ContentLength
{ &lt;span style="color: blue"&gt;get&lt;/span&gt;; } &lt;span style="color: blue"&gt;string &lt;/span&gt;ContentType
{ &lt;span style="color: blue"&gt;get&lt;/span&gt;; } &lt;span style="color: blue"&gt;string &lt;/span&gt;FileName
{ &lt;span style="color: blue"&gt;get&lt;/span&gt;; } &lt;span style="color: #2b91af"&gt;Stream &lt;/span&gt;InputStream
{ &lt;span style="color: blue"&gt;get&lt;/span&gt;; } }&lt;/pre&gt;
&lt;p&gt;
Change the HttpPostedFile to the new IHttpPostedFile in GetStreams():
&lt;/p&gt;
&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IList&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Stream&lt;/span&gt;&amp;gt;
GetStreams(&lt;span style="color: #2b91af"&gt;CustomHttpFileCollection &lt;/span&gt;files) { &lt;span style="color: blue"&gt;var &lt;/span&gt;list
= &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Stream&lt;/span&gt;&amp;gt;(); &lt;span style="color: blue"&gt;foreach &lt;/span&gt;(&lt;span style="color: blue"&gt;string &lt;/span&gt;name &lt;span style="color: blue"&gt;in &lt;/span&gt;files)
{ &lt;span style="color: #2b91af"&gt;IHttpPostedFile &lt;/span&gt;file = files[name]; &lt;span style="color: blue"&gt;if &lt;/span&gt;((file.FileName.EndsWith(&lt;span style="color: #a31515"&gt;&amp;quot;.txt&amp;quot;&lt;/span&gt;)
&amp;amp;&amp;amp; file.ContentLength &amp;gt; MIN_LEN)) { list.Add(file.InputStream); } } &lt;span style="color: blue"&gt;return &lt;/span&gt;list;
}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt; &lt;pre class="code"&gt;&amp;#160;&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt; 
&lt;p&gt;
Now that we have set up the collection, let's write a test to see if it all works
&lt;/p&gt;
&lt;pre class="code"&gt;&lt;span style="color: #2b91af"&gt;Stream &lt;/span&gt;GetStream() { &lt;span style="color: blue"&gt;const
string &lt;/span&gt;s = &lt;span style="color: #a31515"&gt;&amp;quot;hello world&amp;quot;&lt;/span&gt;; &lt;span style="color: blue"&gt;var &lt;/span&gt;memoryStream
= &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;MemoryStream&lt;/span&gt;(System.Text.&lt;span style="color: #2b91af"&gt;Encoding&lt;/span&gt;.Default.GetBytes(s)); &lt;span style="color: blue"&gt;return &lt;/span&gt;memoryStream;
}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt; &lt;pre class="code"&gt;[&lt;span style="color: #2b91af"&gt;Test&lt;/span&gt;] &lt;span style="color: blue"&gt;public
void &lt;/span&gt;can_use_the_customcollection_to_test_the_StreamHelper_class() { &lt;span style="color: blue"&gt;var &lt;/span&gt;collection
= &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;CustomHttpFileCollection&lt;/span&gt;(); &lt;span style="color: blue"&gt;var &lt;/span&gt;httpPostedFile
= &lt;span style="color: #2b91af"&gt;MockRepository&lt;/span&gt;.GenerateMock&amp;lt;&lt;span style="color: #2b91af"&gt;IHttpPostedFile&lt;/span&gt;&amp;gt;();
httpPostedFile.Stub(s =&amp;gt; s.InputStream).Return(GetStream()); httpPostedFile.Stub(s
=&amp;gt; s.FileName).Return(&lt;span style="color: #a31515"&gt;&amp;quot;somefilename.txt&amp;quot;&lt;/span&gt;);
httpPostedFile.Stub(s =&amp;gt; s.ContentLength).Return(5); collection.AddHttpPostedFile(httpPostedFile); &lt;span style="color: #2b91af"&gt;IList&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Stream&lt;/span&gt;&amp;gt;
streams = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;StreamHelper&lt;/span&gt;().GetStreams(collection);
streams.Count.ShouldEqual(1); }&lt;/pre&gt;
&lt;p&gt;
When we execute this test a lot is happening. First I create a mock of the IHttpPostedFile
interface so that I can stub the properties. This allows me to test the method without
having an actual implementation of the interface. Not that it would have complicated
things tremendously, but it's a nice technique.
&lt;/p&gt;
&lt;p&gt;
I also use a convenient helper method to get me a stream. This will come in handy
later when I want to verify the outcome of the GetStreams() method.
&lt;/p&gt;
&lt;p&gt;
Let's execute and:
&lt;/p&gt;
&lt;p&gt;
&amp;#160;
&lt;/p&gt;
&lt;p&gt;
------ Test started: Assembly: Koning.WEWLC.Tests.dll ------ 
&lt;/p&gt;
&lt;p&gt;
TestCase 'Koning.WEWLC.Tests.HttpCollectionTests.can_use_the_customcollection_to_test_the_StreamHelper_class' 
&lt;br /&gt;
failed: 
&lt;br /&gt;
&amp;#160; Expected: 1 
&lt;br /&gt;
&amp;#160; But was:&amp;#160; 0 
&lt;br /&gt;
&amp;#160;&amp;#160;&amp;#160; at Machine.Specifications.NUnitShouldExtensionMethods.ShouldEqual(Object
actual, Object expected) 
&lt;br /&gt;
&amp;#160;&amp;#160;&amp;#160; C:\Dev\Personal\WEWLC\Koning.WEWLC\Koning.WEWLC.Tests\Tests\HttpCollectionTests.cs(59,0):
at Koning.WEWLC.Tests.HttpCollectionTests.can_use_the_customcollection_to_test_the_StreamHelper_class() 
&lt;/p&gt;
&lt;p&gt;
0 passed, 1 failed, 0 skipped, took 1.37 seconds. 
&lt;/p&gt;
&lt;p&gt;
&amp;#160;
&lt;/p&gt;
&lt;p&gt;
Why is this happening? My bad, I didn't implement GetEnumerator() on the custom collection
class. This is easily fixed however:
&lt;/p&gt;
&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;CustomHttpFileCollection &lt;/span&gt;: &lt;span style="color: #2b91af"&gt;NameObjectCollectionBase&lt;/span&gt;, &lt;span style="color: #2b91af"&gt;IEnumerable &lt;/span&gt;{ &lt;span style="color: blue"&gt;readonly &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IList&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;IHttpPostedFile&lt;/span&gt;&amp;gt;
httpPostedFiles = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;IHttpPostedFile&lt;/span&gt;&amp;gt;(); &lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IHttpPostedFile &lt;/span&gt;&lt;span style="color: blue"&gt;this&lt;/span&gt;[&lt;span style="color: blue"&gt;string &lt;/span&gt;name]
{ &lt;span style="color: blue"&gt;get &lt;/span&gt;{ &lt;span style="color: blue"&gt;return &lt;/span&gt;httpPostedFiles.Where(s
=&amp;gt; s.FileName == name).FirstOrDefault(); } } &lt;span style="color: blue"&gt;public new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IEnumerator&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;string&lt;/span&gt;&amp;gt;
GetEnumerator() { &lt;span style="color: blue"&gt;return &lt;/span&gt;httpPostedFiles.Select(s
=&amp;gt; s.FileName).GetEnumerator(); } &lt;span style="color: #2b91af"&gt;IEnumerator IEnumerable&lt;/span&gt;.GetEnumerator()
{ &lt;span style="color: blue"&gt;return &lt;/span&gt;GetEnumerator(); } &lt;span style="color: blue"&gt;public
void &lt;/span&gt;AddHttpPostedFile(&lt;span style="color: #2b91af"&gt;IHttpPostedFile &lt;/span&gt;file)
{ httpPostedFiles.Add(file); } }&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt; 
&lt;p&gt;
I'm using some Linq goodness to get to the filenames and iterate over that. Next up
is refining our test and run it again:
&lt;/p&gt;
&lt;pre class="code"&gt;[&lt;span style="color: #2b91af"&gt;Test&lt;/span&gt;] &lt;span style="color: blue"&gt;public
void &lt;/span&gt;can_use_the_customcollection_to_test_the_StreamHelper_class() { &lt;span style="color: blue"&gt;var &lt;/span&gt;collection
= &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;CustomHttpFileCollection&lt;/span&gt;(); &lt;span style="color: blue"&gt;var &lt;/span&gt;httpPostedFile
= &lt;span style="color: #2b91af"&gt;MockRepository&lt;/span&gt;.GenerateMock&amp;lt;&lt;span style="color: #2b91af"&gt;IHttpPostedFile&lt;/span&gt;&amp;gt;();
httpPostedFile.Stub(s =&amp;gt; s.InputStream).Return(GetStream()); httpPostedFile.Stub(s
=&amp;gt; s.FileName).Return(&lt;span style="color: #a31515"&gt;&amp;quot;somefilename.txt&amp;quot;&lt;/span&gt;);
httpPostedFile.Stub(s =&amp;gt; s.ContentLength).Return(5); collection.AddHttpPostedFile(httpPostedFile); &lt;span style="color: #2b91af"&gt;IList&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Stream&lt;/span&gt;&amp;gt;
streams = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;StreamHelper&lt;/span&gt;().GetStreams(collection);
streams.Count.ShouldEqual(1); streams.First().Length.ShouldBeGreaterThan(0); &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;StreamReader&lt;/span&gt;(streams.First()).ReadLine().ShouldContain(&lt;span style="color: #a31515"&gt;&amp;quot;hello
world&amp;quot;&lt;/span&gt;); }&lt;/pre&gt;
&lt;p&gt;
------ Test started: Assembly: Koning.WEWLC.Tests.dll ------ 
&lt;/p&gt;
&lt;p&gt;
1 passed, 0 failed, 0 skipped, took 1.48 seconds. 
&lt;/p&gt;
&lt;p&gt;
&amp;#160;
&lt;/p&gt;
&lt;p&gt;
Now note that when using the GetStreams() method one would have to transform the items
in HttpPostedFileCollection to the IHttpPostedFile interface before using it. 
&lt;/p&gt;
&lt;p&gt;
&amp;#160;
&lt;/p&gt;
&lt;p&gt;
&amp;#160;
&lt;/p&gt;
&lt;p&gt;
&lt;strong&gt;The Case of the Undetectable Side Effect&lt;/strong&gt;
&lt;/p&gt;
&lt;p&gt;
Every so often you encounter code that just makes you mumble WTF way more than is
healthy for any sane developer. In most cases things just happen everywhere. When
the code is performing a query, it's also updating some other pieces, altering the
file system a bit and lastly setting a whole bunch of other objects in an invalid
state.
&lt;/p&gt;
&lt;p&gt;
I wouldn't recommend getting the debugger up and running to see what's going on. Most
of the time it consumes a lot of time and keeps the frustration really high.
&lt;/p&gt;
&lt;p&gt;
What this kind of code is lacking is proper Command Query Separation (CQS). From the
WEWLC book "It's a is a design principle first described by Bertrand Meyer. Simply
put, it is this: A method should be a command or a query, but not both. A command
is a method that can modify the state of the object but that doesn't return a value.
A query is a method that returns a value but that does not modify the object."
&lt;/p&gt;
&lt;p&gt;
&amp;#160;
&lt;/p&gt;
&lt;p&gt;
You should always strive to adhere to this principle. It will make your code easier
to read and more importantly, easier to skip when reading. When I encounter code that
does not adhere to CQS I always split it up in several smaller methods, break out
objects etc etc. Once that is done, testing immediately becomes easier on the class.
&lt;/p&gt;
&lt;p&gt;
It's a matter of subclassing and overriding any behavior that is unwanted so that
the method you like to test can be tested in isolation. 
&lt;/p&gt;
&lt;p&gt;
&amp;#160;
&lt;/p&gt;
&lt;p&gt;
And with the Undetectable side effect covered we end the I can't get this class into
a test harness chapter of WEWLC. Hope you enjoyed reading. Drop a line in the comments
for feedback, or ideas.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.tjsolutions.nl/aggbug.ashx?id=d5fbb2c1-e30f-42b1-9abb-3706503c33e2" /&gt;</description>
      <comments>http://www.tjsolutions.nl/CommentView,guid,d5fbb2c1-e30f-42b1-9abb-3706503c33e2.aspx</comments>
      <category>WEWLC</category>
    </item>
    <item>
      <trackback:ping>http://www.tjsolutions.nl/Trackback.aspx?guid=06cd78d0-e6f5-4cf7-8ebe-abb2e9f22e02</trackback:ping>
      <pingback:server>http://www.tjsolutions.nl/pingback.aspx</pingback:server>
      <pingback:target>http://www.tjsolutions.nl/PermaLink,guid,06cd78d0-e6f5-4cf7-8ebe-abb2e9f22e02.aspx</pingback:target>
      <dc:creator>Tom</dc:creator>
      <wfw:comment>http://www.tjsolutions.nl/CommentView,guid,06cd78d0-e6f5-4cf7-8ebe-abb2e9f22e02.aspx</wfw:comment>
      <wfw:commentRss>http://www.tjsolutions.nl/SyndicationService.asmx/GetEntryCommentsRss?guid=06cd78d0-e6f5-4cf7-8ebe-abb2e9f22e02</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
This is the second posting in the <a href="http://www.tjsolutions.nl/2009/06/01/AnnouncingTheSeriesWorkingWithLegacyCode.aspx" target="_blank">WEWLC-series</a>. 
</p>
        <p>
 
</p>
        <p>
Other posts are:
</p>
        <p>
          <a href="http://www.tjsolutions.nl/2009/09/15/WEWLCICantRunThisMethodInATestHarness.aspx" target="_blank">I
can't run this method in a test harness</a>
        </p>
        <p>
          <a href="http://www.tjsolutions.nl/2009/09/12/WEWLCIDontHaveMuchTimeAndIHaveToChangeIt.aspx" target="_blank">I
don't have much time and I have to change it</a>
        </p>
        <p>
          <a href="http://www.tjsolutions.nl/2009/09/12/WEWLCAssumptions.aspx" target="_blank">Assumptions
on the reader</a>
        </p>
        <p>
 
</p>
        <p>
 
</p>
        <p>
What to do if the system under test is a nasty legacy class that seems impossible
to get under test? There are various techniques that can help you with this, let get
started with "the case of the irritating parameter".
</p>
        <p>
 
</p>
        <p>
          <strong>
          </strong>
        </p>
        <p>
          <strong>
          </strong>
        </p>
        <p>
          <strong>The case of the irritating parameter</strong>
        </p>
        <p>
When you have a SUT that takes complex objects into it's constructor you can easily
circumvent the situation by applying <a href="http://www.refactoring.com/catalog/extractInterface.html" target="_blank">Extract
interface</a> on the bothering classes. 
</p>
        <p>
After you have created the necessary interfaces you can utilize <a href="http://ayende.com/wiki/Rhino+Mocks+Documentation.ashx" target="_blank">Rhino
Mocks</a> to generate replacement instances (mocks) of the required classes. Rhino
Mocks will actually create an proxy instance for the class. Conveniently, you can
then set expectations &amp; outcomes on these mocks. So without an actual implementation
you fake the system into believing it is dealing with actual classes. 
</p>
        <p>
Let have a look on how this works:
</p>
        <p>
 
</p>
        <pre class="code">
          <span style="color: blue">public class </span>
          <span style="color: #2b91af">CreditValidator </span>{ <span style="color: blue">readonly </span><span style="color: #2b91af">IDbConnection </span>connection; <span style="color: blue">readonly </span><span style="color: #2b91af">ICreditMaster </span>creditMaster; <span style="color: blue">public </span>CreditValidator(<span style="color: #2b91af">IDbConnection </span>connection, <span style="color: #2b91af">ICreditMaster </span>creditMaster)
{ <span style="color: blue">this</span>.connection = connection; <span style="color: blue">this</span>.creditMaster
= creditMaster; } } <span style="color: blue">public class </span><span style="color: #2b91af">CreditMaster</span>: <span style="color: #2b91af">ICreditMaster </span>{ <span style="color: blue">public </span><span style="color: #2b91af">CreditInformation </span>GetCreditInformation(<span style="color: #2b91af">Customer </span>customer)
{ <span style="color: blue">throw new </span><span style="color: #2b91af">NotImplementedException</span>();
} } <span style="color: blue">public interface </span><span style="color: #2b91af">ICreditMaster </span>{ <span style="color: #2b91af">CreditInformation </span>GetCreditInformation(<span style="color: #2b91af">Customer </span>customer);
}</pre>
        <p>
          <a href="http://11011.net/software/vspaste">
          </a>
        </p>
        <p>
First off we create an interface for the CreditMaster class. Once that is done we
can start writing the test ask the Rhino MockRepository for an instance of both IDbConnection
and ICreditMaster.
</p>
        <p>
 
</p>
        <pre class="code">[<span style="color: #2b91af">TestFixture</span>] <span style="color: blue">public
class </span><span style="color: #2b91af">CreditValidatorTests </span>{ [<span style="color: #2b91af">Test</span>] <span style="color: blue">public
void </span>can_construct_an_instance_of_the_SUT() { <span style="color: blue">var </span>connection
= <span style="color: #2b91af">MockRepository</span>.GenerateMock&lt;<span style="color: #2b91af">IDbConnection</span>&gt;(); <span style="color: blue">var </span>creditMaster
= <span style="color: #2b91af">MockRepository</span>.GenerateMock&lt;<span style="color: #2b91af">ICreditMaster</span>&gt;(); <span style="color: blue">var </span>creditValidator
= <span style="color: blue">new </span><span style="color: #2b91af">CreditValidator</span>(connection,
creditMaster); creditValidator.ShouldNotBeNull(); } }</pre>
        <a href="http://11011.net/software/vspaste">
        </a>
        <p>
 
</p>
        <p>
This test should not throw an exception, I assert on null just to write a clear test.
Run it, and surely enough the test passes.
</p>
        <p>
------ Test started: Assembly: Koning.WEWLC.Tests.dll ------ 
</p>
        <p>
1 passed, 0 failed, 0 skipped, took 1.35 seconds.
</p>
        <p>
 
</p>
        <p>
 
</p>
        <p>
          <strong>The Case of the Hidden Dependency</strong>
        </p>
        <p>
Once you get the class instantiated, we try to use it and bang! Some obscure other
complex class is instantiated deep inside and causes the crash. Enter the "case of
the hidden dependency". You need to remove newing the class and either move it to
a public property or to the constructor. You can then either mock the constructor
parameter or set it when you need through the property.
</p>
        <p>
Once you start moving dependencies to the constructor of your classes it quickly starts
to make sense to use a Dependency Injection Container. The one I use most frequently
is Unity as it's included in EntLib and has several advantages over the other DI-containers
available. For one that it's usage it's fairly simple, but even more so that is has
Microsoft's backing, often a requirement at the projects I work.
</p>
        <p>
 
</p>
        <p>
Let's have a look at how such a configuration would look like for a hypothetical complex
class Repository. First create an interface for the Repository and register it in
the BootStrapper. Registration in the Unity container:
</p>
        <pre class="code">
          <span style="color: blue">public static class </span>
          <span style="color: #2b91af">BootStrapper </span>{ <span style="color: blue">public
static </span><span style="color: #2b91af">IUnityContainer </span>GetContainer() { <span style="color: blue">var </span>container
= <span style="color: blue">new </span><span style="color: #2b91af">UnityContainer</span>();
container.RegisterType&lt;<span style="color: #2b91af">IRepository</span>, <span style="color: #2b91af">Repository</span>&gt;(); <span style="color: blue">return </span>container;
} } <span style="color: blue">public class </span><span style="color: #2b91af">Repository</span>:<span style="color: #2b91af">IRepository </span>{
} <span style="color: blue">public interface </span><span style="color: #2b91af">IRepository </span>{
}</pre>
        <a href="http://11011.net/software/vspaste">
        </a>
        <p>
I prefer to use a static container to resolve dependencies in my applications, like
so
</p>
        <pre class="code">
          <span style="color: blue">public static class </span>
          <span style="color: #2b91af">StaticContainer </span>{ <span style="color: blue">public
static </span>T Resolve&lt;T&gt;() { <span style="color: blue">return </span><span style="color: #2b91af">BootStrapper</span>.GetContainer().Resolve&lt;T&gt;();
} }</pre>
        <a href="http://11011.net/software/vspaste">
        </a>
        <p>
Once the dependency is registered it is simply a matter of retrieving the SUT by requesting
the container to construct it. In your tests you can then choose to have the container
construct the dependencies or have Rhino Mocks generate the mocks after which you
can set expectations on them. 
</p>
        <p>
 
</p>
        <p>
          <strong>The Case of the Construction Blob</strong>
        </p>
        <p>
If a constructor constructs a large number of objects internally or accesses a large
number of globals, we could end up with a very large parameter list. One simple rule
is to avoid the construction altogether and move the result of the creation logic
into a dependency property. You could then have your DI container inject it at will
or inject a mock when used in a test harness.
</p>
        <p>
 
</p>
        <p>
 
</p>
        <p>
          <strong>The case of the Irritating Global Dependency</strong>
        </p>
        <p>
In WEWLC, Michael Feathers writes: "Many different kinds of dependency can make it
hard to create and use classes in a testing framework, but one of the hardest to deal
with is global variable usage."
</p>
        <p>
He's describing the hideous Singleton use in legacy code. Personally I haven't run
into problems with a Singleton. Partly, because I didn't write tests at the time I
was using them and on the other hand because nowadays I simply ask my DI container
for a Singleton when I need it.
</p>
        <p>
Still, Singletons can be a pain in the ass and you should try to avoid them. The whole
idea of the singleton pattern is to make it impossible to create more than one instance
of a singleton in an application. Because it is, it is particularly hard to fake.
What do you do when you encounter one?
</p>
        <p>
Basically you have three options, one is to replace all occurrences in the code; this
can be a very tedious job, but with the aid of Resharper, one that I would recommend.
</p>
        <p>
The other is to add a static method to the Singleton that will allow you to pass in
a fake. First the lazy Singleton implementation (I have omitted any useful methods
for  brevity):
</p>
        <pre class="code">
          <span style="color: blue">public class </span>
          <span style="color: #2b91af">PermitRepository </span>{ <span style="color: blue">protected </span>PermitRepository()
{ } <span style="color: blue">public static </span><span style="color: #2b91af">PermitRepository </span>GetInstance()
{ <span style="color: blue">return </span><span style="color: #2b91af">Nested</span>.Instance;
} <span style="color: blue">public static void </span>SetInstance(<span style="color: #2b91af">PermitRepository </span>repository)
{ <span style="color: #2b91af">Nested</span>.Instance = repository; } <span style="color: blue">class </span><span style="color: #2b91af">Nested </span>{ <span style="color: green">//
Explicit static constructor to tell C# compiler // not to mark type as beforefieldinit </span><span style="color: blue">static </span>Nested()
{ } <span style="color: blue">public static </span><span style="color: #2b91af">PermitRepository </span>Instance
{ <span style="color: blue">get </span>{ <span style="color: blue">return </span>instance;
} <span style="color: blue">set </span>{ instance = <span style="color: blue">value</span>;
} } <span style="color: blue">static </span><span style="color: #2b91af">PermitRepository </span>instance
= <span style="color: blue">new </span><span style="color: #2b91af">PermitRepository</span>();
} }</pre>
        <a href="http://11011.net/software/vspaste">
        </a>
        <p>
 
</p>
        <p>
 
</p>
        <p>
And to prove that getting multiple calls of the GetInstance() method will return the
same object whilst using the SetInstance method will change the instance field the
following test:
</p>
        <pre class="code">
          <span style="color: blue">public class </span>
          <span style="color: #2b91af">FakePermitRepository </span>: <span style="color: #2b91af">PermitRepository </span>{
}</pre>
        <a href="http://11011.net/software/vspaste">
        </a>
        <pre class="code">[<span style="color: #2b91af">TestFixture</span>] <span style="color: blue">public
class </span><span style="color: #2b91af">PermitRepositoryTests </span>{ [<span style="color: #2b91af">Test</span>] <span style="color: blue">public
void </span>can_replace_the_PermitRepositoryInstance() { <span style="color: blue">var </span>repository
= <span style="color: #2b91af">PermitRepository</span>.GetInstance(); <span style="color: blue">int </span>hashCode
= repository.GetHashCode(); hashCode.ShouldEqual(<span style="color: #2b91af">PermitRepository</span>.GetInstance().GetHashCode()); <span style="color: #2b91af">PermitRepository</span>.SetInstance(<span style="color: blue">new </span><span style="color: #2b91af">FakePermitRepository</span>()); <span style="color: #2b91af">PermitRepository</span>.GetInstance().GetHashCode().ShouldNotEqual(hashCode);
} }</pre>
        <p>
------ Test started: Assembly: Koning.WEWLC.Tests.dll ------ 
</p>
        <p>
1 passed, 0 failed, 0 skipped, took 1.35 seconds.
</p>
        <p>
 
</p>
        <p>
The third option is to reset the private instance field of the Singleton and set it
to null. First we alter the nested class a bit so that it checks for IsNull() before
returning the object:
</p>
        <pre class="code">
          <span style="color: blue">public class </span>
          <span style="color: #2b91af">PermitRepository </span>{ <span style="color: blue">protected </span>PermitRepository()
{ } <span style="color: blue">public static </span><span style="color: #2b91af">PermitRepository </span>GetInstance()
{ <span style="color: blue">return </span><span style="color: #2b91af">Nested</span>.Instance;
} <span style="color: blue">public static void </span>SetInstance(<span style="color: #2b91af">PermitRepository </span>repository)
{ <span style="color: #2b91af">Nested</span>.Instance = repository; } <span style="color: blue">public
static void </span>Reset() { <span style="color: #2b91af">Nested</span>.Instance = <span style="color: blue">null</span>;
} <span style="color: blue">public class </span><span style="color: #2b91af">Nested </span>{ <span style="color: green">//
Explicit static constructor to tell C# compiler // not to mark type as beforefieldinit </span><span style="color: blue">static </span>Nested()
{ } <span style="color: blue">public static </span><span style="color: #2b91af">PermitRepository </span>Instance
{ <span style="color: blue">get </span>{ <span style="color: blue">if </span>(instance.IsNull())
{ instance = <span style="color: blue">new </span><span style="color: #2b91af">PermitRepository</span>();
} <span style="color: blue">return </span>instance; } <span style="color: blue">set </span>{
instance = <span style="color: blue">value</span>; } } <span style="color: blue">static </span><span style="color: #2b91af">PermitRepository </span>instance
= <span style="color: blue">new </span><span style="color: #2b91af">PermitRepository</span>();
} }</pre>
        <p>
          <a href="http://11011.net/software/vspaste">
          </a>
        </p>
        <p>
With the test to prove that the newly created Reset() method works as expected:
</p>
        <pre class="code">[<span style="color: #2b91af">Test</span>] <span style="color: blue">public
void </span>can_reset_the_PermitRepositoryInstance() { <span style="color: blue">var </span>repository
= <span style="color: #2b91af">PermitRepository</span>.GetInstance(); <span style="color: blue">int </span>hashCode
= repository.GetHashCode(); hashCode.ShouldEqual(<span style="color: #2b91af">PermitRepository</span>.GetInstance().GetHashCode()); <span style="color: #2b91af">PermitRepository</span>.Reset(); <span style="color: #2b91af">PermitRepository</span>.GetInstance().GetHashCode().ShouldNotEqual(hashCode);
}</pre>
        <a href="http://11011.net/software/vspaste">
        </a>
        <p>
------ Test started: Assembly: Koning.WEWLC.Tests.dll ------ 
</p>
        <p>
2 passed, 0 failed, 0 skipped, took 0.93 seconds.
</p>
        <p>
 
</p>
        <p>
          <strong>The Case of the Onion Parameter</strong>
        </p>
        <p>
In in many cases, it can be hard to create objects. Especially if they take other
object that take other objects in their constructor. Every object needs to be set
up in a good state, a state that makes it ready for additional work. This quite closely
resembles a fat onion. 
</p>
        <p>
Every time when I introduce a DI container to the team I start working with I get
the fat onion argument against using a DI container. Due to the steep object graph
it becomes impossible to instantiate a class manually without having to instantiate
many many others. 
</p>
        <p>
I always reply with, why bother. The DI container will take care of it. If you do
find it cumbersome, apply Extract interface and inject a mock or a stub and you'll
be done with it. 
</p>
        <p>
Feathers makes a huge point for simplicity in his WEWLC but with today's ease of use
with DI containers I don't consider the argument to be valid anymore.
</p>
        <p>
 
</p>
        <p>
          <strong>The case the aliased Parameter</strong>
        </p>
        <p>
If only pieces of a class that is used as a parameter causes problems, we can take
another approach. If we subclass the dependency we don't have to create (yet) another
interface. I personally have no issues whatsoever with many interfaces in a system
as I'm a heavy Resharper user which navigating between classes and interfaces trivial.
</p>
        <p>
When we've subclassed the dependency we can write any behavior we'd like to have in
our fake. Obviously my preference would be to fake the class using Rhino Mocks for
easy of setup and speed of writing.
</p>
        <p>
 
</p>
        <p>
Right, that concludes my second <a href="http://feedproxy.google.com/~r/sbellware/~3/slCk_B0PSo4/lean-reading-list.html" target="_blank">post</a> on
WEWLC, I can't get this class in a test harness. Hope you enjoyed it, let me know
what you think.
</p>
        <img width="0" height="0" src="http://www.tjsolutions.nl/aggbug.ashx?id=06cd78d0-e6f5-4cf7-8ebe-abb2e9f22e02" />
      </body>
      <title>WEWLC - I Can't Get This Class into a Test Harness</title>
      <guid isPermaLink="false">http://www.tjsolutions.nl/PermaLink,guid,06cd78d0-e6f5-4cf7-8ebe-abb2e9f22e02.aspx</guid>
      <link>http://www.tjsolutions.nl/2009/09/14/WEWLCICantGetThisClassIntoATestHarness.aspx</link>
      <pubDate>Mon, 14 Sep 2009 20:14:26 GMT</pubDate>
      <description>&lt;p&gt;
This is the second posting in the &lt;a href="http://www.tjsolutions.nl/2009/06/01/AnnouncingTheSeriesWorkingWithLegacyCode.aspx" target="_blank"&gt;WEWLC-series&lt;/a&gt;. 
&lt;/p&gt;
&lt;p&gt;
&amp;#160;
&lt;/p&gt;
&lt;p&gt;
Other posts are:
&lt;/p&gt;
&lt;p&gt;
&lt;a href="http://www.tjsolutions.nl/2009/09/15/WEWLCICantRunThisMethodInATestHarness.aspx" target="_blank"&gt;I
can't run this method in a test harness&lt;/a&gt;
&lt;/p&gt;
&lt;p&gt;
&lt;a href="http://www.tjsolutions.nl/2009/09/12/WEWLCIDontHaveMuchTimeAndIHaveToChangeIt.aspx" target="_blank"&gt;I
don't have much time and I have to change it&lt;/a&gt;
&lt;/p&gt;
&lt;p&gt;
&lt;a href="http://www.tjsolutions.nl/2009/09/12/WEWLCAssumptions.aspx" target="_blank"&gt;Assumptions
on the reader&lt;/a&gt;
&lt;/p&gt;
&lt;p&gt;
&amp;#160;
&lt;/p&gt;
&lt;p&gt;
&amp;#160;
&lt;/p&gt;
&lt;p&gt;
What to do if the system under test is a nasty legacy class that seems impossible
to get under test? There are various techniques that can help you with this, let get
started with "the case of the irritating parameter".
&lt;/p&gt;
&lt;p&gt;
&amp;#160;
&lt;/p&gt;
&lt;p&gt;
&lt;strong&gt;&lt;/strong&gt;
&lt;/p&gt;
&lt;p&gt;
&lt;strong&gt;&lt;/strong&gt;
&lt;/p&gt;
&lt;p&gt;
&lt;strong&gt;The case of the irritating parameter&lt;/strong&gt;
&lt;/p&gt;
&lt;p&gt;
When you have a SUT that takes complex objects into it's constructor you can easily
circumvent the situation by applying &lt;a href="http://www.refactoring.com/catalog/extractInterface.html" target="_blank"&gt;Extract
interface&lt;/a&gt; on the bothering classes. 
&lt;/p&gt;
&lt;p&gt;
After you have created the necessary interfaces you can utilize &lt;a href="http://ayende.com/wiki/Rhino+Mocks+Documentation.ashx" target="_blank"&gt;Rhino
Mocks&lt;/a&gt; to generate replacement instances (mocks) of the required classes. Rhino
Mocks will actually create an proxy instance for the class. Conveniently, you can
then set expectations &amp;amp; outcomes on these mocks. So without an actual implementation
you fake the system into believing it is dealing with actual classes. 
&lt;/p&gt;
&lt;p&gt;
Let have a look on how this works:
&lt;/p&gt;
&lt;p&gt;
&amp;#160;
&lt;/p&gt;
&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;CreditValidator &lt;/span&gt;{ &lt;span style="color: blue"&gt;readonly &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IDbConnection &lt;/span&gt;connection; &lt;span style="color: blue"&gt;readonly &lt;/span&gt;&lt;span style="color: #2b91af"&gt;ICreditMaster &lt;/span&gt;creditMaster; &lt;span style="color: blue"&gt;public &lt;/span&gt;CreditValidator(&lt;span style="color: #2b91af"&gt;IDbConnection &lt;/span&gt;connection, &lt;span style="color: #2b91af"&gt;ICreditMaster &lt;/span&gt;creditMaster)
{ &lt;span style="color: blue"&gt;this&lt;/span&gt;.connection = connection; &lt;span style="color: blue"&gt;this&lt;/span&gt;.creditMaster
= creditMaster; } } &lt;span style="color: blue"&gt;public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;CreditMaster&lt;/span&gt;: &lt;span style="color: #2b91af"&gt;ICreditMaster &lt;/span&gt;{ &lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;CreditInformation &lt;/span&gt;GetCreditInformation(&lt;span style="color: #2b91af"&gt;Customer &lt;/span&gt;customer)
{ &lt;span style="color: blue"&gt;throw new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;NotImplementedException&lt;/span&gt;();
} } &lt;span style="color: blue"&gt;public interface &lt;/span&gt;&lt;span style="color: #2b91af"&gt;ICreditMaster &lt;/span&gt;{ &lt;span style="color: #2b91af"&gt;CreditInformation &lt;/span&gt;GetCreditInformation(&lt;span style="color: #2b91af"&gt;Customer &lt;/span&gt;customer);
}&lt;/pre&gt;
&lt;p&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;
&lt;/p&gt;
&lt;p&gt;
First off we create an interface for the CreditMaster class. Once that is done we
can start writing the test ask the Rhino MockRepository for an instance of both IDbConnection
and ICreditMaster.
&lt;/p&gt;
&lt;p&gt;
&amp;#160;
&lt;/p&gt;
&lt;pre class="code"&gt;[&lt;span style="color: #2b91af"&gt;TestFixture&lt;/span&gt;] &lt;span style="color: blue"&gt;public
class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;CreditValidatorTests &lt;/span&gt;{ [&lt;span style="color: #2b91af"&gt;Test&lt;/span&gt;] &lt;span style="color: blue"&gt;public
void &lt;/span&gt;can_construct_an_instance_of_the_SUT() { &lt;span style="color: blue"&gt;var &lt;/span&gt;connection
= &lt;span style="color: #2b91af"&gt;MockRepository&lt;/span&gt;.GenerateMock&amp;lt;&lt;span style="color: #2b91af"&gt;IDbConnection&lt;/span&gt;&amp;gt;(); &lt;span style="color: blue"&gt;var &lt;/span&gt;creditMaster
= &lt;span style="color: #2b91af"&gt;MockRepository&lt;/span&gt;.GenerateMock&amp;lt;&lt;span style="color: #2b91af"&gt;ICreditMaster&lt;/span&gt;&amp;gt;(); &lt;span style="color: blue"&gt;var &lt;/span&gt;creditValidator
= &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;CreditValidator&lt;/span&gt;(connection,
creditMaster); creditValidator.ShouldNotBeNull(); } }&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt; 
&lt;p&gt;
&amp;#160;
&lt;/p&gt;
&lt;p&gt;
This test should not throw an exception, I assert on null just to write a clear test.
Run it, and surely enough the test passes.
&lt;/p&gt;
&lt;p&gt;
------ Test started: Assembly: Koning.WEWLC.Tests.dll ------ 
&lt;/p&gt;
&lt;p&gt;
1 passed, 0 failed, 0 skipped, took 1.35 seconds.
&lt;/p&gt;
&lt;p&gt;
&amp;#160;
&lt;/p&gt;
&lt;p&gt;
&amp;#160;
&lt;/p&gt;
&lt;p&gt;
&lt;strong&gt;The Case of the Hidden Dependency&lt;/strong&gt;
&lt;/p&gt;
&lt;p&gt;
Once you get the class instantiated, we try to use it and bang! Some obscure other
complex class is instantiated deep inside and causes the crash. Enter the "case of
the hidden dependency". You need to remove newing the class and either move it to
a public property or to the constructor. You can then either mock the constructor
parameter or set it when you need through the property.
&lt;/p&gt;
&lt;p&gt;
Once you start moving dependencies to the constructor of your classes it quickly starts
to make sense to use a Dependency Injection Container. The one I use most frequently
is Unity as it's included in EntLib and has several advantages over the other DI-containers
available. For one that it's usage it's fairly simple, but even more so that is has
Microsoft's backing, often a requirement at the projects I work.
&lt;/p&gt;
&lt;p&gt;
&amp;#160;
&lt;/p&gt;
&lt;p&gt;
Let's have a look at how such a configuration would look like for a hypothetical complex
class Repository. First create an interface for the Repository and register it in
the BootStrapper. Registration in the Unity container:
&lt;/p&gt;
&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public static class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;BootStrapper &lt;/span&gt;{ &lt;span style="color: blue"&gt;public
static &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IUnityContainer &lt;/span&gt;GetContainer() { &lt;span style="color: blue"&gt;var &lt;/span&gt;container
= &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;UnityContainer&lt;/span&gt;();
container.RegisterType&amp;lt;&lt;span style="color: #2b91af"&gt;IRepository&lt;/span&gt;, &lt;span style="color: #2b91af"&gt;Repository&lt;/span&gt;&amp;gt;(); &lt;span style="color: blue"&gt;return &lt;/span&gt;container;
} } &lt;span style="color: blue"&gt;public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Repository&lt;/span&gt;:&lt;span style="color: #2b91af"&gt;IRepository &lt;/span&gt;{
} &lt;span style="color: blue"&gt;public interface &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IRepository &lt;/span&gt;{
}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt; 
&lt;p&gt;
I prefer to use a static container to resolve dependencies in my applications, like
so
&lt;/p&gt;
&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public static class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;StaticContainer &lt;/span&gt;{ &lt;span style="color: blue"&gt;public
static &lt;/span&gt;T Resolve&amp;lt;T&amp;gt;() { &lt;span style="color: blue"&gt;return &lt;/span&gt;&lt;span style="color: #2b91af"&gt;BootStrapper&lt;/span&gt;.GetContainer().Resolve&amp;lt;T&amp;gt;();
} }&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt; 
&lt;p&gt;
Once the dependency is registered it is simply a matter of retrieving the SUT by requesting
the container to construct it. In your tests you can then choose to have the container
construct the dependencies or have Rhino Mocks generate the mocks after which you
can set expectations on them. 
&lt;/p&gt;
&lt;p&gt;
&amp;#160;
&lt;/p&gt;
&lt;p&gt;
&lt;strong&gt;The Case of the Construction Blob&lt;/strong&gt;
&lt;/p&gt;
&lt;p&gt;
If a constructor constructs a large number of objects internally or accesses a large
number of globals, we could end up with a very large parameter list. One simple rule
is to avoid the construction altogether and move the result of the creation logic
into a dependency property. You could then have your DI container inject it at will
or inject a mock when used in a test harness.
&lt;/p&gt;
&lt;p&gt;
&amp;#160;
&lt;/p&gt;
&lt;p&gt;
&amp;#160;
&lt;/p&gt;
&lt;p&gt;
&lt;strong&gt;The case of the Irritating Global Dependency&lt;/strong&gt;
&lt;/p&gt;
&lt;p&gt;
In WEWLC, Michael Feathers writes: "Many different kinds of dependency can make it
hard to create and use classes in a testing framework, but one of the hardest to deal
with is global variable usage."
&lt;/p&gt;
&lt;p&gt;
He's describing the hideous Singleton use in legacy code. Personally I haven't run
into problems with a Singleton. Partly, because I didn't write tests at the time I
was using them and on the other hand because nowadays I simply ask my DI container
for a Singleton when I need it.
&lt;/p&gt;
&lt;p&gt;
Still, Singletons can be a pain in the ass and you should try to avoid them. The whole
idea of the singleton pattern is to make it impossible to create more than one instance
of a singleton in an application. Because it is, it is particularly hard to fake.
What do you do when you encounter one?
&lt;/p&gt;
&lt;p&gt;
Basically you have three options, one is to replace all occurrences in the code; this
can be a very tedious job, but with the aid of Resharper, one that I would recommend.
&lt;/p&gt;
&lt;p&gt;
The other is to add a static method to the Singleton that will allow you to pass in
a fake. First the lazy Singleton implementation (I have omitted any useful methods
for&amp;#160; brevity):
&lt;/p&gt;
&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;PermitRepository &lt;/span&gt;{ &lt;span style="color: blue"&gt;protected &lt;/span&gt;PermitRepository()
{ } &lt;span style="color: blue"&gt;public static &lt;/span&gt;&lt;span style="color: #2b91af"&gt;PermitRepository &lt;/span&gt;GetInstance()
{ &lt;span style="color: blue"&gt;return &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Nested&lt;/span&gt;.Instance;
} &lt;span style="color: blue"&gt;public static void &lt;/span&gt;SetInstance(&lt;span style="color: #2b91af"&gt;PermitRepository &lt;/span&gt;repository)
{ &lt;span style="color: #2b91af"&gt;Nested&lt;/span&gt;.Instance = repository; } &lt;span style="color: blue"&gt;class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Nested &lt;/span&gt;{ &lt;span style="color: green"&gt;//
Explicit static constructor to tell C# compiler // not to mark type as beforefieldinit &lt;/span&gt;&lt;span style="color: blue"&gt;static &lt;/span&gt;Nested()
{ } &lt;span style="color: blue"&gt;public static &lt;/span&gt;&lt;span style="color: #2b91af"&gt;PermitRepository &lt;/span&gt;Instance
{ &lt;span style="color: blue"&gt;get &lt;/span&gt;{ &lt;span style="color: blue"&gt;return &lt;/span&gt;instance;
} &lt;span style="color: blue"&gt;set &lt;/span&gt;{ instance = &lt;span style="color: blue"&gt;value&lt;/span&gt;;
} } &lt;span style="color: blue"&gt;static &lt;/span&gt;&lt;span style="color: #2b91af"&gt;PermitRepository &lt;/span&gt;instance
= &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;PermitRepository&lt;/span&gt;();
} }&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt; 
&lt;p&gt;
&amp;#160;
&lt;/p&gt;
&lt;p&gt;
&amp;#160;
&lt;/p&gt;
&lt;p&gt;
And to prove that getting multiple calls of the GetInstance() method will return the
same object whilst using the SetInstance method will change the instance field the
following test:
&lt;/p&gt;
&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;FakePermitRepository &lt;/span&gt;: &lt;span style="color: #2b91af"&gt;PermitRepository &lt;/span&gt;{
}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt; &lt;pre class="code"&gt;[&lt;span style="color: #2b91af"&gt;TestFixture&lt;/span&gt;] &lt;span style="color: blue"&gt;public
class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;PermitRepositoryTests &lt;/span&gt;{ [&lt;span style="color: #2b91af"&gt;Test&lt;/span&gt;] &lt;span style="color: blue"&gt;public
void &lt;/span&gt;can_replace_the_PermitRepositoryInstance() { &lt;span style="color: blue"&gt;var &lt;/span&gt;repository
= &lt;span style="color: #2b91af"&gt;PermitRepository&lt;/span&gt;.GetInstance(); &lt;span style="color: blue"&gt;int &lt;/span&gt;hashCode
= repository.GetHashCode(); hashCode.ShouldEqual(&lt;span style="color: #2b91af"&gt;PermitRepository&lt;/span&gt;.GetInstance().GetHashCode()); &lt;span style="color: #2b91af"&gt;PermitRepository&lt;/span&gt;.SetInstance(&lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;FakePermitRepository&lt;/span&gt;()); &lt;span style="color: #2b91af"&gt;PermitRepository&lt;/span&gt;.GetInstance().GetHashCode().ShouldNotEqual(hashCode);
} }&lt;/pre&gt;
&lt;p&gt;
------ Test started: Assembly: Koning.WEWLC.Tests.dll ------ 
&lt;/p&gt;
&lt;p&gt;
1 passed, 0 failed, 0 skipped, took 1.35 seconds.
&lt;/p&gt;
&lt;p&gt;
&amp;#160;
&lt;/p&gt;
&lt;p&gt;
The third option is to reset the private instance field of the Singleton and set it
to null. First we alter the nested class a bit so that it checks for IsNull() before
returning the object:
&lt;/p&gt;
&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;PermitRepository &lt;/span&gt;{ &lt;span style="color: blue"&gt;protected &lt;/span&gt;PermitRepository()
{ } &lt;span style="color: blue"&gt;public static &lt;/span&gt;&lt;span style="color: #2b91af"&gt;PermitRepository &lt;/span&gt;GetInstance()
{ &lt;span style="color: blue"&gt;return &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Nested&lt;/span&gt;.Instance;
} &lt;span style="color: blue"&gt;public static void &lt;/span&gt;SetInstance(&lt;span style="color: #2b91af"&gt;PermitRepository &lt;/span&gt;repository)
{ &lt;span style="color: #2b91af"&gt;Nested&lt;/span&gt;.Instance = repository; } &lt;span style="color: blue"&gt;public
static void &lt;/span&gt;Reset() { &lt;span style="color: #2b91af"&gt;Nested&lt;/span&gt;.Instance = &lt;span style="color: blue"&gt;null&lt;/span&gt;;
} &lt;span style="color: blue"&gt;public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Nested &lt;/span&gt;{ &lt;span style="color: green"&gt;//
Explicit static constructor to tell C# compiler // not to mark type as beforefieldinit &lt;/span&gt;&lt;span style="color: blue"&gt;static &lt;/span&gt;Nested()
{ } &lt;span style="color: blue"&gt;public static &lt;/span&gt;&lt;span style="color: #2b91af"&gt;PermitRepository &lt;/span&gt;Instance
{ &lt;span style="color: blue"&gt;get &lt;/span&gt;{ &lt;span style="color: blue"&gt;if &lt;/span&gt;(instance.IsNull())
{ instance = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;PermitRepository&lt;/span&gt;();
} &lt;span style="color: blue"&gt;return &lt;/span&gt;instance; } &lt;span style="color: blue"&gt;set &lt;/span&gt;{
instance = &lt;span style="color: blue"&gt;value&lt;/span&gt;; } } &lt;span style="color: blue"&gt;static &lt;/span&gt;&lt;span style="color: #2b91af"&gt;PermitRepository &lt;/span&gt;instance
= &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;PermitRepository&lt;/span&gt;();
} }&lt;/pre&gt;
&lt;p&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;
&lt;/p&gt;
&lt;p&gt;
With the test to prove that the newly created Reset() method works as expected:
&lt;/p&gt;
&lt;pre class="code"&gt;[&lt;span style="color: #2b91af"&gt;Test&lt;/span&gt;] &lt;span style="color: blue"&gt;public
void &lt;/span&gt;can_reset_the_PermitRepositoryInstance() { &lt;span style="color: blue"&gt;var &lt;/span&gt;repository
= &lt;span style="color: #2b91af"&gt;PermitRepository&lt;/span&gt;.GetInstance(); &lt;span style="color: blue"&gt;int &lt;/span&gt;hashCode
= repository.GetHashCode(); hashCode.ShouldEqual(&lt;span style="color: #2b91af"&gt;PermitRepository&lt;/span&gt;.GetInstance().GetHashCode()); &lt;span style="color: #2b91af"&gt;PermitRepository&lt;/span&gt;.Reset(); &lt;span style="color: #2b91af"&gt;PermitRepository&lt;/span&gt;.GetInstance().GetHashCode().ShouldNotEqual(hashCode);
}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt; 
&lt;p&gt;
------ Test started: Assembly: Koning.WEWLC.Tests.dll ------ 
&lt;/p&gt;
&lt;p&gt;
2 passed, 0 failed, 0 skipped, took 0.93 seconds.
&lt;/p&gt;
&lt;p&gt;
&amp;#160;
&lt;/p&gt;
&lt;p&gt;
&lt;strong&gt;The Case of the Onion Parameter&lt;/strong&gt;
&lt;/p&gt;
&lt;p&gt;
In in many cases, it can be hard to create objects. Especially if they take other
object that take other objects in their constructor. Every object needs to be set
up in a good state, a state that makes it ready for additional work. This quite closely
resembles a fat onion. 
&lt;/p&gt;
&lt;p&gt;
Every time when I introduce a DI container to the team I start working with I get
the fat onion argument against using a DI container. Due to the steep object graph
it becomes impossible to instantiate a class manually without having to instantiate
many many others. 
&lt;/p&gt;
&lt;p&gt;
I always reply with, why bother. The DI container will take care of it. If you do
find it cumbersome, apply Extract interface and inject a mock or a stub and you'll
be done with it. 
&lt;/p&gt;
&lt;p&gt;
Feathers makes a huge point for simplicity in his WEWLC but with today's ease of use
with DI containers I don't consider the argument to be valid anymore.
&lt;/p&gt;
&lt;p&gt;
&amp;#160;
&lt;/p&gt;
&lt;p&gt;
&lt;strong&gt;The case the aliased Parameter&lt;/strong&gt;
&lt;/p&gt;
&lt;p&gt;
If only pieces of a class that is used as a parameter causes problems, we can take
another approach. If we subclass the dependency we don't have to create (yet) another
interface. I personally have no issues whatsoever with many interfaces in a system
as I'm a heavy Resharper user which navigating between classes and interfaces trivial.
&lt;/p&gt;
&lt;p&gt;
When we've subclassed the dependency we can write any behavior we'd like to have in
our fake. Obviously my preference would be to fake the class using Rhino Mocks for
easy of setup and speed of writing.
&lt;/p&gt;
&lt;p&gt;
&amp;#160;
&lt;/p&gt;
&lt;p&gt;
Right, that concludes my second &lt;a href="http://feedproxy.google.com/~r/sbellware/~3/slCk_B0PSo4/lean-reading-list.html" target="_blank"&gt;post&lt;/a&gt; on
WEWLC, I can't get this class in a test harness. Hope you enjoyed it, let me know
what you think.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.tjsolutions.nl/aggbug.ashx?id=06cd78d0-e6f5-4cf7-8ebe-abb2e9f22e02" /&gt;</description>
      <comments>http://www.tjsolutions.nl/CommentView,guid,06cd78d0-e6f5-4cf7-8ebe-abb2e9f22e02.aspx</comments>
      <category>WEWLC</category>
    </item>
    <item>
      <trackback:ping>http://www.tjsolutions.nl/Trackback.aspx?guid=44b7e1e9-0adb-4987-9d13-f6303158fc76</trackback:ping>
      <pingback:server>http://www.tjsolutions.nl/pingback.aspx</pingback:server>
      <pingback:target>http://www.tjsolutions.nl/PermaLink,guid,44b7e1e9-0adb-4987-9d13-f6303158fc76.aspx</pingback:target>
      <dc:creator>Tom</dc:creator>
      <wfw:comment>http://www.tjsolutions.nl/CommentView,guid,44b7e1e9-0adb-4987-9d13-f6303158fc76.aspx</wfw:comment>
      <wfw:commentRss>http://www.tjsolutions.nl/SyndicationService.asmx/GetEntryCommentsRss?guid=44b7e1e9-0adb-4987-9d13-f6303158fc76</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
Who hasn't been into this position? I think we all know the drill: "we'd like you
to do it know and you have until xxx to fix it". How do you approach such a situation?
Do you open the source and start hammering code in an unbelievable pace or do you
think the changes through, think where you will be invasive and what tests need to
be written?
</p>
        <p>
This (long overdue) first post is regarding making those changes. I will assume you
have a working understanding about this.
</p>
        <p>
 
</p>
        <p>
Right, let's get started. If you don't have much time and you still need to make the
change there are some techniques that let you safely insert / inject code while minimizing
the risk of introducing errors.
</p>
        <p>
 
</p>
        <p>
          <strong>Sprout Method</strong>
        </p>
        <p>
WEWLC: "When you need to add a feature to a system and it can be formulated completely
as new code, write the code in a new method. Call it from the places where the new
functionality needs to be"
</p>
        <p>
This is a nice trick in that it will allow you to write the new code in a test harness
provided you can instantiate the system under test (SUT).
</p>
        <p>
 
</p>
        <p>
Suppose we a class TransactionGate that is used to <a href="http://feedproxy.google.com/~r/sbellware/~3/slCk_B0PSo4/lean-reading-list.html" target="_blank">post</a> entries.
These entries need to have a certain timestamp that is applied before adding the entries
to the transactionBundle.  
</p>
        <pre class="code">
          <span style="color: blue">public class </span>
          <span style="color: #2b91af">TransactionGate </span>{ <span style="color: blue">readonly </span><span style="color: #2b91af">IList</span>&lt;<span style="color: #2b91af">Entry</span>&gt;
transactionBundle = <span style="color: blue">new </span><span style="color: #2b91af">List</span>&lt;<span style="color: #2b91af">Entry</span>&gt;(); <span style="color: blue">public
void </span>PostEntries(<span style="color: #2b91af">List</span>&lt;<span style="color: #2b91af">Entry</span>&gt;
entries) { entries.ForEach(entry =&gt; { entry.PostDate(); transactionBundle.Add(entry);
}); } }</pre>
        <a href="http://11011.net/software/vspaste">
        </a>
        <p>
 
</p>
        <p>
Now the requirement is that we check whether an entry is already listed in the transactionBundle
before we add it. Fair enough, we change the code to look like this:
</p>
        <pre class="code">
          <span style="color: blue">public class </span>
          <span style="color: #2b91af">TransactionGate </span>{ <span style="color: blue">readonly </span><span style="color: #2b91af">IList</span>&lt;<span style="color: #2b91af">Entry</span>&gt;
transactionBundle = <span style="color: blue">new </span><span style="color: #2b91af">List</span>&lt;<span style="color: #2b91af">Entry</span>&gt;(); <span style="color: blue">public
void </span>PostEntries(<span style="color: #2b91af">List</span>&lt;<span style="color: #2b91af">Entry</span>&gt;
entries) { entries.ForEach(entry =&gt; { entry.PostDate(); <span style="color: blue">if </span>(!transactionBundle.Contains(entry))
{ transactionBundle.Add(entry); } }); } }</pre>
        <p>
          <a href="http://11011.net/software/vspaste">
          </a>
        </p>
        <p>
Contrived as it may look like we are actually making the code worse. What if the next
day another requirement is to alter the conditional? It would be very tempting to
simply add the next bit of code as well making the code start to rot.
</p>
        <p>
A better solution is to use <strong>Sprout method</strong>. In this case, filter out
the entries that are already in the transactionBundle and only add those. 
</p>
        <pre class="code">
          <span style="color: blue">public class </span>
          <span style="color: #2b91af">TransactionGate </span>{ <span style="color: blue">public </span>TransactionGate()
{ TransactionBundle = <span style="color: blue">new </span><span style="color: #2b91af">List</span>&lt;<span style="color: #2b91af">Entry</span>&gt;();
} <span style="color: blue">public </span><span style="color: #2b91af">IList</span>&lt;<span style="color: #2b91af">Entry</span>&gt;
TransactionBundle { <span style="color: blue">get</span>; <span style="color: blue">set</span>;
} <span style="color: blue">public void </span>PostEntries(<span style="color: #2b91af">IList</span>&lt;<span style="color: #2b91af">Entry</span>&gt;
entries) { <span style="color: blue">var </span>newEntries = FilterEntries(entries);
newEntries.ForEach(entry =&gt; { entry.PostDate(); TransactionBundle.Add(entry); });
} <span style="color: #2b91af">IList</span>&lt;<span style="color: #2b91af">Entry</span>&gt;
FilterEntries(<span style="color: #2b91af">IEnumerable</span>&lt;<span style="color: #2b91af">Entry</span>&gt;
entries) { <span style="color: blue">return </span>entries .Where(s =&gt; !TransactionBundle.Contains(s))
.ToList(); } }</pre>
        <a href="http://11011.net/software/vspaste">
        </a>
        <p>
          <a href="http://11011.net/software/vspaste">
          </a>It would be trivial simple to unit
test the newly created method:
</p>
        <pre class="code">
          <span style="color: blue">public class </span>
          <span style="color: #2b91af">TransactionGateTests</span>: <span style="color: #2b91af">ContextSpecification</span>&lt;<span style="color: #2b91af">TransactionGate</span>&gt;
{ [<span style="color: #2b91af">Test</span>] <span style="color: blue">public void </span>when_an_entry_is_added_that_is_already_in_the_transactionBundle_it_should_not_Be_added()
{ <span style="color: blue">var </span>transactionGate = <span style="color: blue">new </span><span style="color: #2b91af">TransactionGate</span>();
transactionGate.PostEntries(<span style="color: blue">new</span>[] {<span style="color: blue">new </span><span style="color: #2b91af">Entry</span>(1), <span style="color: blue">new </span><span style="color: #2b91af">Entry</span>(2)});
transactionGate.PostEntries(<span style="color: blue">new</span>[]{<span style="color: blue">new </span><span style="color: #2b91af">Entry</span>(1),
}); transactionGate.TransactionBundle.Count().ShouldEqual(2); } }</pre>
        <a href="http://11011.net/software/vspaste">
        </a>
        <p>
------ Test started: Assembly: Koning.WEWLC.Tests.dll ------ 
</p>
        <p>
1 passed, 0 failed, 0 skipped, took 1.23 seconds.
</p>
        <p>
 
</p>
        <p>
However, if you then create this test:
</p>
        <p>
[<span style="color: #2b91af">Test</span>] 
<br /><span style="color: blue">public void </span>when_duplicate_entries_are_added_that_were_not_before_in_the_bundle_only_unique_entries_should_be_added() 
<br />
{ 
<br />
    <span style="color: blue">var </span>transactionGate = <span style="color: blue">new </span><span style="color: #2b91af">TransactionGate</span>(); 
<br />
    transactionGate.PostEntries(<span style="color: blue">new</span>[]
{ <span style="color: blue">new </span><span style="color: #2b91af">Entry</span>(1), <span style="color: blue">new </span><span style="color: #2b91af">Entry</span>(1)
}); 
<br />
    transactionGate.TransactionBundle.Count().ShouldEqual(1); 
<br />
} 
<br /></p>
        <p>
if fails miserably:
</p>
        <p>
------ Test started: Assembly: Koning.WEWLC.Tests.dll ------ 
</p>
        <p>
TestCase 'Koning.WEWLC.Tests.TransactionGateTests
</p>
        <p>
.when_duplicate_entries_are_added_that_were_not_before_in_the_bundle_only_unique_entries_should_be_added'
failed: 
<br />
  Expected: 1 
<br />
  But was:  2 
<br />
    at Machine.Specifications.NUnitShouldExtensionMethods.ShouldEqual(Object
actual, Object expected) 
<br />
    C:\Dev\Personal\WEWLC\Koning.WEWLC\Koning.WEWLC.Tests\Tests\TransactionGateTests.cs(25,0):
at Koning.WEWLC.Tests.TransactionGateTests.
</p>
        <p>
when_duplicate_entries_are_added_that_were_not_before_in_the_bundle_only_unique_entries_should_be_added() 
</p>
        <p>
1 passed, <strong>1 failed</strong>, 0 skipped, took 1.24 seconds<strong>.</strong></p>
        <a href="http://11011.net/software/vspaste">
        </a>
        <a href="http://11011.net/software/vspaste">
        </a>
        <p>
 
</p>
        <p>
If you take a look at the initial code we wrote then it becomes obviously clear that
there is a huge benefit to writing the code in a new method: the code to PostEntries
does not need to change, we only need to correct the code in the GetNewEntriesFrom
method.
</p>
        <p>
We now have a test that fails, good! Let's add a Distinct() clause to the filtering
code so that the test passes:
</p>
        <pre class="code">
          <span style="color: blue">public class </span>
          <span style="color: #2b91af">TransactionGate </span>{ <span style="color: blue">public </span>TransactionGate()
{ TransactionBundle = <span style="color: blue">new </span><span style="color: #2b91af">List</span>&lt;<span style="color: #2b91af">Entry</span>&gt;();
} <span style="color: blue">public </span><span style="color: #2b91af">IList</span>&lt;<span style="color: #2b91af">Entry</span>&gt;
TransactionBundle { <span style="color: blue">get</span>; <span style="color: blue">set</span>;
} <span style="color: blue">public void </span>PostEntries(<span style="color: #2b91af">IList</span>&lt;<span style="color: #2b91af">Entry</span>&gt;
entries) { <span style="color: blue">var </span>newEntries = FilterEntries(entries);
newEntries.ForEach(entry =&gt; { entry.PostDate(); TransactionBundle.Add(entry); });
} <span style="color: #2b91af">IList</span>&lt;<span style="color: #2b91af">Entry</span>&gt;
FilterEntries(<span style="color: #2b91af">IEnumerable</span>&lt;<span style="color: #2b91af">Entry</span>&gt;
entries) { <span style="color: blue">return </span>entries .<strong>Distinct</strong>()
.Where(s =&gt; !TransactionBundle.Contains(s)) .ToList(); } }</pre>
        <a href="http://11011.net/software/vspaste">
        </a>
        <p>
Only a subtle change but one that would not have been obvious if it were not for the
tests written.
</p>
        <p>
 
</p>
        <p>
          <strong>Sprout Class</strong>
        </p>
        <p>
The mechanics between Sprout Class and Sprout Method are not that different. You use
Sprout class if the logic you want to add really belongs in its own separate class.
You can also use Sprout Class if the class to alter is difficult to get into a test
harness. 
</p>
        <p>
 
</p>
        <p>
          <strong>Wrap Method</strong>
        </p>
        <p>
          <a href="http://11011.net/software/vspaste">
            <font color="#000000">When</font>
          </a> you
encounter a method that consists a lot of procedural code it is often easiest to first
wrap the existing method into another method. Say we have the Following PayDispatcher
class:
</p>
        <pre class="code">
          <span style="color: blue">public class </span>
          <span style="color: #2b91af">PayDispatcher </span>{ <span style="color: blue">public
void </span>Pay(<span style="color: #2b91af">Employee </span>employee) { <span style="color: green">//....
a lot of code follows </span>} } <span style="color: blue">public class </span><span style="color: #2b91af">Employee </span>{
}</pre>
        <a href="http://11011.net/software/vspaste">
        </a>
        <p>
Suppose we are required to add logging to the Pay method following. With Resharper
this extraction is made extremely easy using the key combination CTRL-R, M (Extract
method). We first move the code in Pay to DispatchPayment() and then add logging.
</p>
        <p>
 
</p>
        <a href="http://11011.net/software/vspaste">
        </a>
        <p>
You will probably end up with something like this:
</p>
        <pre class="code">
          <span style="color: blue">public class </span>
          <span style="color: #2b91af">PayDispatcher </span>{ <span style="color: blue">public
void </span>Pay(<span style="color: #2b91af">Employee </span>employee) { DispatchPayment(employee);
LogPayment(employee); } <span style="color: blue">void </span>DispatchPayment(<span style="color: #2b91af">Employee </span>employee)
{ <span style="color: green">//.... a lot of code follows </span>} <span style="color: blue">void </span>LogPayment(<span style="color: #2b91af">Employee </span>employee)
{ <span style="color: green">//.... some logging code follows </span>} }</pre>
        <a href="http://11011.net/software/vspaste">
        </a>
        <p>
Now, the point here is to see how wrapping the method calls would increase readability
and isolation of the changes. Obviously the logging could be done in several other
ways.
</p>
        <p>
 
</p>
        <p>
          <strong>Wrap Class</strong>
        </p>
        <p>
One of the (many) alternatives would be to completely wrap the logging into a <a href="http://en.wikipedia.org/wiki/Decorator_pattern" target="_blank">decorator</a>.
Let's have a look.
</p>
        <p>
We first have to undo the logging in the original PayDispatcher class:
</p>
        <pre class="code">
          <span style="color: blue">public class </span>
          <span style="color: #2b91af">PayDispatcher </span>{ <span style="color: blue">public
void </span>Pay(<span style="color: #2b91af">Employee </span>employee) { DispatchPayment(employee);
} <span style="color: blue">void </span>DispatchPayment(<span style="color: #2b91af">Employee </span>employee)
{ <span style="color: green">//.... a lot of code follows </span>} }</pre>
        <p>
We can then write a decorator PayDispatcher that will wrap our existing PayDispatcher
and apply the required logging, like so:
</p>
        <pre class="code">
          <span style="color: blue">public class </span>
          <span style="color: #2b91af">LoggingPayDispatcher </span>{ <span style="color: blue">readonly </span><span style="color: #2b91af">PayDispatcher </span>payDispatcher; <span style="color: blue">public </span>LoggingPayDispatcher(<span style="color: #2b91af">PayDispatcher </span>payDispatcher)
{ <span style="color: blue">this</span>.payDispatcher = payDispatcher; } <span style="color: blue">public
void </span>Pay(<span style="color: #2b91af">Employee </span>employee) { payDispatcher.Pay(employee);
LogPayment(employee); } <span style="color: blue">void </span>LogPayment(<span style="color: #2b91af">Employee </span>employee)
{ <span style="color: green">//.... some logging code follows </span>} }</pre>
This concludes the various approaches found in WEWLC for "I don't have much time and
I have to change it". Hope you liked it, let me know where to improve. <img width="0" height="0" src="http://www.tjsolutions.nl/aggbug.ashx?id=44b7e1e9-0adb-4987-9d13-f6303158fc76" /></body>
      <title>WEWLC - I don’t have much time and I have to change it</title>
      <guid isPermaLink="false">http://www.tjsolutions.nl/PermaLink,guid,44b7e1e9-0adb-4987-9d13-f6303158fc76.aspx</guid>
      <link>http://www.tjsolutions.nl/2009/09/12/WEWLCIDontHaveMuchTimeAndIHaveToChangeIt.aspx</link>
      <pubDate>Sat, 12 Sep 2009 10:55:07 GMT</pubDate>
      <description>&lt;p&gt;
Who hasn't been into this position? I think we all know the drill: "we'd like you
to do it know and you have until xxx to fix it". How do you approach such a situation?
Do you open the source and start hammering code in an unbelievable pace or do you
think the changes through, think where you will be invasive and what tests need to
be written?
&lt;/p&gt;
&lt;p&gt;
This (long overdue) first post is regarding making those changes. I will assume you
have a working understanding about this.
&lt;/p&gt;
&lt;p&gt;
&amp;#160;
&lt;/p&gt;
&lt;p&gt;
Right, let's get started. If you don't have much time and you still need to make the
change there are some techniques that let you safely insert / inject code while minimizing
the risk of introducing errors.
&lt;/p&gt;
&lt;p&gt;
&amp;#160;
&lt;/p&gt;
&lt;p&gt;
&lt;strong&gt;Sprout Method&lt;/strong&gt;
&lt;/p&gt;
&lt;p&gt;
WEWLC: "When you need to add a feature to a system and it can be formulated completely
as new code, write the code in a new method. Call it from the places where the new
functionality needs to be"
&lt;/p&gt;
&lt;p&gt;
This is a nice trick in that it will allow you to write the new code in a test harness
provided you can instantiate the system under test (SUT).
&lt;/p&gt;
&lt;p&gt;
&amp;#160;
&lt;/p&gt;
&lt;p&gt;
Suppose we a class TransactionGate that is used to &lt;a href="http://feedproxy.google.com/~r/sbellware/~3/slCk_B0PSo4/lean-reading-list.html" target="_blank"&gt;post&lt;/a&gt; entries.
These entries need to have a certain timestamp that is applied before adding the entries
to the transactionBundle.&amp;#160; 
&lt;/p&gt;
&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;TransactionGate &lt;/span&gt;{ &lt;span style="color: blue"&gt;readonly &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IList&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Entry&lt;/span&gt;&amp;gt;
transactionBundle = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Entry&lt;/span&gt;&amp;gt;(); &lt;span style="color: blue"&gt;public
void &lt;/span&gt;PostEntries(&lt;span style="color: #2b91af"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Entry&lt;/span&gt;&amp;gt;
entries) { entries.ForEach(entry =&amp;gt; { entry.PostDate(); transactionBundle.Add(entry);
}); } }&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt; 
&lt;p&gt;
&amp;#160;
&lt;/p&gt;
&lt;p&gt;
Now the requirement is that we check whether an entry is already listed in the transactionBundle
before we add it. Fair enough, we change the code to look like this:
&lt;/p&gt;
&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;TransactionGate &lt;/span&gt;{ &lt;span style="color: blue"&gt;readonly &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IList&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Entry&lt;/span&gt;&amp;gt;
transactionBundle = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Entry&lt;/span&gt;&amp;gt;(); &lt;span style="color: blue"&gt;public
void &lt;/span&gt;PostEntries(&lt;span style="color: #2b91af"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Entry&lt;/span&gt;&amp;gt;
entries) { entries.ForEach(entry =&amp;gt; { entry.PostDate(); &lt;span style="color: blue"&gt;if &lt;/span&gt;(!transactionBundle.Contains(entry))
{ transactionBundle.Add(entry); } }); } }&lt;/pre&gt;
&lt;p&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;
&lt;/p&gt;
&lt;p&gt;
Contrived as it may look like we are actually making the code worse. What if the next
day another requirement is to alter the conditional? It would be very tempting to
simply add the next bit of code as well making the code start to rot.
&lt;/p&gt;
&lt;p&gt;
A better solution is to use &lt;strong&gt;Sprout method&lt;/strong&gt;. In this case, filter out
the entries that are already in the transactionBundle and only add those. 
&lt;/p&gt;
&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;TransactionGate &lt;/span&gt;{ &lt;span style="color: blue"&gt;public &lt;/span&gt;TransactionGate()
{ TransactionBundle = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Entry&lt;/span&gt;&amp;gt;();
} &lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IList&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Entry&lt;/span&gt;&amp;gt;
TransactionBundle { &lt;span style="color: blue"&gt;get&lt;/span&gt;; &lt;span style="color: blue"&gt;set&lt;/span&gt;;
} &lt;span style="color: blue"&gt;public void &lt;/span&gt;PostEntries(&lt;span style="color: #2b91af"&gt;IList&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Entry&lt;/span&gt;&amp;gt;
entries) { &lt;span style="color: blue"&gt;var &lt;/span&gt;newEntries = FilterEntries(entries);
newEntries.ForEach(entry =&amp;gt; { entry.PostDate(); TransactionBundle.Add(entry); });
} &lt;span style="color: #2b91af"&gt;IList&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Entry&lt;/span&gt;&amp;gt;
FilterEntries(&lt;span style="color: #2b91af"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Entry&lt;/span&gt;&amp;gt;
entries) { &lt;span style="color: blue"&gt;return &lt;/span&gt;entries .Where(s =&amp;gt; !TransactionBundle.Contains(s))
.ToList(); } }&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt; 
&lt;p&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;It would be trivial simple to unit
test the newly created method:
&lt;/p&gt;
&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;TransactionGateTests&lt;/span&gt;: &lt;span style="color: #2b91af"&gt;ContextSpecification&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;TransactionGate&lt;/span&gt;&amp;gt;
{ [&lt;span style="color: #2b91af"&gt;Test&lt;/span&gt;] &lt;span style="color: blue"&gt;public void &lt;/span&gt;when_an_entry_is_added_that_is_already_in_the_transactionBundle_it_should_not_Be_added()
{ &lt;span style="color: blue"&gt;var &lt;/span&gt;transactionGate = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;TransactionGate&lt;/span&gt;();
transactionGate.PostEntries(&lt;span style="color: blue"&gt;new&lt;/span&gt;[] {&lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Entry&lt;/span&gt;(1), &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Entry&lt;/span&gt;(2)});
transactionGate.PostEntries(&lt;span style="color: blue"&gt;new&lt;/span&gt;[]{&lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Entry&lt;/span&gt;(1),
}); transactionGate.TransactionBundle.Count().ShouldEqual(2); } }&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt; 
&lt;p&gt;
------ Test started: Assembly: Koning.WEWLC.Tests.dll ------ 
&lt;/p&gt;
&lt;p&gt;
1 passed, 0 failed, 0 skipped, took 1.23 seconds.
&lt;/p&gt;
&lt;p&gt;
&amp;#160;
&lt;/p&gt;
&lt;p&gt;
However, if you then create this test:
&lt;/p&gt;
&lt;p&gt;
[&lt;span style="color: #2b91af"&gt;Test&lt;/span&gt;] 
&lt;br /&gt;
&lt;span style="color: blue"&gt;public void &lt;/span&gt;when_duplicate_entries_are_added_that_were_not_before_in_the_bundle_only_unique_entries_should_be_added() 
&lt;br /&gt;
{ 
&lt;br /&gt;
&amp;#160;&amp;#160;&amp;#160; &lt;span style="color: blue"&gt;var &lt;/span&gt;transactionGate = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;TransactionGate&lt;/span&gt;(); 
&lt;br /&gt;
&amp;#160;&amp;#160;&amp;#160; transactionGate.PostEntries(&lt;span style="color: blue"&gt;new&lt;/span&gt;[]
{ &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Entry&lt;/span&gt;(1), &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Entry&lt;/span&gt;(1)
}); 
&lt;br /&gt;
&amp;#160;&amp;#160;&amp;#160; transactionGate.TransactionBundle.Count().ShouldEqual(1); 
&lt;br /&gt;
} 
&lt;br /&gt;
&lt;/p&gt;
&lt;p&gt;
if fails miserably:
&lt;/p&gt;
&lt;p&gt;
------ Test started: Assembly: Koning.WEWLC.Tests.dll ------ 
&lt;/p&gt;
&lt;p&gt;
TestCase 'Koning.WEWLC.Tests.TransactionGateTests
&lt;/p&gt;
&lt;p&gt;
.when_duplicate_entries_are_added_that_were_not_before_in_the_bundle_only_unique_entries_should_be_added'
failed: 
&lt;br /&gt;
&amp;#160; Expected: 1 
&lt;br /&gt;
&amp;#160; But was:&amp;#160; 2 
&lt;br /&gt;
&amp;#160;&amp;#160;&amp;#160; at Machine.Specifications.NUnitShouldExtensionMethods.ShouldEqual(Object
actual, Object expected) 
&lt;br /&gt;
&amp;#160;&amp;#160;&amp;#160; C:\Dev\Personal\WEWLC\Koning.WEWLC\Koning.WEWLC.Tests\Tests\TransactionGateTests.cs(25,0):
at Koning.WEWLC.Tests.TransactionGateTests.
&lt;/p&gt;
&lt;p&gt;
when_duplicate_entries_are_added_that_were_not_before_in_the_bundle_only_unique_entries_should_be_added() 
&lt;/p&gt;
&lt;p&gt;
1 passed, &lt;strong&gt;1 failed&lt;/strong&gt;, 0 skipped, took 1.24 seconds&lt;strong&gt;.&lt;/strong&gt; 
&lt;/p&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt;&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt; 
&lt;p&gt;
&amp;#160;
&lt;/p&gt;
&lt;p&gt;
If you take a look at the initial code we wrote then it becomes obviously clear that
there is a huge benefit to writing the code in a new method: the code to PostEntries
does not need to change, we only need to correct the code in the GetNewEntriesFrom
method.
&lt;/p&gt;
&lt;p&gt;
We now have a test that fails, good! Let's add a Distinct() clause to the filtering
code so that the test passes:
&lt;/p&gt;
&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;TransactionGate &lt;/span&gt;{ &lt;span style="color: blue"&gt;public &lt;/span&gt;TransactionGate()
{ TransactionBundle = &lt;span style="color: blue"&gt;new &lt;/span&gt;&lt;span style="color: #2b91af"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Entry&lt;/span&gt;&amp;gt;();
} &lt;span style="color: blue"&gt;public &lt;/span&gt;&lt;span style="color: #2b91af"&gt;IList&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Entry&lt;/span&gt;&amp;gt;
TransactionBundle { &lt;span style="color: blue"&gt;get&lt;/span&gt;; &lt;span style="color: blue"&gt;set&lt;/span&gt;;
} &lt;span style="color: blue"&gt;public void &lt;/span&gt;PostEntries(&lt;span style="color: #2b91af"&gt;IList&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Entry&lt;/span&gt;&amp;gt;
entries) { &lt;span style="color: blue"&gt;var &lt;/span&gt;newEntries = FilterEntries(entries);
newEntries.ForEach(entry =&amp;gt; { entry.PostDate(); TransactionBundle.Add(entry); });
} &lt;span style="color: #2b91af"&gt;IList&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Entry&lt;/span&gt;&amp;gt;
FilterEntries(&lt;span style="color: #2b91af"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Entry&lt;/span&gt;&amp;gt;
entries) { &lt;span style="color: blue"&gt;return &lt;/span&gt;entries .&lt;strong&gt;Distinct&lt;/strong&gt;()
.Where(s =&amp;gt; !TransactionBundle.Contains(s)) .ToList(); } }&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt; 
&lt;p&gt;
Only a subtle change but one that would not have been obvious if it were not for the
tests written.
&lt;/p&gt;
&lt;p&gt;
&amp;#160;
&lt;/p&gt;
&lt;p&gt;
&lt;strong&gt;Sprout Class&lt;/strong&gt;
&lt;/p&gt;
&lt;p&gt;
The mechanics between Sprout Class and Sprout Method are not that different. You use
Sprout class if the logic you want to add really belongs in its own separate class.
You can also use Sprout Class if the class to alter is difficult to get into a test
harness. 
&lt;/p&gt;
&lt;p&gt;
&amp;#160;
&lt;/p&gt;
&lt;p&gt;
&lt;strong&gt;Wrap Method&lt;/strong&gt;
&lt;/p&gt;
&lt;p&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;font color="#000000"&gt;When&lt;/font&gt;&lt;/a&gt; you
encounter a method that consists a lot of procedural code it is often easiest to first
wrap the existing method into another method. Say we have the Following PayDispatcher
class:
&lt;/p&gt;
&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;PayDispatcher &lt;/span&gt;{ &lt;span style="color: blue"&gt;public
void &lt;/span&gt;Pay(&lt;span style="color: #2b91af"&gt;Employee &lt;/span&gt;employee) { &lt;span style="color: green"&gt;//....
a lot of code follows &lt;/span&gt;} } &lt;span style="color: blue"&gt;public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;Employee &lt;/span&gt;{
}&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt; 
&lt;p&gt;
Suppose we are required to add logging to the Pay method following. With Resharper
this extraction is made extremely easy using the key combination CTRL-R, M (Extract
method). We first move the code in Pay to DispatchPayment() and then add logging.
&lt;/p&gt;
&lt;p&gt;
&amp;#160;
&lt;/p&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt; 
&lt;p&gt;
You will probably end up with something like this:
&lt;/p&gt;
&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;PayDispatcher &lt;/span&gt;{ &lt;span style="color: blue"&gt;public
void &lt;/span&gt;Pay(&lt;span style="color: #2b91af"&gt;Employee &lt;/span&gt;employee) { DispatchPayment(employee);
LogPayment(employee); } &lt;span style="color: blue"&gt;void &lt;/span&gt;DispatchPayment(&lt;span style="color: #2b91af"&gt;Employee &lt;/span&gt;employee)
{ &lt;span style="color: green"&gt;//.... a lot of code follows &lt;/span&gt;} &lt;span style="color: blue"&gt;void &lt;/span&gt;LogPayment(&lt;span style="color: #2b91af"&gt;Employee &lt;/span&gt;employee)
{ &lt;span style="color: green"&gt;//.... some logging code follows &lt;/span&gt;} }&lt;/pre&gt;
&lt;a href="http://11011.net/software/vspaste"&gt;&lt;/a&gt; 
&lt;p&gt;
Now, the point here is to see how wrapping the method calls would increase readability
and isolation of the changes. Obviously the logging could be done in several other
ways.
&lt;/p&gt;
&lt;p&gt;
&amp;#160;
&lt;/p&gt;
&lt;p&gt;
&lt;strong&gt;Wrap Class&lt;/strong&gt;
&lt;/p&gt;
&lt;p&gt;
One of the (many) alternatives would be to completely wrap the logging into a &lt;a href="http://en.wikipedia.org/wiki/Decorator_pattern" target="_blank"&gt;decorator&lt;/a&gt;.
Let's have a look.
&lt;/p&gt;
&lt;p&gt;
We first have to undo the logging in the original PayDispatcher class:
&lt;/p&gt;
&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;PayDispatcher &lt;/span&gt;{ &lt;span style="color: blue"&gt;public
void &lt;/span&gt;Pay(&lt;span style="color: #2b91af"&gt;Employee &lt;/span&gt;employee) { DispatchPayment(employee);
} &lt;span style="color: blue"&gt;void &lt;/span&gt;DispatchPayment(&lt;span style="color: #2b91af"&gt;Employee &lt;/span&gt;employee)
{ &lt;span style="color: green"&gt;//.... a lot of code follows &lt;/span&gt;} }&lt;/pre&gt;
&lt;p&gt;
We can then write a decorator PayDispatcher that will wrap our existing PayDispatcher
and apply the required logging, like so:
&lt;/p&gt;
&lt;pre class="code"&gt;&lt;span style="color: blue"&gt;public class &lt;/span&gt;&lt;span style="color: #2b91af"&gt;LoggingPayDispatcher &lt;/span&gt;{ &lt;span style="color: blue"&gt;readonly &lt;/span&gt;&lt;span style="color: #2b91af"&gt;PayDispatcher &lt;/span&gt;payDispatcher; &lt;span style="color: blue"&gt;public &lt;/span&gt;LoggingPayDispatcher(&lt;span style="color: #2b91af"&gt;PayDispatcher &lt;/span&gt;payDispatcher)
{ &lt;span style="color: blue"&gt;this&lt;/span&gt;.payDispatcher = payDispatcher; } &lt;span style="color: blue"&gt;public
void &lt;/span&gt;Pay(&lt;span style="color: #2b91af"&gt;Employee &lt;/span&gt;employee) { payDispatcher.Pay(employee);
LogPayment(employee); } &lt;span style="color: blue"&gt;void &lt;/span&gt;LogPayment(&lt;span style="color: #2b91af"&gt;Employee &lt;/span&gt;employee)
{ &lt;span style="color: green"&gt;//.... some logging code follows &lt;/span&gt;} }&lt;/pre&gt;
This concludes the various approaches found in WEWLC for "I don't have much time and
I have to change it". Hope you liked it, let me know where to improve. &lt;img width="0" height="0" src="http://www.tjsolutions.nl/aggbug.ashx?id=44b7e1e9-0adb-4987-9d13-f6303158fc76" /&gt;</description>
      <comments>http://www.tjsolutions.nl/CommentView,guid,44b7e1e9-0adb-4987-9d13-f6303158fc76.aspx</comments>
      <category>WEWLC</category>
    </item>
    <item>
      <trackback:ping>http://www.tjsolutions.nl/Trackback.aspx?guid=7623b248-4a56-4e01-8e5c-e34dddf7d947</trackback:ping>
      <pingback:server>http://www.tjsolutions.nl/pingback.aspx</pingback:server>
      <pingback:target>http://www.tjsolutions.nl/PermaLink,guid,7623b248-4a56-4e01-8e5c-e34dddf7d947.aspx</pingback:target>
      <dc:creator>Tijmen</dc:creator>
      <wfw:comment>http://www.tjsolutions.nl/CommentView,guid,7623b248-4a56-4e01-8e5c-e34dddf7d947.aspx</wfw:comment>
      <wfw:commentRss>http://www.tjsolutions.nl/SyndicationService.asmx/GetEntryCommentsRss?guid=7623b248-4a56-4e01-8e5c-e34dddf7d947</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
As I will write the translations of the code snippets from the excellent Working Effectively
With Legacy Code (<a href="http://www.amazon.com/Working-Effectively-Legacy-Michael-Feathers/dp/0131177052" target="_blank">WEWLC</a>)
book by Michael Feathers I will also assume the following:
</p>
        <ul>
          <li>
There is some sort of understanding what <a href="http://martinfowler.com/articles/mocksArentStubs.html" target="_blank">mocks</a> are 
</li>
          <li>
There is some understanding of how Rhino mocks <a href="http://en.wikibooks.org/wiki/How_to_Use_Rhino_Mocks/Introduction" target="_blank">work</a> (if
not, you will find out anyway by continue reading this blog) 
</li>
          <li>
There is some understanding of <a href="http://martinfowler.com/articles/injection.html" target="_blank">Dependency
injection</a></li>
          <li>
One knows what <a href="http://www.testdriven.net/" target="_blank">TestDriven.net</a> is. 
</li>
          <li>
One knows why <a href="http://www.autohotkey.com/" target="_blank">AutoHotKey</a> is
used and what you can do with it 
</li>
          <li>
Some understanding of <a href="http://www.jetbrains.com/resharper/" target="_blank">Reshaper</a></li>
        </ul>
        <img width="0" height="0" src="http://www.tjsolutions.nl/aggbug.ashx?id=7623b248-4a56-4e01-8e5c-e34dddf7d947" />
      </body>
      <title>WEWLC – Assumptions</title>
      <guid isPermaLink="false">http://www.tjsolutions.nl/PermaLink,guid,7623b248-4a56-4e01-8e5c-e34dddf7d947.aspx</guid>
      <link>http://www.tjsolutions.nl/2009/09/12/WEWLCAssumptions.aspx</link>
      <pubDate>Sat, 12 Sep 2009 09:16:26 GMT</pubDate>
      <description>&lt;p&gt;
As I will write the translations of the code snippets from the excellent Working Effectively
With Legacy Code (&lt;a href="http://www.amazon.com/Working-Effectively-Legacy-Michael-Feathers/dp/0131177052" target="_blank"&gt;WEWLC&lt;/a&gt;)
book by Michael Feathers I will also assume the following:
&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
There is some sort of understanding what &lt;a href="http://martinfowler.com/articles/mocksArentStubs.html" target="_blank"&gt;mocks&lt;/a&gt; are 
&lt;/li&gt;
&lt;li&gt;
There is some understanding of how Rhino mocks &lt;a href="http://en.wikibooks.org/wiki/How_to_Use_Rhino_Mocks/Introduction" target="_blank"&gt;work&lt;/a&gt; (if
not, you will find out anyway by continue reading this blog) 
&lt;/li&gt;
&lt;li&gt;
There is some understanding of &lt;a href="http://martinfowler.com/articles/injection.html" target="_blank"&gt;Dependency
injection&lt;/a&gt; 
&lt;/li&gt;
&lt;li&gt;
One knows what &lt;a href="http://www.testdriven.net/" target="_blank"&gt;TestDriven.net&lt;/a&gt; is. 
&lt;/li&gt;
&lt;li&gt;
One knows why &lt;a href="http://www.autohotkey.com/" target="_blank"&gt;AutoHotKey&lt;/a&gt; is
used and what you can do with it 
&lt;/li&gt;
&lt;li&gt;
Some understanding of &lt;a href="http://www.jetbrains.com/resharper/" target="_blank"&gt;Reshaper&lt;/a&gt; 
&lt;/li&gt;
&lt;/ul&gt;
&lt;img width="0" height="0" src="http://www.tjsolutions.nl/aggbug.ashx?id=7623b248-4a56-4e01-8e5c-e34dddf7d947" /&gt;</description>
      <comments>http://www.tjsolutions.nl/CommentView,guid,7623b248-4a56-4e01-8e5c-e34dddf7d947.aspx</comments>
      <category>WEWLC</category>
    </item>
    <item>
      <trackback:ping>http://www.tjsolutions.nl/Trackback.aspx?guid=a51d4f5a-a5bd-4a69-8daa-ca9a71e7e507</trackback:ping>
      <pingback:server>http://www.tjsolutions.nl/pingback.aspx</pingback:server>
      <pingback:target>http://www.tjsolutions.nl/PermaLink,guid,a51d4f5a-a5bd-4a69-8daa-ca9a71e7e507.aspx</pingback:target>
      <dc:creator>Tijmen</dc:creator>
      <wfw:comment>http://www.tjsolutions.nl/CommentView,guid,a51d4f5a-a5bd-4a69-8daa-ca9a71e7e507.aspx</wfw:comment>
      <wfw:commentRss>http://www.tjsolutions.nl/SyndicationService.asmx/GetEntryCommentsRss?guid=a51d4f5a-a5bd-4a69-8daa-ca9a71e7e507</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
I've finally finished reading the excellent <a href="http://www.amazon.co.uk/Working-Effectively-Legacy-Robert-Martin/dp/0131177052" target="_blank">Working
effectively with legacy code</a> by Michael Feathers. It has been quite a struggle
but that's merely because of the amount of useful information in it.
</p>
        <p>
 
</p>
        <p>
The author declares all code that is not under test to be legacy code. Ayende (author
of <a href="http://ayende.com/projects/rhino-mocks.aspx" target="_blank">Rhino mocks</a>)
basically based his mocking framework on the concepts in the book. Not surprisingly,
he recommends the book as <a href="http://ayende.com/Blog/archive/2005/08/28/BookReviewWorkingEffectivelyWithLegacyCode.aspx" target="_blank">well</a>.
</p>
        <p>
 
</p>
        <p>
I recently worked on an application written by another team that had zero unit tests.
It did have a winforms test app included but that was merely for integration testing
and required quite a bit of tweaking before anything useful could come out. 
</p>
        <p>
I started with isolating large chunks of functionality using Dependency injection
with Unity. I then used <a href="http://codebetter.com/blogs/jeremy.miller/archive/2008/02/09/automocker-in-structuremap-2-5.aspx" target="_blank">StructureMap's
automocker</a> to bring most of the codebase under test (+80%). 
</p>
        <p>
Adding the required features was made much easier when most code was under test. This
inspired me to throw a talk on <a href="http://www.werkenbijavanade.nl/events/Pages/mimmei09.aspx" target="_blank">TDD
at meet the Masters</a> in Microsoft at Avanade.
</p>
        <p>
 
</p>
        <p>
I´ll be hosting another talk about PEX next week and in preparing I will be diving
into the book´s concepts. As most of these are written for either Java or C++, my
focus will be around utilizing the same concepts in the beautiful world of .Net.
</p>
        <img width="0" height="0" src="http://www.tjsolutions.nl/aggbug.ashx?id=a51d4f5a-a5bd-4a69-8daa-ca9a71e7e507" />
      </body>
      <title>Announcing the series: Working with legacy code</title>
      <guid isPermaLink="false">http://www.tjsolutions.nl/PermaLink,guid,a51d4f5a-a5bd-4a69-8daa-ca9a71e7e507.aspx</guid>
      <link>http://www.tjsolutions.nl/2009/06/01/AnnouncingTheSeriesWorkingWithLegacyCode.aspx</link>
      <pubDate>Mon, 01 Jun 2009 15:23:05 GMT</pubDate>
      <description>&lt;p&gt;
I've finally finished reading the excellent &lt;a href="http://www.amazon.co.uk/Working-Effectively-Legacy-Robert-Martin/dp/0131177052" target="_blank"&gt;Working
effectively with legacy code&lt;/a&gt; by Michael Feathers. It has been quite a struggle
but that's merely because of the amount of useful information in it.
&lt;/p&gt;
&lt;p&gt;
&amp;nbsp;
&lt;/p&gt;
&lt;p&gt;
The author declares all code that is not under test to be legacy code. Ayende (author
of &lt;a href="http://ayende.com/projects/rhino-mocks.aspx" target="_blank"&gt;Rhino mocks&lt;/a&gt;)
basically based his mocking framework on the concepts in the book. Not surprisingly,
he recommends the book as &lt;a href="http://ayende.com/Blog/archive/2005/08/28/BookReviewWorkingEffectivelyWithLegacyCode.aspx" target="_blank"&gt;well&lt;/a&gt;.
&lt;/p&gt;
&lt;p&gt;
&amp;nbsp;
&lt;/p&gt;
&lt;p&gt;
I recently worked on an application written by another team that had zero unit tests.
It did have a winforms test app included but that was merely for integration testing
and required quite a bit of tweaking before anything useful could come out. 
&lt;/p&gt;
&lt;p&gt;
I started with isolating large chunks of functionality using Dependency injection
with Unity. I then used &lt;a href="http://codebetter.com/blogs/jeremy.miller/archive/2008/02/09/automocker-in-structuremap-2-5.aspx" target="_blank"&gt;StructureMap's
automocker&lt;/a&gt; to bring most of the codebase under test (+80%). 
&lt;/p&gt;
&lt;p&gt;
Adding the required features was made much easier when most code was under test. This
inspired me to throw a talk on &lt;a href="http://www.werkenbijavanade.nl/events/Pages/mimmei09.aspx" target="_blank"&gt;TDD
at meet the Masters&lt;/a&gt; in Microsoft at Avanade.
&lt;/p&gt;
&lt;p&gt;
&amp;nbsp;
&lt;/p&gt;
&lt;p&gt;
I´ll be hosting another talk about PEX next week and in preparing I will be diving
into the book´s concepts. As most of these are written for either Java or C++, my
focus will be around utilizing the same concepts in the beautiful world of .Net.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://www.tjsolutions.nl/aggbug.ashx?id=a51d4f5a-a5bd-4a69-8daa-ca9a71e7e507" /&gt;</description>
      <comments>http://www.tjsolutions.nl/CommentView,guid,a51d4f5a-a5bd-4a69-8daa-ca9a71e7e507.aspx</comments>
      <category>WEWLC</category>
    </item>
  </channel>
</rss>