<?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>Arrange Act Assert &#187; Test Driven Development (TDD)</title>
	<atom:link href="http://www.arrangeactassert.com/category/test-driven-development-tdd/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.arrangeactassert.com</link>
	<description>Jag Reehal on Agile Development, ASP.NET MVC, Silverlight and all manner of good stuff</description>
	<lastBuildDate>Wed, 28 Jul 2010 06:22:14 +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>Excellent FREE resource for learning Domain Driven Design</title>
		<link>http://www.arrangeactassert.com/excellent-free-resource-for-learning-domain-driven-design/</link>
		<comments>http://www.arrangeactassert.com/excellent-free-resource-for-learning-domain-driven-design/#comments</comments>
		<pubDate>Mon, 02 Nov 2009 11:09:35 +0000</pubDate>
		<dc:creator>Jag Reehal</dc:creator>
				<category><![CDATA[Agile]]></category>
		<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[Extreme Programming (XP)]]></category>
		<category><![CDATA[Test Driven Development (TDD)]]></category>

		<guid isPermaLink="false">http://www.arrangeactassert.com/?p=407</guid>
		<description><![CDATA[If you asked developers what books they should read, most would (or should) include Domain Driven Design by Eric Evans. Why is it important? The patterns and practices outlined in this book will help you develop more successful software solutions. How? Eric Evans shows how you can improve communication with your customer (by doing things [...]]]></description>
			<content:encoded><![CDATA[<p>If you asked developers what books they should read, most would (or should) include <a href="http://www.amazon.com/Domain-Driven-Design-Tackling-Complexity-Software/dp/0321125215">Domain Driven Design by Eric Evans</a>.</p>
<p><strong>Why is it important?</strong></p>
<p>The patterns and practices outlined in this book will help you develop more successful software solutions.  </p>
<p><strong>How?</strong></p>
<p>Eric Evans shows how you can improve communication with your customer (by doing things like developing a ubiquitous language), implement agile practices and create maintainable solutions which follow good software development principles.  </p>
<p><em>One of common criticisms of the book is that ‘it does go on a bit’.</em></p>
<p>The good news is that the folks over at <a href="http://www.infoq.com">InfoQ</a> have come up with ‘<a href="http://www.infoq.com/minibooks/domain-driven-design-quickly">Domain Driven Design Quickly</a>’ which summarizes what Domain Driven Design is about.</p>
<p>The even better news is that it’s FREE if you register with <a href="http://www.infoq.com">InfoQ</a>, which is no bad thing because it&#8217;s a fantastic resource with videos, presentations and some very good articles. </p>
]]></content:encoded>
			<wfw:commentRss>http://www.arrangeactassert.com/excellent-free-resource-for-learning-domain-driven-design/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How AutoMocking and RhinoMocks could change how you write unit tests</title>
		<link>http://www.arrangeactassert.com/how-automocking-and-rhinomocks-could-change-how-you-write-unit-tests/</link>
		<comments>http://www.arrangeactassert.com/how-automocking-and-rhinomocks-could-change-how-you-write-unit-tests/#comments</comments>
		<pubDate>Mon, 10 Aug 2009 23:38:43 +0000</pubDate>
		<dc:creator>Jag Reehal</dc:creator>
				<category><![CDATA[Automocking]]></category>
		<category><![CDATA[RhinoMocks]]></category>
		<category><![CDATA[Test Driven Development (TDD)]]></category>
		<category><![CDATA[Unit tests]]></category>

		<guid isPermaLink="false">http://www.arrangeactassert.com/?p=208</guid>
		<description><![CDATA[One of the biggest headaches when it comes to unit tests and test driven development is having to modify existing tests when a constructor changes even if they don&#8217;t need to use the newly injected object. For an introduction to RhinoMocks check out How to write better unit tests using RhinoMocks and stubs. You might [...]]]></description>
			<content:encoded><![CDATA[<p>One of the biggest headaches when it comes to unit tests and test driven development is having to modify existing tests when a constructor changes even if they don&#8217;t need to use the newly injected object.</p>
<p>For an introduction to RhinoMocks check out <a href="http://www.arrangeactassert.com/how-to-write-better-unit-tests-using-rhinomocks-and-stubs/">How to write better unit tests using RhinoMocks and stubs</a>.</p>
<p>You might fix the problem by passing in null or writing a line such as the one below</p>
<pre class="brush: csharp; gutter: false; toolbar: true;">
var somethingYouWantToStub = MockRepository.Stub&lt;AnInterface&gt;();
</pre>
<p>and it to the ever growing lines of creating stub objects.</p>
<blockquote><p><strong>Anouncer:</strong> What if there was a way to write your unit tests where you didn&#8217;t have to manually stub out everything up front and existing tests could still run if a constructor changes?  Well there is!<br />
<strong>Action:</strong> Automocking container enters from stage door left.</p></blockquote>
<p>The code below shows two unit tests for a full name creator which calls various providers to get a first and last name and then concatenates together. Look out for:</p>
<ul>
<li>how in the first test (&#8220;Can_Create_FullName&#8221;) each name provider has to be stubbed out and then added in the constructor for the FullName creator.</li>
</ul>
<ul>
<li>how in the second test (&#8220;Can_Create_FullName_Using_AutoMockingContainer&#8221;) an auto mocking container is used to create the FullName creator.</li>
<li>The use of the <strong>arrange</strong>, <strong>act</strong> and <strong>assert</strong> to make the tests easier to follow</li>
</ul>
<pre class="brush: csharp; highlight: [43,44,46,66]; toolbar: true; wrap-lines: false;">
using System;
using NUnit.Framework;
using Rhino.Mocks;

namespace AutoMockingContainer
{
    public interface IFirstNameProvider
    {
        string GetFirstName();
    }

    public interface ILastNameProvider
    {
        string GetLastName();
    }

    public class FullNameCreator
    {
        private readonly IFirstNameProvider _firstNameProvider;
        private readonly ILastNameProvider _lastNameProvider;

        public FullNameCreator(IFirstNameProvider firstNameProvider, ILastNameProvider lastNameProvider)
        {
            _firstNameProvider = firstNameProvider;
            _lastNameProvider = lastNameProvider;
        }

        public string Concatenate()
        {
            var firstName = _firstNameProvider.GetFirstName(); ;
            var lastName = _lastNameProvider.GetLastName();
            return String.Format(&quot;{0} {1}&quot;, firstName, lastName);
        }
    }

    [TestFixture]
    public class FullNameCreatorTests
    {
        [Test]
        public void Can_Create_FullName()
        {
            // Arrange
            var firstNameProvider = MockRepository.GenerateStub&lt;IFirstNameProvider&gt;();
            var lastNameProvider = MockRepository.GenerateStub&lt;ILastNameProvider&gt;();

            FullNameCreator fullNameCreator = new FullNameCreator(firstNameProvider, lastNameProvider);

            firstNameProvider.Stub(n =&gt; n.GetFirstName()).Return(&quot;William&quot;);
            lastNameProvider.Stub(n =&gt; n.GetLastName()).Return(&quot;Clinton&quot;);

            // Act
            var result = fullNameCreator.Concatenate();

            // Assert
            Assert.That(result, Is.EqualTo(&quot;William Clinton&quot;));
        }

        [Test]
        public void Can_Create_FullName_Using_AutoMockingContainer()
        {
            // Arrange
            var mocks = new MockRepository();
            var container = new Rhino.Testing.AutoMocking.AutoMockingContainer(mocks);
            container.Initialize();

            FullNameCreator fullNameCreator = container.Create&lt;FullNameCreator&gt;();

            using (mocks.Record())
            {
                container.Resolve&lt;IFirstNameProvider&gt;().Stub(r =&gt; r.GetFirstName()).Return(&quot;William&quot;);
                container.Resolve&lt;ILastNameProvider&gt;().Stub(r =&gt; r.GetLastName()).Return(&quot;Clinton&quot;);
            }

            // Act
            string result;
            using (mocks.Playback())
            {
                result = fullNameCreator.Concatenate();
            }

            // Assert
            Assert.That(result, Is.EqualTo(&quot;William Clinton&quot;));
        }
    }
}
</pre>
<p>In the second test we have to apply RhinoMocks record-playback pattern.  At this point there is no clear winner.</p>
<p>So now what if client/customer creates the following user story:</p>
<blockquote><p><strong>As a</strong> account administrator<br />
<strong>I want</strong> to be able to see the first, middle and last name when I retrive customer information<br />
<strong>So that</strong> I know their full name.</p></blockquote>
<p>or for you behavior driven development fans</p>
<blockquote><p><strong>Given</strong> a customers&#8217; first name is &#8220;William&#8221;, second name is &#8220;Jefferson&#8221; and third name is &#8220;Clinton&#8221;<br />
<strong>When</strong> a user wants to retrieve their full name<br />
<strong>Then</strong> &#8220;William Jefferson Clinton&#8221; should be returned</p></blockquote>
<p>Doing this the test driven way, we can assume we will using a MiddleNameProvider and calling a method called &#8216;GetMiddleName&#8217;.</p>
<p>Without auto mocking it&#8217;s a case of creating a stubbed object, changing the constructor for the FullNameCreator and then setting up the stubbed object.  <strong>With auto mocking it&#8217;s a one line code change.</strong></p>
<pre class="brush: csharp; highlight: [12,18,41]; wrap-lines: false;">
[TestFixture]
public class FullNameCreatorTests
{
    [TestFixture]
    public class FullNameCreatorTests
    {
        [Test]
        public void Can_Create_FullName()
        {
            // Arrange
            var firstNameProvider = MockRepository.GenerateStub&lt;IFirstNameProvider&gt;();
            var middleNameProvider = MockRepository.GenerateStub&lt;IMiddleNameProvider&gt;();
            var lastNameProvider = MockRepository.GenerateStub&lt;ILastNameProvider&gt;();

            FullNameCreator fullNameCreator = new FullNameCreator(firstNameProvider, middleNameProvider, lastNameProvider);

            firstNameProvider.Stub(n =&gt; n.GetFirstName()).Return(&quot;William&quot;);
            middleNameProvider.Stub(n =&gt; n.GetMiddleName()).Return(&quot;Jefferson&quot;);
            lastNameProvider.Stub(n =&gt; n.GetLastName()).Return(&quot;Clinton&quot;);

            // Act
            var result = fullNameCreator.Concatenate();

            // Assert
            Assert.That(result, Is.EqualTo(&quot;William Jefferson Clinton&quot;));
        }

        [Test]
        public void Can_Create_FullName_Using_AutoMockingContainer()
        {
            // Arrange
            var mocks = new MockRepository();
            var container = new Rhino.Testing.AutoMocking.AutoMockingContainer(mocks);
            container.Initialize();

            FullNameCreator fullNameCreator = container.Create&lt;FullNameCreator&gt;();

            using (mocks.Record())
            {
                container.Resolve&lt;IFirstNameProvider&gt;().Stub(r =&gt; r.GetFirstName()).Return(&quot;William&quot;);
                container.Resolve&lt;IMiddleNameProvider&gt;().Stub(r =&gt; r.GetMiddleName()).Return(&quot;Jefferson&quot;);
                container.Resolve&lt;ILastNameProvider&gt;().Stub(r =&gt; r.GetLastName()).Return(&quot;Clinton&quot;);
            }

            // Act
            string result;
            using (mocks.Playback())
            {
                result = fullNameCreator.Concatenate();
            }

            // Assert
            Assert.That(result, Is.EqualTo(&quot;William Jefferson Clinton&quot;));
        }
    }
}
</pre>
<p>It&#8217;s not only a reduction in the amount of code we have to write.  What you have to remember here is that  any changes to the constructor for the FullNameCreator will break the non-auto mocked unit test.</p>
<p>Here&#8217;s an example to show what I mean.  The customer/client decides they want to add logging.  This has nothing to do with our expected outcomes.  The code for the ILogger and changes to the FullNameCreator are shown below.</p>
<pre class="brush: csharp; highlight: [11,13,18,23,25,27,29]; wrap-lines: false;">
public interface ILogger
{
    void Log(string message);
}

public class FullNameCreator
{
    private readonly IFirstNameProvider _firstNameProvider;
    private readonly IMiddleNameProvider _middleNameProvider;
    private readonly ILastNameProvider _lastNameProvider;
    private readonly ILogger _logger;

    public FullNameCreator(IFirstNameProvider firstNameProvider, IMiddleNameProvider middleNameProvider, ILastNameProvider lastNameProvider, ILogger logger)
    {
        _firstNameProvider = firstNameProvider;
        _middleNameProvider = middleNameProvider;
        _lastNameProvider = lastNameProvider;
        _logger = logger;
    }

    public string Calculate()
    {
        _logger.Log(&quot;Getting the first name&quot;);
        var firstName = _firstNameProvider.GetFirstName();
        _logger.Log(&quot;Getting the middle name&quot;);
        var middleName = _middleNameProvider.GetMiddleName();
        _logger.Log(&quot;Getting the last name&quot;);
        var lastName = _lastNameProvider.GetLastName();
        return String.Format(&quot;{0} {1} {2}&quot;, firstName, middleName, lastName);
    }
}
</pre>
<p>This solution will not build because a unit test needs amending&#8230;  no prizes for guessing which one!</p>
<p><img src="http://www.arrangeactassert.com/wp-content/uploads/2009/08/AutoMockingContainer.jpg" alt="AutoMockingContainer.FullNameCreator does not contain a constructor that takes 3 arguments" width="100%" /></p>
<p>At this point we can&#8217;t even just pass null, because the code will try and call the Log method.  We have to create a stub object and pass it in.</p>
<p><strong>For the unit test using the auto mocking container the addition of the logger made no difference whatsoever.</strong></p>
<p>So am I writing all my tests using the auto mocking container?  Sort of.  When I&#8217;m doing test driven development I don&#8217;t like using the record playback syntax, I find it slows me down and takes my focus away from writing good unit tests.  However when I have reached a point where the user story is complete and refactoring begins, I would adopt the auto mocking approach.</p>
<p>The other problem is that in order to use the automocking container I have to reference five libraries which is a bit of a pain and could lead to a whole host of version nightmares&#8230; more on that in another post.</p>
<p>The code is available at <a href="http://code.google.com/p/arrangeactassert/">http://code.google.com/p/arrangeactassert/</a>. The solution is in the AutoMockingContainer folder.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.arrangeactassert.com/how-automocking-and-rhinomocks-could-change-how-you-write-unit-tests/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Did you know NUnit 2.5 is out?</title>
		<link>http://www.arrangeactassert.com/did-you-know-nunit-2-5-is-out/</link>
		<comments>http://www.arrangeactassert.com/did-you-know-nunit-2-5-is-out/#comments</comments>
		<pubDate>Tue, 23 Jun 2009 20:48:44 +0000</pubDate>
		<dc:creator>Jag Reehal</dc:creator>
				<category><![CDATA[Test Driven Development (TDD)]]></category>
		<category><![CDATA[Unit tests]]></category>

		<guid isPermaLink="false">http://arrangeactassert.wordpress.com/?p=92</guid>
		<description><![CDATA[Go to http://www.nunit.org/index.php?p=download to get it! It has awesome new features such as data driven tests! See http://nunit.com/blogs/?p=66 for more information. That means I can now do the things only possible before in other frameworks such as MbUnit and xUnit. Just be aware if you write your asserts like this Assert.That(1, Is.EqualTo(1)); &#8216;Is&#8217; is now [...]]]></description>
			<content:encoded><![CDATA[<p>Go to <a href="http://www.nunit.org/index.php?p=download">http://www.nunit.org/index.php?p=download</a> to get it!</p>
<p>It has awesome new features such as <a href="http://nunit.com/blogs/?p=66">data driven tests!  See http://nunit.com/blogs/?p=66</a> for more information.  That means I can now do the things only possible before in other frameworks such as <a href="http://www.mbunit.com">MbUnit</a> and <a href="http://www.codeplex.com/xunit">xUnit</a>.</p>
<p>Just be aware if you write your asserts like this</p>
<pre class="brush: csharp; gutter: false;">
Assert.That(1, Is.EqualTo(1));
</pre>
<p>&#8216;Is&#8217; is now a member of &#8216;NUnit.Framework&#8217; and not &#8216;NUnit.Framework.SyntaxHelpers&#8217; so you will have to remove the using statement that looks like this</p>
<pre class="brush: csharp; gutter: false;">
using NUnit.Framework.SyntaxHelpers;
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.arrangeactassert.com/did-you-know-nunit-2-5-is-out/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>How to write better unit tests using RhinoMocks and mocking</title>
		<link>http://www.arrangeactassert.com/how-to-write-better-unit-tests-using-rhinomocks-and-mocking/</link>
		<comments>http://www.arrangeactassert.com/how-to-write-better-unit-tests-using-rhinomocks-and-mocking/#comments</comments>
		<pubDate>Tue, 23 Jun 2009 20:25:02 +0000</pubDate>
		<dc:creator>Jag Reehal</dc:creator>
				<category><![CDATA[RhinoMocks]]></category>
		<category><![CDATA[Test Driven Development (TDD)]]></category>
		<category><![CDATA[Unit tests]]></category>

		<guid isPermaLink="false">http://arrangeactassert.wordpress.com/?p=84</guid>
		<description><![CDATA[In the last post we saw how the use of stub functionality of a mocking framework within a unit test. The aim of this post is build upon this and look at mocking functionality. If you find yourself having to create a class to hold &#8216;state&#8217;, like this using System.Collections.Generic; namespace GettingStartedWithRhinoMocks { public class [...]]]></description>
			<content:encoded><![CDATA[<p>In the <a href="http://www.arrangeactassert.com/how-to-write-better-unit-tests-using-rhinomocks-and-stubs/">last post</a> we saw how the use of stub functionality of a mocking framework within a unit test.  The aim of this post is build upon this and look at mocking functionality.</p>
<p>If you find yourself having to create a class to hold &#8216;state&#8217;, like this</p>
<pre class="brush: csharp; toolbar: true; wrap-lines: false;">
using System.Collections.Generic;

namespace GettingStartedWithRhinoMocks
{
    public class TestLogger : ILogger
    {
        public TestLogger()
        {
            Messages = new List&lt;string&gt;();
        }

        public IList&lt;string&gt; Messages { get; private set; }

        public void LogError(string errorMessage)
        {
            Messages.Add(errorMessage);
        }
    }
}
</pre>
<p>And your test looks something like this</p>
<pre class="brush: csharp; toolbar: true; wrap-lines: false;">
[Test]
public void Will_Write_To_Log_If_Customer_Fails_Validation_When_Adding_Customer_Using_Stub()
{
	// Arrange
	ICustomerValidator customerValidator = MockRepository.GenerateStub&lt;icustomerValidator&gt;();
	var testLogger = new TestLogger();

	var customerService = new CustomerService(customerValidator, testLogger);

	customerValidator.Stub(c =&gt; c.IsValid(null))
		.IgnoreArguments() // Use this because the argument is not important
		.Throw(new ArgumentException(CustomerValidator.CUSTOMER_NAME_ERROR_MESSAGE));  // This will simulate the throwing of an exception

	//Act
	customerService.AddCustomer(new Customer());

	//Assert
	Assert.That(testLogger.Messages.Count, Is.EqualTo(1));
}
</pre>
<p>You can eliminate the need for the TestLogger class by using a mock like this</p>
<pre class="brush: csharp; toolbar: true; wrap-lines: false;">
[Test]
public void Will_Write_To_Log_If_Customer_Fails_Validation_When_Adding_Customer_Using_Stub_And_Mock()
{
	// Arrange
	ICustomerValidator customerValidator = MockRepository.GenerateStub&lt;icustomerValidator&gt;();
	ILogger logger = MockRepository.GenerateMock&lt;ilogger&gt;();

	var customerService = new CustomerService(customerValidator, logger);

	customerValidator.Stub(c =&gt; c.IsValid(null))
		  .IgnoreArguments() // Use this because the argument is not important
		  .Throw(new ArgumentException(CustomerValidator.CUSTOMER_NAME_ERROR_MESSAGE));  // This will simulate the throwing of an exception

	// Act
	customerService.AddCustomer(new Customer());

	// Assert
	logger.AssertWasCalled(l =&gt; l.LogError(CustomerValidator.CUSTOMER_NAME_ERROR_MESSAGE));
}
</pre>
<p>The difference is how we assert the exception was logged.  The extension method &#8216;AssertWasCalled&#8217; ensures that the &#8216;LogError&#8217; method of a logger was called with the correct error message.</p>
<p>If we changed the assert to this</p>
<pre class="brush: csharp; gutter: false; toolbar: true; wrap-lines: false;">
//Assert
logger.AssertWasCalled(l =&gt; l.LogError(&quot;Oh no&quot;));
</pre>
<p>The test would fail and RhinoMocks would throw the following exception</p>
<pre class="brush: csharp; gutter: false; toolbar: true; wrap-lines: false;">
Rhino.Mocks.Exceptions.ExpectationViolationException: ILogger.LogError(&quot;Oh no&quot;); Expected #1, Actual #0.
</pre>
<p>So over the two posts we have refactored the unit tests from not using a mocking framework to using both stub and mock functionality of a mocking framework and still have unit tests which are easy to read and maintain.</p>
<p><a href="http://martinfowler.com/articles/mocksArentStubs.html">Martin Fowlers&#8217; article </a> discusses the two styles testing.  I recommend you choose which is better on a test by test basis.</p>
<p>The code is available at <a href="http://code.google.com/p/arrangeactassert/">http://code.google.com/p/arrangeactassert/</a>.  The solution is in the GettingStartedWithRhinoMocks folder.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.arrangeactassert.com/how-to-write-better-unit-tests-using-rhinomocks-and-mocking/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>How to write better unit tests using RhinoMocks and stubs</title>
		<link>http://www.arrangeactassert.com/how-to-write-better-unit-tests-using-rhinomocks-and-stubs/</link>
		<comments>http://www.arrangeactassert.com/how-to-write-better-unit-tests-using-rhinomocks-and-stubs/#comments</comments>
		<pubDate>Thu, 04 Jun 2009 00:08:48 +0000</pubDate>
		<dc:creator>Jag Reehal</dc:creator>
				<category><![CDATA[RhinoMocks]]></category>
		<category><![CDATA[Test Driven Development (TDD)]]></category>
		<category><![CDATA[Unit tests]]></category>

		<guid isPermaLink="false">http://arrangeactassert.wordpress.com/?p=53</guid>
		<description><![CDATA[When I was first learning about mocking frameworks (in my case RhinoMocks I found many examples on how to use them. One in particular (this post by Nikola Malovic) gave me the aha moment. This was written some time ago before .Net 3.5 was released. I wanted to show an example of a unit test [...]]]></description>
			<content:encoded><![CDATA[<p>When I was first learning about mocking frameworks (in my case RhinoMocks I found many examples on how to use them.  One in particular (<a href="http://blog.vuscode.com/malovicn/archive/2007/02/05/tdd-rhino-mocks-part-1-introduction.aspx">this post by Nikola Malovic</a>) gave me the aha moment. This was written some time ago before .Net 3.5 was released.</p>
<p>I wanted to show an example of a unit test before and after implementing a mocking framework.  My aim is to show why and how mocking frameworks (including <a href="http://code.google.com/p/moq/">Moq</a>) can help you write unit tests more productively without compromising code readability or maintainability.  Don&#8217;t worry if you&#8217;re new to writing unit tests or mocking frameworks, the examples should be easy enough to follow.  If we have any questions just ask.</p>
<p>So here&#8217;s my take on it.  I have split this post into two parts, stubs and mocks.</p>
<p>Anyway let&#8217;s get to the code.  The goal is to create a unit test to assert &#8216;an error message is logged if a exception occurs when a user tries to add an invalid customer to a database&#8217;.  </p>
<p>The emphasis shouldn&#8217;t be on the code per se, the aim is to keep it simple and easy to understand, after all validating objects is common practice!  Notice how I&#8217;ve used the <strong>Arrange</strong>, <strong>Act</strong> and <strong>Assert</strong> layout so the test is easy to follow.</p>
<p>The code below shows:</p>
<ul>
<li>Customer object</li>
<li>A interface for the logger</li>
<li>A interface and class for customer validation</li>
<li>A class for the customer service</li>
</ul>
<pre class="brush: csharp; toolbar: true; wrap-lines: false;">
using System;

namespace RhinoMocksDemo
{
    public class Customer
    {
        public string Name { get; set; }
    }

    public interface ICustomerValidator
    {
        bool IsValid(Customer customer);
    }

    public class CustomerValidator : ICustomerValidator
    {
        public const string CUSTOMER_NAME_ERROR_MESSAGE = &quot;Customer name cannot be null or empty&quot;;

        public bool IsValid(Customer customer)
        {
            if (String.IsNullOrEmpty(customer.Name))
            {
                throw new ArgumentException(CUSTOMER_NAME_ERROR_MESSAGE);
            }
            return true;
        }
    }

    public interface ILogger
    {
        void LogError(string errorMessage);
    }

    public class CustomerService
    {
        private readonly ICustomerValidator _customerValidator;
        private readonly ILogger _logger;

        public CustomerService(ICustomerValidator customerValidator,ILogger logger)
        {
            _customerValidator = customerValidator;
            _logger = logger;
        }

        public bool AddCustomer(Customer customer)
        {
            try
            {
                if (_customerValidator.IsValid(customer))
                {
                    // Add it to the database
                    return true;
                }
            }
            catch (Exception exception)
            {
                _logger.LogError(exception.Message);
            }
            return false;
        }
    }
}
</pre>
<p>Notice the separation of concerns in the code as the customer validator and logger are passed (injected) in the constructor.  It&#8217;s possible to use mocking frameworks without coding this way, and I might post on how to do that, but let&#8217;s stick to <a href="http://www.hanselman.com/blog/HanselminutesPodcast145SOLIDPrinciplesWithUncleBobRobertCMartin.aspx">Uncle Bobs&#8217; SOLID Principles</a>  for now.</p>
<p>So if I wasn&#8217;t using a mocking framework, I could write a test class that implements the logging interface and pass that into the constructor.</p>
<pre class="brush: csharp; toolbar: true; wrap-lines: false;">
using System.Collections.Generic;
using NUnit.Framework;
using NUnit.Framework.SyntaxHelpers;

namespace RhinoMocksDemo
{
    public class TestLogger: ILogger
    {
        public TestLogger()
        {
            Messages = new List&lt;string&gt;();
        }

        public List&lt;string&gt; Messages { get; private set; }

        public void LogError(string errorMessage)
        {
            Messages.Add(errorMessage);
        }
    }

    [TestFixture]
    public class CustomerProviderTestFixture
    {
        [Test]
        public void Will_Write_To_Log_If_Customer_Fails_Validation_When_Adding_Customer()
        {
            // Arrange
            var customerValidator = new CustomerValidator();
            var testLogger = new TestLogger();

            var customerService = new CustomerService(customerValidator,testLogger);

            var customerWithNoNameThatIsFailVaidation = new Customer();

            //Act
            customerService.AddCustomer(customerWithNoNameThatIsFailVaidation);

            //Assert
            Assert.That(testLogger.Messages.Count,Is.EqualTo(1));
        }
    }
}
</pre>
<p>The test passes and the good news is we have a unit test that achieves our goal.</p>
<p>However there is a major problem here:</p>
<ul>
<li>We are to dependent on the validation class &#8211; i.e. we had to know how to make it throw an exception</li>
</ul>
<p>A mocking framework provides us with the ability use a stub instead of an actual object.  In the code below you can see the test now uses RhinoMocks to generate (a proxy for) the validation object as a stub.  This allows you to control how the stubbed object should behave.</p>
<p>For our example when calling the IsValid method in the code an exception should be thrown.</p>
<pre class="brush: csharp; toolbar: true; wrap-lines: false;">
        [Test]
        public void Will_Write_To_Log_If_Customer_Fails_Validation_When_Adding_Customer_Using_Stub()
        {
            // Arrange
            ICustomerValidator customerValidator = MockRepository.GenerateStub&lt;icustomerValidator&gt;();
            var testLogger = new TestLogger();

            var customerService = new CustomerService(customerValidator, testLogger);

            customerValidator.Stub(c =&gt; c.IsValid(null))
                .IgnoreArguments() // Use this because the argument is not important
                .Throw(new ArgumentException(CustomerValidator.CUSTOMER_NAME_ERROR_MESSAGE));  // This will simulate the throwing of an exception

            //Act
            customerService.AddCustomer(new Customer());

            //Assert
            Assert.That(testLogger.Messages.Count, Is.EqualTo(1));
        }
</pre>
<p>The unit test still passes and we are no longer dependent on how or what makes the validation class throw an exception.</p>
<p>The most common usage is to stub repositories because you don’t want to depend on a database, especially when it comes to continuous integration builds. The following example shows how to get famous people using a repository stub without ever having to create a concrete implementation of a famous people repository. This makes testing faster and allows you to focus on writing good unit tests for the subject under test.</p>
<pre class="brush: csharp; toolbar: true; wrap-lines: false;">
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using Rhino.Mocks;

namespace GettingStartedWithRhinoMocks
{
    public class FamousPeople
    {
        public string Name { get; set; }
    }

    public interface IFamousPeopleRepository
    {
        IEnumerable&lt;famousPeople&gt; GetFamousPeople();
    }

    public class FamousPeopleService
    {
        private readonly IFamousPeopleRepository _famousPeopleRepository;

        public FamousPeopleService(IFamousPeopleRepository famousPeopleRepository)
        {
            _famousPeopleRepository = famousPeopleRepository;
        }

        public IEnumerable&lt;famousPeople&gt; NameStartsWithFilter(string searchText)
        {
            return _famousPeopleRepository.GetFamousPeople().Where(c =&gt; c.Name.StartsWith(searchText));
        }
    }

    [TestFixture]
    public class FamousPeopleServiceTestFixture
    {
        [Test]
        public void Can_Filter_FamousPeople_Using_Stub_To_Return_FamousPeople()
        {
            // Arrange
            var famousPeopleRepository = MockRepository.GenerateStub&lt;ifamousPeopleRepository&gt;();
            var famousPeopleService = new FamousPeopleService(famousPeopleRepository);

            famousPeopleRepository.Stub(c =&gt; c.GetFamousPeople()).Return(FamousPeopleStub);

            // Act
            var result = famousPeopleService.NameStartsWithFilter(&quot;Bill&quot;);

            // Assert
            Assert.That(result.Count(), Is.EqualTo(3));
        }

        private List&lt;famousPeople&gt; FamousPeopleStub
        {
            get
            {

                return new List&lt;famousPeople&gt;()
                           {
                               new FamousPeople(){Name = &quot;Bill Gates&quot;},
                               new FamousPeople(){Name = &quot;Bill Clinton&quot;},
                               new FamousPeople(){Name = &quot;Bob Hope&quot;},
                               new FamousPeople(){Name = &quot;Billy The Kid&quot;}
                           };
            }
        }
    }
}
</pre>
<p>The code is available at <a href="http://code.google.com/p/arrangeactassert/">http://code.google.com/p/arrangeactassert/</a>.  The solution is in the GettingStartedWithRhinoMocks folder.</p>
<p>That&#8217;s it for part 1, in <a href="http://www.arrangeactassert.com/how-to-write-better-unit-tests-using-rhinomocks-and-mocking">part 2</a> we will see how and where using mocks can make a difference!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.arrangeactassert.com/how-to-write-better-unit-tests-using-rhinomocks-and-stubs/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Why releasing code without unit tests as deadlines loom is the same as resorting to playing the &#039;long ball&#039; in football when you’re losing</title>
		<link>http://www.arrangeactassert.com/why-releasing-code-without-unit-tests-as-deadlines-loom-is-the-same-as-resorting-to-playing-the-long-ball-in-football-when-you%e2%80%99re-losing/</link>
		<comments>http://www.arrangeactassert.com/why-releasing-code-without-unit-tests-as-deadlines-loom-is-the-same-as-resorting-to-playing-the-long-ball-in-football-when-you%e2%80%99re-losing/#comments</comments>
		<pubDate>Sun, 25 Jan 2009 20:32:21 +0000</pubDate>
		<dc:creator>Jag Reehal</dc:creator>
				<category><![CDATA[Barcelona FC]]></category>
		<category><![CDATA[Test Driven Development (TDD)]]></category>
		<category><![CDATA[Unit tests]]></category>

		<guid isPermaLink="false">http://arrangeactassert.wordpress.com/?p=23</guid>
		<description><![CDATA[At the last developer developer developer day (DDD7) a few months ago I heard Ian Cooper talk about developers who stopped practicing TDD or even worst still stop writing unit tests altogether as the deadlines approached. I’ve just seen Seville who are second in the Spanish Football League resort to playing long balls that wouldn’t [...]]]></description>
			<content:encoded><![CDATA[<p>At the last developer developer  developer day (<a href="http://www.developerday.co.uk/ddd/default.asp">DDD7</a>) a few months ago I heard Ian Cooper talk about developers who stopped practicing TDD or even worst still stop writing unit tests altogether as the deadlines approached.</p>
<p>I’ve just seen Seville who are second in the Spanish Football League resort to playing long balls that wouldn’t look out of place at Bolton or Blackburn.  What’s more there’s no Sam Allardyce in sight.  Seville were losing 2-0 at home against mid-table Racing Santander.  With more than twenty minutes to go and playing against ten men, a team who are more than capable of playing it ‘on the deck’ started hoofing it.  They still lost 2-0</p>
<p>Barcelona on the other hand have scored no less than 33 goals in the last twenty minutes of their games this season (<a href="http://stats.football365.com/dom/ESP/teams/Barcelona.html">see here</a>).  Even when coming from behind they still manage to play the kind of mouth watering football you expect from them.</p>
<p>So next time a deadline approaches ever closer don’t just sell your soul and ditch unit testing, try and play it cool and remain true of what you believe in.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.arrangeactassert.com/why-releasing-code-without-unit-tests-as-deadlines-loom-is-the-same-as-resorting-to-playing-the-long-ball-in-football-when-you%e2%80%99re-losing/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
