<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Quickduck &#187; Unit Testing</title>
	<atom:link href="http://quickduck.com/blog/category/development/unit-testing/feed/" rel="self" type="application/rss+xml" />
	<link>http://quickduck.com/blog</link>
	<description>Straight from the mind of geniuseseses....</description>
	<lastBuildDate>Wed, 30 Jun 2010 10:52:18 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>Unit Testing DateTime.Now</title>
		<link>http://quickduck.com/blog/2009/09/07/unit-testing-datetime-now/</link>
		<comments>http://quickduck.com/blog/2009/09/07/unit-testing-datetime-now/#comments</comments>
		<pubDate>Mon, 07 Sep 2009 11:54:45 +0000</pubDate>
		<dc:creator>Drew</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Unit Testing]]></category>
		<category><![CDATA[Mocks]]></category>
		<category><![CDATA[Rhino]]></category>

		<guid isPermaLink="false">http://quickduck.com/blog/?p=138</guid>
		<description><![CDATA[I&#8217;m sure alot of you have come across a method that uses DateTime.Now at some point in your lives. Normally this is fine and nobody blinks an eyelid&#8230; until we need to unit test it. Consider the follow code: public class MyEntity { public DateTime Created { get; set; } } public class MyRepository { [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m sure alot of you have come across a method that uses DateTime.Now at some point in your lives. Normally this is fine and nobody blinks an eyelid&#8230; until we need to unit test it.</p>
<p>Consider the follow code:</p>
<pre class="brush: csharp;">public class MyEntity
 {
   public DateTime Created { get; set; }
 }

 public class MyRepository
 {
   public void UpdateMyEntity(MyEntity entity)
   {
     entity.Created = DateTime.Now;
   }
 }</pre>
<p>Unless you are one of one of those fancy pants with <a title="TypeMock" href="http://www.typemock.com/" target="_blank">TypeMock</a> and the ability to <a title="Typemock Isolator 5.3.1 can fake DateTime.Now" href="http://bloggingabout.net/blogs/dennis/archive/2009/06/03/typemock-isolator-5-3-1-can-fake-datetime-now.aspx" target="_blank">fake DateTime.Now</a>, the rest of use must look elsewhere for a solution. Here are three different ways to solve this.</p>
<p><strong>1. Wrap your DateTime calls with another class</strong></p>
<p><a title="Dealing with time in tests" href="http://ayende.com/Blog/archive/2008/07/07/Dealing-with-time-in-tests.aspx" target="_blank">Some people</a> prefer using a static &#8220;Clock&#8221; class to handle this which can be easily faked out during your unit testing.</p>
<pre class="brush: csharp;">
public static class Clock
{
    public static Func&lt;DateTime&gt; Now = () =&gt; DateTime.Now;
}
</pre>
<p>This approach, while decoupling your dependency on System.DateTime is a bit of overkill and requires all developers on the project to be aware of it and to use it.</p>
<p><strong>2.Use an Interface and your favourite Isolation Framework</strong><span> </span></p>
<pre class="brush: csharp;">
public interface IClock
{
  DateTime Now {get;}
}

public class SystemClock : IClock
{
  public DateTime Now { get { return DateTime.Now; } }
}
</pre>
<p>You can now use an isolation framework such as <a title="Rhino Mocks" href="http://ayende.com/projects/rhino-mocks.aspx" target="_blank">Rhino.Mocks</a> to fake the call to Now();</p>
<p><strong>3. Use a DateTime Comparer that accepts a range</strong></p>
<p>While not 100% accurate to the millisecond, this approach is my prefered approach as you don&#8217;t have to change to your code just to unit test it. No littering your code with IClock dependencies or using a delegate to return the current DateTime.Now (although one could argue that DateTime.Now <a title="Properties vs Methods" href="http://msdn.microsoft.com/en-us/library/bzwdh01d%28VS.71%29.aspx#cpconpropertyusageguidelinesanchor1" target="_blank">shouldn&#8217;t be a property</a> to begin with). This approach asserts that the Created property that is set in MyRepository.Update is within a certain range.</p>
<pre class="brush: csharp;">
 /// &lt;summary&gt;
 /// Helper class to compare 2 values are within a certain range.
 /// &lt;/summary&gt;
 public class DateComparer : IComparer&lt;DateTime&gt;
 {
 public TimeSpan MarginOfError { get; private set; }

 public DateComparer(TimeSpan marginOfError)
 {
   MarginOfError = marginOfError;
 }

  public int Compare(DateTime x, DateTime y)  // x = expected, y = actual
   {
     var margin = x - y;
     if (margin &lt;= MarginOfError)
       return 0;
     return new Comparer(CultureInfo.CurrentUICulture).Compare(x, y);
   }
 }
</pre>
<p>You can now write the follow test:</p>
<pre class="brush: csharp;">
public void MyRepository_UpdateTest()
 {
   var repository = new MyRepository();
   var entity = new MyEntity();
   repository.UpdateMyEntity(entity);
   var comparer = new DateComparer(new TimeSpan(0, 0, 0, 5));
   Assert.IsTrue(comparer.Compare(entity.Created, DateTime.Now) == 0);
 }
</pre>
]]></content:encoded>
			<wfw:commentRss>http://quickduck.com/blog/2009/09/07/unit-testing-datetime-now/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Unit Testing Expression Tree Equality</title>
		<link>http://quickduck.com/blog/2009/08/25/unit-testing-expression-tree-equality/</link>
		<comments>http://quickduck.com/blog/2009/08/25/unit-testing-expression-tree-equality/#comments</comments>
		<pubDate>Tue, 25 Aug 2009 03:31:02 +0000</pubDate>
		<dc:creator>Ben</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Unit Testing]]></category>
		<category><![CDATA[Comparison]]></category>
		<category><![CDATA[Equality]]></category>
		<category><![CDATA[Expression Trees]]></category>
		<category><![CDATA[Mocks]]></category>
		<category><![CDATA[Rhino]]></category>

		<guid isPermaLink="false">http://quickduck.com/blog/?p=131</guid>
		<description><![CDATA[Sometimes you need to test whether two expressions are the same. However when you do a simple AreEqual() test on two expressions that look the same you get a negative result. This method will fail [TestMethod] public void TestDoesNotWork() { Expression&#60;Func&#60;int, int&#62;&#62; expressionA = x =&#62; x + 1; Expression&#60;Func&#60;int, int&#62;&#62; expressionB = x =&#62; [...]]]></description>
			<content:encoded><![CDATA[<p>Sometimes you need to test whether two expressions are the same. However when you do a simple AreEqual() test on two expressions that look the same you get a negative result.</p>
<p><strong>This method will fail</strong></p>
<pre class="brush: csharp;">
[TestMethod]
public void TestDoesNotWork()
{
  Expression&lt;Func&lt;int, int&gt;&gt; expressionA = x =&gt; x + 1;
  Expression&lt;Func&lt;int, int&gt;&gt; expressionB = x =&gt; x + 1;

  Assert.AreEqual(expressionA, expressionB);
}
</pre>
<p>This looks like it should work however it doesn&#8217;t. This is because when using anonymous expressions/delegates the CLR does some magic behind the scene to add a method on the fly, creating a new instance for every anonymous expression/delegate.</p>
<p>So if you have two expressions that are syntactically the same but not the same reference the easiest way to ensure they are the same is to compile the expression and invoke it comparing the resultant value.</p>
<pre class="brush: csharp;">
[TestMethod]
public void TestDoesWork()
{
  Expression&lt;Func&lt;int, int&gt;&gt; expressionA = x =&gt; x + 1;
  Expression&lt;Func&lt;int, int&gt;&gt; expressionB = x =&gt; x + 1;

  Assert.AreEqual(expressionA.Compile().Invoke(3), expressionB.Compile().Invoke(3));
}
</pre>
<p>An alternate approach would be to de-construct each constituent part of the expression trees comparing each part as you go. This however is far more complex.</p>
<p>For a more real world example that involves using Rhino mocks and Expect calls please read on:</p>
<p><span id="more-131"></span></p>
<p>When using Rhino Mocks and setting up an Expect call on a method that takes an expression you will most likely find that the Expect assertion always fails.</p>
<p><strong> The class that will be mocked out.</strong><br />
This class will have the method on it that takes an expression.</p>
<pre class="brush: csharp;">
public class Repository
{
  public virtual void Get&lt;TEntity&gt;(Expression&lt;Func&lt;TEntity, bool&gt;&gt; whereCondition)
  {
        // Actual logic.
   }
}
</pre>
<p><strong>The class we are unit testing</strong></p>
<pre class="brush: csharp;">
public class UserManager
{
  public Repository Repo { get; set; }

  public void GetUserById(int id)
  {
    Repo.Get&lt;User&gt;(x =&gt; x.Id == id);
  }
}
</pre>
<p><strong>Supporting classes</strong></p>
<pre class="brush: csharp;">
public class User
{
  public int Id { get; set;  }
  public int Name { get; set; }
}
</pre>
<p>For our unit test we want to test that when we call the GetUserById() method on the UserManager class that we Expect the Repository.Get<TEntity>() method will be called with an expected expression value.</p>
<p><strong>Unit Test</strong></p>
<pre class="brush: csharp;">
[TestMethod]
public void Test()
{
  // Arrange
  UserManager manager = new UserManager { Repo = MockRepository.GenerateMock&lt;Repository&gt;() };
  manager.Repo.Expect(r =&gt; r.Get&lt;User&gt;(x =&gt; x.Id == 3));

  // Act
  manager.GetUserById(3);

  // Assert
  manager.Repo.VerifyAllExpectations();
}
</pre>
<p>This looks like it should work however it won&#8217;t.</p>
<p>So using the approach listed earlier we can test that the method with an expression is called with the correct value by compiling and invoking the expected expression and the actual expression that was called and comparing their values.</p>
<pre class="brush: csharp;">
[TestMethod]
public void TestExpressionCalled()
{
  // Arrange
  UserManager manager = new UserManager { Repo = MockRepository.GenerateMock&lt;Repository&gt;() };

  // Act
  manager.GetUserById(3);

  // Assert
  Expression&lt;Func&lt;User, bool&gt;&gt; expected = x =&gt; x.Id == 3;
  Expression&lt;Func&lt;User, bool&gt;&gt; actual = (Expression&lt;Func&lt;User, bool&gt;&gt;)manager.Repo.GetArgumentsForCallsMadeOn(r =&gt; r.Get&lt;User&gt;(null))[0][0];

  User user = new User { Id = 3 };
  Assert.AreEqual(expected.Compile().Invoke(user), actual.Compile().Invoke(user));
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://quickduck.com/blog/2009/08/25/unit-testing-expression-tree-equality/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Visual Studio 2008 &#8211; Shortcut Keys for running Unit Tests</title>
		<link>http://quickduck.com/blog/2008/10/30/visual-studio-2008-shortcut-keys-for-running-unit-tests/</link>
		<comments>http://quickduck.com/blog/2008/10/30/visual-studio-2008-shortcut-keys-for-running-unit-tests/#comments</comments>
		<pubDate>Thu, 30 Oct 2008 23:41:25 +0000</pubDate>
		<dc:creator>Ben</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://quickduck.com/blog/2008/10/30/visual-studio-2008-shortcut-keys-for-running-unit-tests/</guid>
		<description><![CDATA[Short Cut Keys to Run Tests: • Ctl R, T: Run Tests in Current context (namespace, class, and method – ie. Based on where your cursor is within a file it determines the tests to run) • Ctl R, C: Run Tests in Current Test Class • Ctl R, N: Run Tests in Current Namespace [...]]]></description>
			<content:encoded><![CDATA[<p>Short Cut Keys to Run Tests: </p>
<p>•         Ctl R, T: Run Tests in Current context (namespace, class, and method – ie. Based on where your cursor is within a file it determines the tests to run)<br />
•         Ctl R, C: Run Tests in Current Test Class<br />
•         Ctl R, N: Run Tests in Current Namespace<br />
•         Ctl R, S: Run All Tests in Solution<br />
•         Ctl R, D: Run the Tests in the Last Test Run<br />
•         Ctl R, F: Run the Failed Tests of the Last Test Run</p>
]]></content:encoded>
			<wfw:commentRss>http://quickduck.com/blog/2008/10/30/visual-studio-2008-shortcut-keys-for-running-unit-tests/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>I&#8217;m back</title>
		<link>http://quickduck.com/blog/2008/10/30/im-back/</link>
		<comments>http://quickduck.com/blog/2008/10/30/im-back/#comments</comments>
		<pubDate>Thu, 30 Oct 2008 07:06:02 +0000</pubDate>
		<dc:creator>Ben</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Asp.Net]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://quickduck.com/blog/2008/10/30/im-back/</guid>
		<description><![CDATA[After having 9 months off from doing .net (travelling, bumming and then a 3 month contract role as an architect in a coldfusion shop) I finally got myself a role doing what I love doing best &#8211; playing with .net and c#. In the last 4 weeks I&#8217;ve been researching and prototyping apps that use [...]]]></description>
			<content:encoded><![CDATA[<p>After having 9 months off from doing .net (travelling, bumming and then a 3 month contract role as an architect in a coldfusion shop) I finally got myself a role doing what I love doing best &#8211; playing with .net and c#.</p>
<p>In the last 4 weeks I&#8217;ve been researching and prototyping apps that use</p>
<ul>
<li>.net 3.5</li>
<li><a href="http://en.wikipedia.org/wiki/ADO.NET_Entity_Framework">ado.net entity framework</a></li>
<li><a href="http://msdn.microsoft.com/en-us/data/bb931106.aspx">ado.net data services</a> &#8211; including .net, ajax and silverlight client libraries</li>
<li><a href="http://silverlight.net">Silverlight 2.0</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/ms364077(VS.80).aspx">Visual Studio for Software Testers &#8211; Web Testing</a></li>
</ul>
<p>It&#8217;s been awesome to have the time and resources to touch across all of these technologies to enjoy their benefits and to loath the limitations.</p>
<p>All in all I reckon all of the technologies are a great addition to the .net stack and look forward to seeing them mature with each new release.</p>
<p>I look forward to documenting my findings as I find time to re-work them into don&#8217;t-give-away-IP examples.</p>
]]></content:encoded>
			<wfw:commentRss>http://quickduck.com/blog/2008/10/30/im-back/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Running VS Unit Tests stops IIS</title>
		<link>http://quickduck.com/blog/2008/10/24/running-vs-unit-tests-stops-iis/</link>
		<comments>http://quickduck.com/blog/2008/10/24/running-vs-unit-tests-stops-iis/#comments</comments>
		<pubDate>Fri, 24 Oct 2008 01:32:05 +0000</pubDate>
		<dc:creator>Ben</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://quickduck.com/blog/2008/10/24/running-vs-unit-tests-stops-iis/</guid>
		<description><![CDATA[We recently ran into this problem where we discovered that running our VS unit tests was killing IIS. As with all problems, I like to break things down to the simplest scenario I can find and as such created a brand new unit test that did nothing to see if that still caused the problem [...]]]></description>
			<content:encoded><![CDATA[<p>We recently ran into this problem where we discovered that running our VS unit tests was killing IIS.</p>
<p>As with all problems, I like to break things down to the simplest scenario I can find and as such created a brand new unit test that did nothing to see if that still caused the problem &#8211; it did.</p>
<p>So knowing that it had nothing to do with any code that was web dependent I knew to start looking elsewhere. </p>
<p>Turns out the problem is caused by enabling code coverage on projects that are dependent on IIS &#8211; e.g. a web project.</p>
<p><img src='http://quickduck.com/blog/wp-content/uploads/2008/10/codecoverage.jpg' alt='Visual Studio Code Coverage' width="500" /></p>
<p>The simple solution is to disable code coverage on the problem-causing project <strong>OR</strong> alternately remove the dependency on IIS by modifying it to  use the in-built Cassini web server.</p>
]]></content:encoded>
			<wfw:commentRss>http://quickduck.com/blog/2008/10/24/running-vs-unit-tests-stops-iis/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Unit testing data access code</title>
		<link>http://quickduck.com/blog/2008/02/19/unit-testing-data-access-code/</link>
		<comments>http://quickduck.com/blog/2008/02/19/unit-testing-data-access-code/#comments</comments>
		<pubDate>Tue, 19 Feb 2008 09:00:13 +0000</pubDate>
		<dc:creator>Ben</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://quickduck.com/blog/2008/02/19/unit-testing-data-access-code/</guid>
		<description><![CDATA[A classic problem to unit testing code that modifies the underlying data in the database tables is that you need to find a way to revert back to the original database state so that the tests can be run over and over again. Using the transaction capabilities provided with the .Net 2.0 framework and a [...]]]></description>
			<content:encoded><![CDATA[<p>A classic problem to unit testing code that modifies the underlying data in the database tables is that you need to find a way to revert back to the original database state so that the tests can be run over and over again.</p>
<p>Using the transaction capabilities provided with the .Net 2.0 framework and a unit testing framework you can achieve this easily. </p>
<p>The process:</p>
<ul>
<li>Create a new transaction before each test.</li>
<li>Dispose (Rollback) the transaction after each test.</li>
</ul>
<pre><code>

    using System.Data;

    [TestClass]
    public class DataProviderTest {

        private readonly DataProvider _dp = new DataProvider();
        private TransactionScope _transactionScope;

        [TestInitialize]
        public void TestInitialize() {
            _transactionScope = new TransactionScope();
        }

        [TestCleanup]
        public void TestCleanup() {
            _transactionScope.Dispose();
        }

        [TestMethod]
        public void InsertTest()
        {
            // modify the database
            ...
        }
    }
</code></pre>
]]></content:encoded>
			<wfw:commentRss>http://quickduck.com/blog/2008/02/19/unit-testing-data-access-code/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Unit Testing, Mocking and Dependency Injection</title>
		<link>http://quickduck.com/blog/2008/02/18/unit-testing-mocking-and-dependency-injection/</link>
		<comments>http://quickduck.com/blog/2008/02/18/unit-testing-mocking-and-dependency-injection/#comments</comments>
		<pubDate>Mon, 18 Feb 2008 10:57:47 +0000</pubDate>
		<dc:creator>Ben</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://quickduck.com/blog/2008/02/18/unit-testing-mocking-and-dependency-injection/</guid>
		<description><![CDATA[The following article tries to outline an approach for unit/integration testing using the Visual Studio Team System testing framework. The article is long, but hopefully worth the read. Defining terminology Unit Testing vs. Integration Testing vs. System Testing The following is taken from our good friends at Wikipedia. Unit testing is a procedure used to [...]]]></description>
			<content:encoded><![CDATA[<p>The following article tries to outline an approach for unit/integration testing using the Visual Studio Team System testing framework.</p>
<p>The article is long, but hopefully worth the read.</p>
<h2>Defining terminology</h2>
<h3>Unit Testing vs. Integration Testing vs. System Testing</h3>
<p>The following is taken from our good friends at Wikipedia.</p>
<blockquote><p>Unit testing is a procedure used to validate that individual units of source code are working properly. A unit is the smallest testable part of an application, in OO the smallest unit is a method; which may belong to a base/super class, abstract class or derived/child class.</p>
<p>Ideally, each test case is independent from the others; mock objects and test harnesses can be used to assist testing a module in isolation. Unit testing is typically done by developers and not by end-users.</p></blockquote>
<blockquote><p>Integration testing  is the phase of software testing in which individual software modules are combined and tested as a group. It follows unit testing and precedes system testing.</p>
<p>Integration testing takes as its input modules that have been unit tested, groups them in larger aggregates, applies tests defined in an integration test plan to those aggregates, and delivers as its output the integrated system ready for system testing.</p></blockquote>
<blockquote><p>System testing of software is testing conducted on a complete, integrated system to evaluate the system&#8217;s compliance with its specified requirements. System testing falls within the scope of black box testing, and as such, should require no knowledge of the inner design of the code or logic. [1]</p>
<p>As a rule, system testing takes, as its input, all of the &#8220;integrated&#8221; software components that have successfully passed integration testing and also the software system itself integrated with any applicable hardware system(s). The purpose of integration testing is to detect any inconsistencies between the software units that are integrated together (called assemblages) or between any of the assemblages and the hardware. System testing is a more limiting type of testing; it seeks to detect defects both within the &#8220;inter-assemblages&#8221; and also within the system as a whole.</p></blockquote>
<h3>Whitebox Testing (goes hand in hand with Unit Testing)</h3>
<p>Unit Tests typically are usually written with intimate knowledge of the unit being tested – which allows all paths within the unit to be covered by the tests ensuring complete code coverage.</p>
<p>Mocking frameworks such as Rhino provided utilities to help assert code paths are tested.</p>
<p>For more information, see <a href="http://en.wikipedia.org/wiki/Whitebox_testing">http://en.wikipedia.org/wiki/Whitebox_testing</a></p>
<h3>Dependency Injection</h3>
<p>Dependency injection aims to solve a particular problem in designing and constructing data structures dependent on other pieces of code, in a way that minimizes the coupling between them.</p>
<p>Dependency injection aids in helping to test particular units of code, substituting in your own versions of the dependency, removing the need to test the dependent code.</p>
<p>For more information, see<br />
<a href="http://www.ddj.com/development-tools/185300375;jsessionid=ET54EFB24JNO0QSNDLRSKH0CJUNN2JVN?_requestid=734131">Dependency Injection &amp; Testable Objects</a><br />
<a href="http://www.martinfowler.com/articles/injection.html#FormsOfDependencyInjection">Inversion of Control Containers and the Dependency Injection pattern</a></p>
<h3>Mocking</h3>
<p>Using the Dependency Injection pattern doesn’t require the use of a mocking framework to by-pass dependencies. It’s entirely plausible to create your own implementations and pass through. This however, will require a lot of time writing the code and cause your projects to bloat. A mocking framework should provide the facility to create dependency implementations (mocks) dynamically, taking the hard work away from the unit tester. The framework also, should provide functionality to help you assert that the mocked objects are used the way you expect them to behave.</p>
<p>There are various mocking frameworks out in the wild, I personally have used NMock and Rhino Mock. My experience with both favours Rhino Mock for flexibility, ease of use and performance. Type.Mock seems to get a lot of high praise too.</p>
<p>For more information, see:<br />
<a href="http://www.ayende.com/Wiki/(S(nob0ep45irtrqcbrboltmf55))/Rhino+Mocks+Introduction.ashx">Rhino Mocks &#8211; Introduction</a><br />
<a href="http://www.ayende.com/Wiki/(S(nob0ep45irtrqcbrboltmf55))/Default.aspx?Page=Rhino+Mocks+Documentation">Rhino Mocks &#8211; Documentation</a></p>
<h3>Time for a Code Walkthrough</h3>
<p>We have a CustomerServices class that provides business functions for a Customer entity. The CustomerServices class uses a CustomerDataAccess object to persist/read information from a database. Therefore, the CustomerServices class has a dependency on the CustomerDataAcess class.</p>
<p>A first cut of the two classes might look like this:</p>
<pre class="brush: csharp;">
public class CustomerDataAccess : ICustomerDataAccess {

        public void InsertCustomer(string name)
        {
            // long running dependency
            Thread.Sleep(10000); // 10 seconds.
        }
}

public class CustomerServices {

  public void AddCustomer(Customer customer){
            new CustomerDataAccess().InsertCustomer(customer.Name);
  }

}
</pre>
<p>As you can see when we write a unit test for the CustomerServices.AddCustomer method it will make a call to the CustomerDataAccess class and take 100 seconds to complete.</p>
<pre class="brush: csharp;">
[TestMethod]
public void TestAddCustomer () {

  Customer customer = new Customer();
  customer.Name = 'Ben';

  new CustomerServices().AddCustomer(customer);

 // To verify the test worked, a database lookup would be required.

}
</pre>
<p>Now we should already have appropriate unit tests for the CustomerDataAccess.InsertCustomer() method, so in our CustomerServices tests we can remove this dependency as it has already been tested.</p>
<p>Let’s re-write the CustomerServices class to utilize the dependency injection pattern:</p>
<pre class="brush: csharp;">
public class CustomerServices {
        private readonly ICustomerDataAccess _customerDataAccess;
        public CustomerServices() : this (new CustomerDataAccess()) {}

        // using internal prevents the constructor from being publicly
        // available to other assemblies.
        internal CustomerServices(ICustomerDataAccess customerDataAccess)
        {
            _customerDataAccess = customerDataAccess;
        }

        public void AddCustomer(Customer customer) {
             _customerDataAccess.InsertCustomer(customer.Name);
        }
}

//NOTE:  To allow our unit testing project to access the internal members of the project we’re testing, an attribute is added to the AssemblyInfo.cs file.

#if DEBUG
  [assembly: InternalsVisibleTo(&quot;CustomerServiceTests &quot;)]
#endif
</pre>
<p>Now we have the ability to insert our own CustomerDataAccess object, we’ll create our own mock object and use it to remove the dependency – this is for illustration purposes only.</p>
<pre class="brush: csharp;">
public class MockCustomerDataAccess : ICustomerDataAccess {

      private int _insertCustomerCount = 0;

      public void InsertCustomer(string name) {
            _insertCustomerCount++;
      }

      public int InsertCustomerCount {
            get { return _insertCustomerCount; }
      }
}

[TestMethod]
public void TestAddCustomerWithStaticMock() {
      Customer customer = new Customer();
      customer.Name = 'Ben';

      ICustomerDataAccess mock = new MockCustomerDataAccess();

      CustomerServices _customerServices = new CustomerServices(mock);
      _customerServices.AddCustomer(customer);

      Assert.AreEqual(1, mock.InsertCustomerCount);
}
</pre>
<p>As you can see here, creating our own mocks and keeping metrics will become tiresome and mean code bloat – especially as you might need many instances of the same interface for differing code paths etc.</p>
<p>Don’t worry though there is a way forward – using a mocking framework like Rhino Mocks.</p>
<p>[TestMethod]<br />
public void TestAddCustomerWithDynamicMock() {<br />
// create the Rhino mock repository<br />
_mockRepository = new MockRepository();</p>
<p>// get a dynamic instance of the ICustomerDataAccess interface<br />
_dynamicMock = (ICustomerDataAccess) _mockRepository.DynamicMock(typeof(ICustomerDataAccess));<br />
_customerServices = new CustomerServices(_dynamicMock);</p>
<p>// Expect the CustomerDataAccess.InsertCustomer method to be called exactly once.<br />
_dynamicMock.InsertCustomer(null);</p>
<p>LastCall.IgnoreArguments().Repeat.Once();<br />
_mockRepository.ReplayAll();</p>
<p>Customer customer = new Customer();<br />
customer.Name = &#8216;Ben&#8217;;<br />
_customerServices.AddCustomer(customer);</p>
<p>// ensure the asserts are correct<br />
_mockRepository.VerifyAll();<br />
}</p>
<p>Using Rhino Mocks we don’t need to create hard-coded mock objects for our tests and we get built in metric checking and a whole lot more – all for free.</p>
<h3>What to Test?</h3>
<p>1.       Any non-trivial piece of code.<br />
2.       All code is non-trivial.<br />
3.       Then again, something’s just aren’t worth your time.<br />
4.       Confused?</p>
<p>For every method that has some meat on it, there should be [TestMethod]s that test all execution paths.<br />
Public properties that are just get/set would be a situation of overkill.</p>
<p>The VSTS code coverage tool is excellent for seeing what you’ve tested and what’s been missed.</p>
<p>To use the VSTS code coverage tool, open up VS 2005 and edit the selected test configuration run:</p>
<p><a href="http://quickduck.com/blog/wp-content/uploads/2008/02/vsts-codecoverage-1.JPG"><img src="http://quickduck.com/blog/wp-content/uploads/2008/02/vsts-codecoverage-1.JPG" alt="Enabling Code Coverage" width="550px" /></a><br />
Click for Full Size Image</p>
<p>Then select the assemblies you wish to monitor:</p>
<p><img src="http://quickduck.com/blog/wp-content/uploads/2008/02/vsts-codecoverage-2.JPG" alt="Select Assemblies" /></p>
<p>Then all you have to do is run your tests (but not in debug mode) for it to calculate the metrics. Once finished open up the Code Coverage Window and inspect the results.</p>
<p><a href="http://quickduck.com/blog/wp-content/uploads/2008/02/vsts-codecoverage-3.JPG"><img src="http://quickduck.com/blog/wp-content/uploads/2008/02/vsts-codecoverage-3.JPG" alt="Code Coverage Results" width="550px" /></a><br />
Click for Full Size Image</p>
<h3>What about Integration Testing?</h3>
<p>We can still use the VSTS unit testing framework to write integration tests. The difference though, comes from the point of view that the test methods will not substitute in mocks for the dependencies, allowing the tests to run end-to-end testing a module/function of code right through.</p>
]]></content:encoded>
			<wfw:commentRss>http://quickduck.com/blog/2008/02/18/unit-testing-mocking-and-dependency-injection/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
	</channel>
</rss>
