<?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; Automocking</title>
	<atom:link href="http://www.arrangeactassert.com/category/automocking/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>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>
	</channel>
</rss>
