<?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>the tar pit &#187; BDD</title>
	<atom:link href="http://blog.goneopen.com/tag/bdd/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.goneopen.com</link>
	<description>Thrashing around in the stickiness of software</description>
	<lastBuildDate>Wed, 25 Aug 2010 10:10:16 +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>Object Mothers as Fakes</title>
		<link>http://blog.goneopen.com/2009/07/object-mothers-as-fakes/</link>
		<comments>http://blog.goneopen.com/2009/07/object-mothers-as-fakes/#comments</comments>
		<pubDate>Thu, 30 Jul 2009 09:07:41 +0000</pubDate>
		<dc:creator>todd</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[BDD]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[C# 3.5]]></category>
		<category><![CDATA[DDD]]></category>
		<category><![CDATA[extensions]]></category>
		<category><![CDATA[ExtremeProgramming]]></category>
		<category><![CDATA[Fake]]></category>
		<category><![CDATA[Object Mother]]></category>
		<category><![CDATA[OO]]></category>
		<category><![CDATA[patterns]]></category>
		<category><![CDATA[PI]]></category>
		<category><![CDATA[POCO]]></category>
		<category><![CDATA[storyq]]></category>
		<category><![CDATA[TDD]]></category>
		<category><![CDATA[test automation pyramid]]></category>
		<category><![CDATA[TestDataBuilder]]></category>
		<category><![CDATA[UnitTesting]]></category>
		<category><![CDATA[XP]]></category>

		<guid isPermaLink="false">http://blog.goneopen.com/2009/07/object-mothers-as-fakes/</guid>
		<description><![CDATA[This is a follow to Fakes Arent Object Mothers Or Test Builders. Over the last few weeks I have had the chance to reengage with MO and fakes. I am going to document a helper or two with building fakes using extensions. But before that I want to make an observation or two: I have [...]]]></description>
			<content:encoded><![CDATA[<p>This is a follow to <a href="../../../2008/11/fakes-arent-object-mothers-or-test-builders">Fakes Arent Object Mothers Or Test Builders</a>. Over the last few weeks I have had the chance to reengage with MO and fakes. I am going to document a helper or two with building fakes using extensions. But before that I want to make an observation or two:</p>


<ul>
<li>I have been naming my mother objects as ValidMO.xxxxx and making sure they are static</li>
<li>I find that I have a ValidMO per project and that is better than a shared one. For example, in my unit tests the validMO tends to need Ids populated and that is really good as I explore the domain and have to build up the object graph. In my integration tests, however, Id shouldn&#8217;t be populated because that comes from the database and of course changes over time. My MOs in the regression and acceptance test are different again. I wouldn&#8217;t have expected this. It is great because I don&#8217;t have to spawn yet another project just to hold the MO data as I have in previous projects.</li>
<li>I find that I only need one MO per object</li>
<li>Needing another valid example suggests in fact a new type of domain object</li>
<li>I don&#8217;t need to have invalid MOs (I used to)</li>
</ul>



<p>Now for some code.</p>

<p>When building objects for test, the pattern is to either:</p>


<ul>
<li>provide the MO</li>
<li>build the exceptions in a new object and fill out the rest with the MO</li>
<li>not use MO at all (very rarely)</li>
<li>I use this pattern to build objects with basic objects and not Lists &#8211; you&#8217;ll need to extend the tests/code for that</li>
</ul>



<p>To do this I primarily use a builder as an extension. This extension differs between unit and integration tests.</p>

<h2>Unit test object builder</h2>

<p>This code has two tests: Valid and Invalid. The tests demonstrate a couple of things. The first of which is that I am bad by having three tests in the first test. Let&#8217;s just say that&#8217;s for readability <img src='http://blog.goneopen.com/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' />  The first set of tests check that I have setup the ValidMO correctly and that it behaves well with the extension helper &#8220;SetupWithDefaultValuesFrom&#8221;. This series of tests has been really important in the development of the extensions and quickly point to problems &#8211; and believe me this approach hits limits quickly. Nonetheless it is great for most <span class="caps">POCO</span>s.</p>

<p>The second test demonstrates testing invalid by exception. Here there rule is that the image banner is invalid if it has no name. So the code says, make the name empty and populate the rest of the model.</p>



<pre>
  using Core.Domain.Model;
  using Contrib.TestHelper;
  using Microsoft.VisualStudio.TestTools.UnitTesting;
  using UnitTests.Core.Domain.MotherObjects;
  using NBehave.Spec.MSTest;

  namespace UnitTests.Core.Domain.Model
  {
      /// &lt;summary&gt;
      /// Summary description for Image Banner Property Validation Test
      /// &lt;/summary&gt;
      [TestClass]
      public class ImageBannerPropertyValidationTest
      {
          [TestMethod]
          public void Valid()
          {
              ValidMO.ImageBanner.ShouldNotBeNull();
              ValidMO.ImageBanner.IsValid().ShouldBeTrue();
              new ImageBanner().SetupWithDefaultValuesFrom(ValidMO.ImageBanner).IsValid().ShouldBeTrue();
          }

          [TestMethod]
          public void InvalidHasNoName()
          {
              new ImageBanner { Name = &quot;&quot; }.SetupWithDefaultValuesFrom(ValidMO.ImageBanner).IsValid().ShouldBeFalse();
          }
      } 
  }
</pre>



<p>Here&#8217;s the ValidMO.</p>



<pre>
  namespace UnitTests.Core.Domain.MotherObjects
  {
      public static class ValidMO
      {
          public static IBanner ImageBanner
          {
              get
              {
                  return new ImageBanner
                             {
                                 Id = 1,
                                 Name = &quot;KiwiSaver&quot;,
                                 Url = &quot;http://localhost/repos/first-image.png&quot;,
                                 Destination = &quot;http://going-to-after-click.com&quot;,
                                 Description = &quot;Kiwisaver Banner for latest Govt initiative&quot;,
                                 IsActive = true,
                                 IsDeleted = false
                             };
              }
          }
      }
  }
</pre>



<p>At this stage, you should have a reasonable grasp of the object through the tests and what we think is exemplar scenario data. Here&#8217;s the model if you insist.</p>



<pre>
  using Castle.Components.Validator;

  namespace Core.Domain.Model
  {
      public class ImageBanner : Banner
      {
          [ValidateNonEmpty, ValidateLength(0, 200)]
          public virtual string Url { get; set; }

          [ValidateNonEmpty, ValidateLength(0, 200)]
          public string Destination { get; set; }
      }
  }
</pre>



<h2>Builder extensions</h2>

<p>Now for the extensions that hold this code together. It is a simple piece of code that takes the model and OM and merges them. Before we go too far. It is actually little more ugly than I want it to be and haven&#8217;t had time to think of a more elegant solution. There are actually two methods. One that overrides the model based on null/empty properties and one that also see zero ints and empty strings also as null/empty. So generally, you need to two.</p>



<pre>
  using System;
  using System.Linq;
  using Contrib.Utility;

  namespace Contrib.TestHelper
  {
      /// &lt;summary&gt;
      /// Test helpers on Mother objects
      /// &lt;/summary&gt;
      public static class MotherObjectExtensions
      {

          /// &lt;summary&gt;
          /// Setups the specified model ready for test by merging a fake model with the model at hand. The code merges
          /// the properties of the given model with any defaults from the fake. If the value of a property on the model is an int and its value is 0 
          /// it is treated as null and the fake is used instead.
          /// overridden 
          /// &lt;/summary&gt;
          /// &lt;typeparam name=&quot;T&quot;&gt;&lt;/typeparam&gt;
          /// &lt;param name=&quot;model&quot;&gt;The model.&lt;/param&gt;
          /// &lt;param name=&quot;fake&quot;&gt;The fake.&lt;/param&gt;
          /// &lt;returns&gt;the model&lt;/returns&gt;
          public static T SetupWithDefaultValuesFrom&lt;T&gt;(this T model, T fake)
          {
              var props = from prop in model.GetType().GetProperties() // select model properities to populate the fake because the fake is the actual base
                          where prop.CanWrite
                          &amp;&amp; prop.GetValue(model, null) != null
                          &amp;&amp; (
                              ((prop.PropertyType == typeof(int) || prop.PropertyType == typeof(int?)) &amp;&amp; prop.GetValue(model, null).As&lt;int&gt;() != 0)
                           || ((prop.PropertyType == typeof(long) || prop.PropertyType == typeof(long?)) &amp;&amp; prop.GetValue(model, null).As&lt;long&gt;() != 0)
                           || (prop.PropertyType == typeof(string) &amp;&amp; prop.GetValue(model, null).As&lt;string&gt;() != String.Empty)
                              )
                          select prop;

              foreach (var prop in props)
                  prop.SetValue(fake, prop.GetValue(model, null), null); //override the fake with model values

              return fake;
          }
   
          /// &lt;summary&gt;
          /// Setups the specified model ready for test by merging a fake model with the model at hand. The code merges
          /// the properties of the given model with any defaults from the fake. This method is the same as &lt;see cref=&quot;SetupWithDefaultValuesFrom{T}&quot;/&gt;
          /// except that empty strings or 0 int/long are able to be part of the setup model
          /// overridden 
          /// &lt;/summary&gt;
          /// &lt;typeparam name=&quot;T&quot;&gt;&lt;/typeparam&gt;
          /// &lt;param name=&quot;model&quot;&gt;The model.&lt;/param&gt;
          /// &lt;param name=&quot;fake&quot;&gt;The fake.&lt;/param&gt;
          /// &lt;returns&gt;the model&lt;/returns&gt;
          public static T SetupWithDefaultValuesFromAllowEmpty&lt;T&gt;(this T model, T fake)
          {
              var props = from prop in model.GetType().GetProperties() // select model properities to populate the fake because the fake is the actual base
                          where prop.CanWrite
                          &amp;&amp; prop.GetValue(model, null) != null
                          select prop;

              foreach (var prop in props)
                  prop.SetValue(fake, prop.GetValue(model, null), null); //override the fake with model values

              return fake;
          }
      }
  }
</pre>




<p>oh, and I just noticed there is another little helper in there too. It is the object.As<object> helper that casts my results in this case as a string. I will include it and thank Rob for the original code and Mark for an update &#8211; and probably our employer for sponsoring our after-hours work <img src='http://blog.goneopen.com/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> :<br />
  </p>


<pre>
    using System;
    using System.IO;


    namespace Contrib.Utility
    {
        /// &lt;summary&gt;
        /// Class used for type conversion related extension methods
        /// &lt;/summary&gt;
        public static class ConversionExtensions
        {
            public static T As&lt;T&gt;(this object obj) where T : IConvertible
            {
                return obj.As&lt;T&gt;(default(T));
            }

            public static T As&lt;T&gt;(this object obj, T defaultValue) where T : IConvertible
            {
                try
                {
                    string s = obj == null ? null : obj.ToString();
                    if (s != null)
                    {
                        Type type = typeof(T);
                        bool isEnum = typeof(Enum).IsAssignableFrom(type);
                        return (T)(isEnum ?
                            Enum.Parse(type, s, true)
                            : Convert.ChangeType(s, type));
                    }
                }
                catch
                {
                }
                return defaultValue; 
            }

            public static T? AsNullable&lt;T&gt;(this object obj) where T : struct, IConvertible
            {
                try
                {
                    string s = obj as string;
                    if (s != null)
                    {
                        Type type = typeof(T);
                        bool isEnum = typeof(Enum).IsAssignableFrom(type);
                        return (T)(isEnum ?
                            Enum.Parse(type, s, true)
                            : Convert.ChangeType(s, type));
                    }
                }
                catch
                {

                }
                return null;
            }

            public static byte[] ToBytes(this Stream stream)
            {
                int capacity = stream.CanSeek ? (int)stream.Length : 0;
                using (MemoryStream output = new MemoryStream(capacity))
                {
                    int readLength;
                    byte[] buffer = new byte[4096];

                    do
                    {
                        readLength = stream.Read(buffer, 0, buffer.Length);
                        output.Write(buffer, 0, readLength);
                    }
                    while (readLength != 0);

                    return output.ToArray();
                }
            }

            public static string ToUTF8String(this byte[] bytes)
            {
                if (bytes == null)
                    return null;
                else if (bytes.Length == 0)
                    return string.Empty;
                var str = System.Text.Encoding.UTF8.GetString(bytes);

                // If the string begins with the byte order mark
                if (str[0] == '\xFEFF')
                    return str.Substring(1);
                else
                {
                    return str;
                }
            }
        }
    }
    
</pre>




<p>Finally, if actually do use this code here are tests:</p>



<pre>
  using Contrib.TestHelper;
  using Microsoft.VisualStudio.TestTools.UnitTesting;
  using NBehave.Spec.MSTest;

  namespace Contrib.Tests.TestHelper
  {
      /// &lt;summary&gt;
      /// Summary description for MotherObject Extensions Test
      /// &lt;/summary&gt;
      [TestClass]
      public class MotherObjectExtensionsTest
      {

          [TestMethod]
          public void EmptyString()
          {
              var test = new Test { }.SetupWithDefaultValuesFrom(new Test { EmptyString = &quot;this&quot; });
              test.EmptyString.ShouldEqual(&quot;this&quot;);
          }
          [TestMethod]
          public void ModelStringIsUsed()
          {
              var test = new Test { EmptyString = &quot;that&quot; }.SetupWithDefaultValuesFrom(new Test { EmptyString = &quot;this&quot; });
              test.EmptyString.ShouldEqual(&quot;that&quot;);
          }
          [TestMethod]
          public void EmptyStringIsAccepted()
          {
              var test = new Test { EmptyString = &quot;&quot; }.SetupWithDefaultValuesFromAllowEmpty(new Test { EmptyString = &quot;this&quot; });
              test.EmptyString.ShouldEqual(&quot;&quot;);
          }

          [TestMethod]
          public void ZeroInt()
          {
              var test = new Test { }.SetupWithDefaultValuesFrom(new Test { ZeroInt = 1 });
              test.ZeroInt.ShouldEqual(1);
          }
          [TestMethod]
          public void ModelIntIsUsed()
          {
              var test = new Test { ZeroInt = 2 }.SetupWithDefaultValuesFrom(new Test { ZeroInt = 1 });
              test.ZeroInt.ShouldEqual(2);
          }
          [TestMethod]
          public void ZeroIntIsAccpted()
          {
              var test = new Test { ZeroInt = 0}.SetupWithDefaultValuesFromAllowEmpty(new Test { ZeroInt = 1 });
              test.ZeroInt.ShouldEqual(0);
          }

          [TestMethod]
          public void ZeroLong()
          {
              var test = new Test { }.SetupWithDefaultValuesFrom(new Test { ZeroLong = 1 });
              test.ZeroLong.ShouldEqual(1);
          }
          [TestMethod]
          public void ModelLongIsUsed()
          {
              var test = new Test { ZeroLong = 2 }.SetupWithDefaultValuesFrom(new Test { ZeroLong = 1 });
              test.ZeroLong.ShouldEqual(2);
          }
          [TestMethod]
          public void ZeroLongIsAccepted()
          {
              var test = new Test {ZeroLong = 0}.SetupWithDefaultValuesFromAllowEmpty(new Test { ZeroLong = 1 });
              test.ZeroLong.ShouldEqual(0);
          }

          private class Test
          {
              public string EmptyString { get; set; }
              public int ZeroInt { get; set; }
              public long ZeroLong { get; set; }
          }
      }
  }

</pre>



<p>I hope that helps.</p>]]></content:encoded>
			<wfw:commentRss>http://blog.goneopen.com/2009/07/object-mothers-as-fakes/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Creating a restful-resources application in rails</title>
		<link>http://blog.goneopen.com/2009/07/creating-a-restful-resources-application-in-rails/</link>
		<comments>http://blog.goneopen.com/2009/07/creating-a-restful-resources-application-in-rails/#comments</comments>
		<pubDate>Sun, 12 Jul 2009 03:00:45 +0000</pubDate>
		<dc:creator>todd</dc:creator>
				<category><![CDATA[BDD]]></category>
		<category><![CDATA[rails]]></category>
		<category><![CDATA[rspec]]></category>

		<guid isPermaLink="false">http://blog.goneopen.com/2009/07/creating-a-restful-resources-application-in-rails/</guid>
		<description><![CDATA[I am creating a rails application and I haven&#8217;t used rails in 2 years and, of course, version 2.2.2. So I thought that I had better record my major steps. I also needed to learn how to use rspec with rails (rather than the unit tests). Update all the gems gem update Install the plugins [...]]]></description>
			<content:encoded><![CDATA[<p>I am creating a rails application and I haven&#8217;t used rails in 2 years and, of course, version 2.2.2. So I thought that I had better record my major steps. I also needed to learn how to use rspec with rails (rather than the unit tests).</p>

<h2>Update all the gems</h2>



<pre>gem update </pre>



<h2>Install the plugins</h2>



<pre>
  sudo gem install rspec
  sudo gem install cucumber
  sudo gem install rcov
  sudo gem install rspec-rails
  
  script/plugin install git &lt;-- rspec
  script/plugin install git://github.com/phorsfall/rspec_on_rails_nested_scaffold.git
  script/plugin install git://github.com/activescaffold/active_scaffold.git
</pre>



<h2>Install Jquery</h2>



<pre>
  ./script/plugin install http://ennerchi.googlecode.com/svn/trunk/plugins/jrails
  </pre>



<h2>Tutorial for logins</h2>



<pre>git clone git://github.com/activefx/restful_authentication_tutorial.git new_folder</pre>



<p><code>./script/generate rspec_scaffold Skill name:string category_id:integer description:string</code></p>]]></content:encoded>
			<wfw:commentRss>http://blog.goneopen.com/2009/07/creating-a-restful-resources-application-in-rails/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Fakes Arent Object Mothers Or Test Builders</title>
		<link>http://blog.goneopen.com/2008/11/fakes-arent-object-mothers-or-test-builders/</link>
		<comments>http://blog.goneopen.com/2008/11/fakes-arent-object-mothers-or-test-builders/#comments</comments>
		<pubDate>Thu, 20 Nov 2008 03:59:11 +0000</pubDate>
		<dc:creator>todd</dc:creator>
				<category><![CDATA[BDD]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[C# 3.5]]></category>
		<category><![CDATA[DDD]]></category>
		<category><![CDATA[extensions]]></category>
		<category><![CDATA[ExtremeProgramming]]></category>
		<category><![CDATA[Fake]]></category>
		<category><![CDATA[Object Mother]]></category>
		<category><![CDATA[OO]]></category>
		<category><![CDATA[patterns]]></category>
		<category><![CDATA[PI]]></category>
		<category><![CDATA[POCO]]></category>
		<category><![CDATA[storyq]]></category>
		<category><![CDATA[TDD]]></category>
		<category><![CDATA[TestDataBuilder]]></category>
		<category><![CDATA[UnitTesting]]></category>
		<category><![CDATA[XP]]></category>

		<guid isPermaLink="false">http://blog.goneopen.com/2008/11/fakes-arent-object-mothers-or-test-builders/</guid>
		<description><![CDATA[Fakes are not Object Mothers or Test Data Builders and Extensions are a bridge to aid BDD through StoryQ I&#8217;ve just spent the week at Agile2008 and have had it pointed out to me that I have been using Fakes as nomenclature when in fact it is an Object Mother pattern. So I have set [...]]]></description>
			<content:encoded><![CDATA[<h1>Fakes are not Object Mothers or Test Data Builders and Extensions are a bridge to aid <span class="caps">BDD </span>through StoryQ</h1>

<p>I&#8217;ve just spent the week at Agile2008 and have had it pointed out to me that I have been using Fakes as nomenclature when in fact it is an Object Mother pattern. So I have set off to learn about the Object Mother pattern and in doing so came across the Test Data Builder pattern. But because I am currently working in C# 3.5 and using PI/POCOs/DDD, the builder pattern at looking a little heavy and the criticism of Object Mother holds that it ends up as a God object and hence a little too cluttered.</p>

<p>I&#8217;ve also found utilising Extensions in C# 3.5 as a good way to keep the OM clean. By adding extensions, it cleans up the code significantly such that <span class="caps">BDD </span>through StoryQ became attractive. Extensions have these advantages:</p>


<ul>
<li>Allows you to put a SetUp (Build/Contruct) method on the object itself</li>
<li>Makes this/these methods only available within the test project only</li>
<li>Keeps data/values separate from setup ie as a cross-cutting concern</li>
<li>In tests, specific edge data &#8211; or basic tests &#8211; aren&#8217;t put into object mothers</li>
<li>Extensions end up concise and <span class="caps">DRY </span>code</li>
</ul>



<h2>Background</h2>

<p>I have been using a Fake models as a strategy to unit test (based on Jimmy Nillson&#8217;s <span class="caps">DDD </span>in C# book). Technically, these are not fakes. According to sites, fakes are a strategy to replace service objects rather than value objects. My use of fakes is rather the &#8220;Object Mother&#8221; pattern. (Am I the only person six years behind? Probably.) Since knowing about this pattern, I&#8217;ve found it on Fowler&#8217;s bliki and the original description at XP Universe 2001 (however, I haven&#8217;t been able to download the paper as yet &#8211; xpuniverse.com isn&#8217;t responding).</p>

<p>Having read entries around this pattern, another pattern emerged: the &#8220;Test Data Builder&#8221; pattern. It is a likable pattern. (In fact, it could be leveraged as an internal <span class="caps">DSL </span>- but I haven&#8217;t pursued that as yet.) But, given the work I do in C#, it looks a little heavy as it is useful to cope with complex dependencies. In contrast, the fake/object mother I have been using has been really easily to teach, and well liked by, developers. </p>

<h2>Basic approach</h2>

<p>To test these approaches, I am going to create a simple model: User which has an Address. Both models have validations on the fields and I can ask the model to validate itself. You&#8217;ll note that I am using Castle&#8217;s validations component. This breaks <span class="caps">POCO </span>rules of a single library but in practice is a good trade-off. My basic test heuristic:</p>


<ul>
<li>populate with defaults = valid</li>
<li>test each field with an invalid value</li>
<li>ensure that inherited objects are also validated</li>
</ul>



<h2>Four Strategies:</h2>


<ol>
<li> Object Mother</li>
<li> Test Data Builder</li>
<li> Extensions with Object Mother</li>
<li> StoryQ with Extensions (and Object Mother)</li>
</ol>



<h1>Strategy One: Object Mother</h1>

<p>First, the test loads up a valid user through a static method (or property if you wish). I use the convention &#8220;Valid&#8221; to always provide back what is always a valid model. This is a good way to demonstrate to new devs what the exemplar object looks like. Interesting, in C# 3.5, the new constructor convention works very well here. You can read down the list of properties easily, often without need to look at the original model code. Moreover, in the original object, there is no need for an overloaded constructor.</p>



<pre>[Test]
 public void ValidUser()
 {
     var fake = TestUser.Valid();
     Assert.IsTrue(fake.IsOKToAccept());
 }

  public class TestUser
   {
       public static User Valid()
       {
           return new User {
               Name = &quot;Hone&quot;, 
               Email = &quot;Hone@somewhere.com&quot;, 
               Password=&quot;Hone&quot;, 
               Confirm = &quot;Hone&quot;
       }
   }
</pre>



<p>Oh, and here&#8217;s the User model if you are interested. Goto to <a href="http://castle.org">Castle Validations</a> if this isn&#8217;t clear.</p>



<pre> public class User
 {
     [ValidateLength(1, 4)]
     public string Name { get; set; }

     [ValidateEmail]
     public string Email { get; set; }

     [ValidateSameAs(&quot;Confirm&quot;)]
     [ValidateLength(1,9)]
     public string Password { get; set; }
     public string Confirm { get; set; }

     public bool IsOKToAccept()
     {
         ValidatorRunner runner = new ValidatorRunner(new CachedValidationRegistry());
         return runner.IsValid(this);
     }
  }
</pre>



<p>Second, the test works through confirming that each validation works. Here we need to work through each of the fields checking for invalid values. With the object mother pattern, each case is a separate static method: email, name and password. The strategy is to always always start with the valid model, make only one change and test. It&#8217;s a simple strategy, easy to read and avoids duplication. The problem with this approach is hiding test data; we have to trust that the method, &#8220;invalidName&#8221;, is actually an invalid name or follow it through to the static method. In practice, it works well enough and avoids duplication.</p>



<pre>public static User InvalidEmail()
{
    var fake = Valid();
    fake.Email = &quot;invalid@@some.com&quot;;
    return fake;
}

public static User InvalidName()
{
    var fake = Valid();
    fake.Name = &quot;with_more_than_four&quot;;
    return fake;
}

public static User InvalidPassword()
{
    var fake = Valid();
    fake.Password = &quot;not_same&quot;;
    fake.Confirm = &quot;different&quot;;
    return fake;
}

[Test]
public void InValidEmail()
{
    var fake = TestUser.InvalidEmail();
    Assert.IsFalse(fake.IsOKToAccept());
}

[Test]
public void InValidName()
{
    var fake = TestUser.InvalidName();
    Assert.IsFalse(fake.IsOKToAccept());
}

[Test]
public void InValidPassword()
{
    var fake = TestUser.InvalidPassword();
    Assert.IsFalse(fake.IsOKToAccept());
}
</pre>



<h1>Strategy Two: Test Data Builder</h1>

<p>I&#8217;m not going to spend long on this piece of code because the builder looks like too much work. The pattern is well documented so I assume you already understand it. I do think that it could be useful if you want to create an internal <span class="caps">DSL </span>to work through dependencies. Put differently, this example is too simple to demonstrate a case for when to use this pattern (IMHO).</p>

<p>First, here&#8217;s the test for the valid user. I found that I injected the valid user behind the scenes (with an object mother) so that I could have a fluent interface with Build(). I can overload the constructor to explicitly inject a user too. I have two options when passing in an object: (1) inject my object mother or (2) inject a locally constructed object. The local construction is useful for explicitly seeing what is being tested. But really, it is the syntactic sugar of C# that is giving visibility rather than the pattern; so, for simple cases, the syntax of the language renders the pattern more verbose.</p>



<pre>[Test]
public void ValidUser()
{
    var fake = new UserBuilder().Build();
    Assert.IsTrue(fake.IsOKToAccept());

}

[Test]
public void LocalUser()
{
    var fake = new UserBuilder(TestUser.Valid()).Build();
    Assert.IsTrue(fake.IsOKToAccept());

    fake = new UserBuilder(new User
                    {
                        Name = &quot;Hone&quot;, 
                        Email = &quot;good@com.com&quot;,
                        Password = &quot;password&quot;,
                        Confirm = &quot;password&quot;,
                        Address = new Address
                                      {
                                          Street = &quot;Fred&quot;,
                                          Number = &quot;19&quot;
                                      }
                    })
                    .Build();
    Assert.IsTrue(fake.IsOKToAccept());
}

public class UserBuilder
{
    private readonly User user;

    public UserBuilder()
    {
        user = TestUser.Valid();
    }

    public UserBuilder(User user)
    {
        this.user = user;
    }

    public User Build() { return user; }
}
</pre>



<p>Second, let&#8217;s validate each field. In the code, and on the positive side, it is clear what constitutes an invalid value and it caters for dependencies such as in &#8220;withPassword&#8221; between password and confirm. But, really, there is just too much typing; I have to create a method for every field and dependency. For simple models, I am not going to do this. For complex or large models, it would take ages.</p>



<pre>[Test]
public void InValidEmail()
{
    var fake = new UserBuilder()
        .withEmail(&quot;incorect@@@emai.comc.com.com&quot;)
        .Build();
    Assert.IsFalse(fake.IsOKToAccept());
}

[Test]
public void InValidName()
{
    var fake = new UserBuilder()
        .withName(&quot;a_name_longer_than_four_characters&quot;)
        .Build();
    Assert.IsFalse(fake.IsOKToAccept());
}

[Test]
public void InValidPassword()
{
    var fake = new UserBuilder()
        .withPassword(&quot;bad_password&quot;)
        .Build();
    Assert.IsFalse(fake.IsOKToAccept());
}

public class UserBuilder
{
    private readonly User user;

    public UserBuilder()
    {
        user = TestUser.Valid();
    }

    public UserBuilder(User user)
    {
        this.user = user;
    }

    public UserBuilder withEmail(string email)
    {
        user.Email = email;
        return this;
    }

    public UserBuilder withPassword(string password)
    {
        user.Confirm = password;
        user.Password = password;
        return this;
    }

    public UserBuilder withName(string name)
    {
        user.Name = name;
        return this;
    }

    public UserBuilder withAddress(Address address)
    {
        user.Address = address;
        return this;
    }

    public User Build() { return user; }
}
</pre>



<h2>Strategy Three: Object Mother with Extensions</h2>

<p>Having tried the two previous patterns, I now turn to what extensions have to offer me. (Extensions are something I have been meaning to try for a while.) As it turns out extensions combined with the new constructors allow for <span class="caps">SOC </span>and <span class="caps">DRY </span>and also allow us to separate valid and invalid data in tests. There is a downside of course. It requires some (reflection) code to make it play nicely. More code &#8211; a slippery slope some might say &#8230;</p>

<p>First, I have added a new method to my User model in the form of an extension. I have named it SetUp so that it translates into the setup and teardown (init and dispose) phases of unit testing. I could use Build or Construct instead. This method returns my object mother. I still like to keep my object mother data separate because I think of construction and data as separate concerns.</p>



<pre>[Test]
 public void ValidUser()
 {
     var fake = new User().SetUp();
     Assert.IsTrue(fake.IsOKToAccept());
 }

 public static User SetUp(this User user)
 {
     User fake = TestUser.Valid();
     return fake; 
 }
</pre>



<p>I also want to test how to create a version of the user visible from the test code. This is where more code is required to combine the any provided fields from the test with the default, valid model.  In returning hydrated test user, this method accepts your partially hydrated object and then adds defaults. The goal is that your unit test code only provides specifics for the test. The rest of the valid fields are opaque to your test; the code reflects on your model only hydrating empty fields so that validations do not fail. This reflection code is used by all SetUp methods across models.</p>



<pre>[Test]
 public void LocalUser()
 {
     var fake = new User { Name = &quot;John&quot;, Email = &quot;valid@someone.com&quot; }.SetUp();
     Assert.IsTrue(fake.IsOKToAccept());
 }

 public static User SetUp(this User user)
 {
     User fake = TestUser.Valid();
     SyncPropertiesWithDefaults(user, fake);
     return fake; 
 }

 private static void SyncPropertiesWithDefaults(object obj, object @base)
   {
       foreach (PropertyInfo prop in obj.GetType().GetProperties())
       {
           object[] val = new object[1];
           val[0] = obj.GetType().GetProperty(prop.Name).GetValue(obj, null);
           if (val[0] != null)
           {
               obj.GetType().InvokeMember(prop.Name, BindingFlags.SetProperty, Type.DefaultBinder, @base, val);
           }
       }
   }
</pre>



<p>Second, let&#8217;s again look at the code to validate all the fields. Now, note at this point there no other object mothers. I see this strategy says, use object mothers to model significant data and avoid cluttering these with edge cases. The result is to hand in the field/value to isolate and then test. I find this readable and it addresses the concern of not making visible the edge case (invalid) data.</p>



<pre>[Test]
public void InValidEmail()
{
    var fake = new User { Email = &quot;BAD@@someone.com&quot; }.SetUp();
    Assert.IsFalse(fake.IsOKToAccept());
}

[Test]
public void InValidName()
{
    var fake = new User { Name = &quot;too_long_a_name&quot; }.SetUp();
    Assert.IsFalse(fake.IsOKToAccept());
}

[Test]
public void InValidPassword()
{
    var fake = new User { Password = &quot;password_one&quot;, Confirm = &quot;password_two&quot; }.SetUp();
    Assert.IsFalse(fake.IsOKToAccept());
}

Using extensions combined with constructors are nice. We can also format the page to make it look like a fluent interface if need. For example:

[Test]
public void InValidPassword()
{
    var fake = new User 
                { 
                    Password = &quot;password_one&quot;, 
                    Confirm = &quot;password_two&quot; 
                }
                .SetUp();
    Assert.IsFalse(fake.IsOKToAccept());
}
</pre>



<h1>Strategy Four: <span class="caps">BDD </span>and StoryQ</h1>

<p>Having worked out that using extensions reduce repetitious code, I still think there is a smell here. Are those edge cases going to add value in the current form? They really are bland. Sure, the code is tested. But, really, who wants to read and review those tests? I certainly didn&#8217;t use them to develop the model code; they merely assert overtime that my assumptions haven&#8217;t changed. Let&#8217;s look at how I would have written the same tests using <span class="caps">BDD </span>and in particularly <a href="http://storyq.codeplex.com">StoryQ</a>. Here&#8217;s a potential usage of my User model.</p>



<pre>Story: Creating and maintaining users

  As an user
  I want to have an account
  So that I can register, login and return to the site

  Scenario 1: Registration Page
    Given I enter my name, address, email and password     
    When username isn't longer than 4 characters           
      And email is validate                                
      And password is correct length and matches confirm   
      And address is valid                                 
    Then I can log now login
      And I am sent a confirmation email
</pre>



<p>Leaving aside any problems in the workflow (which there are), the story works with the model in context. Here is the code that generates this story:</p>



<pre>[Test]
public void Users()
{
    Story story = new Story(&quot;Creating and maintaining users&quot;);

    story.AsA(&quot;user&quot;)
        .IWant(&quot;to have an account&quot;)
        .SoThat(&quot;I can register, login and return to the site&quot;);

    story.WithScenario(&quot;Registration Page&quot;)
        .Given(Narrative.Exec(&quot;I enter my name, address, email and password&quot;, 
                 () =&gt; Assert.IsTrue(new User().SetUp().IsOKToAccept())))
        
        .When(Narrative.Exec(&quot;username isn't longer than 4 characters&quot;, 
                 () =&gt; Assert.IsFalse(new User{Name = &quot;Too_long&quot;}.SetUp().IsOKToAccept())))

        .And(Narrative.Exec(&quot;email is validate&quot;, 
                 () =&gt; Assert.IsFalse(new User { Email = &quot;bad_email&quot; }.SetUp().IsOKToAccept())))

        .And(Narrative.Exec(&quot;password is correct length and matches confirm&quot;, 
                 () =&gt; Assert.IsFalse(new User { Password = &quot;one_version&quot;, Confirm = &quot;differnt&quot;}.SetUp().IsOKToAccept())))

        .And(Narrative.Exec(&quot;address is valid&quot;, 
                  () =&gt; Assert.IsFalse(new User { Address = new Address{Street = null}}.SetUp().IsOKToAccept())))
        
        .Then(Narrative.Text(&quot;I can log now login&quot;))
        .And(Narrative.Text(&quot;I am sent a confirmation email&quot;));

    story.Assert();
}
</pre>



<p>Working with <span class="caps">BDD </span>around domain models and validations makes sense to me. I think that it is a good way to report validations back up to the client and the team. There is also a good delineation between the &#8220;valid&#8221; model (&#8220;Given&#8221; section) and &#8220;invalid&#8221; (&#8220;When&#8221; section) edge cases in the structure. In this case, it also demonstrates that those models so far do nothing because there are no tests in the &#8220;Then&#8221; section. </p>

<h2>Some quick conclusions</h2>


<ol>
<li> Syntactic sugar of new constructor methods in C# 3.5 avoids the need for &#8220;with&#8221; methods found the Test Data Builder pattern</li>
<li> Extensions may better replace the Build method in the builder</li>
<li> Object mothers are still helpful to retain separation of concerns (eg data from construction)</li>
<li> Go <span class="caps">BDD </span> <img src='http://blog.goneopen.com/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> </li>
</ol>



<p>Well that&#8217;s about it for now. Here&#8217;s a download of the full code sample in <span class="caps">VS2008.</span></p>

<p><strong>Postscript:</strong> About Naming Conventions</p>

<p>How do I go about naming my object mother? I have lots of options: Test, Fake, ObjectMother, <span class="caps">OM,</span> Dummy. Of course, if I was purist it would be ObjectMother. But that doesn&#8217;t sit well with me when explaining it others. Although it does make explicit the pattern being used, I find fake most useful (eg FakeUser). It rolls off the tongue, it is self evident enough to outsiders as a strategy. Test (eg TestUser), on the other hand, is generic enough that I have to remind myself of its purpose and then I find I always need to do quick translations from the tests themselves. For example, with UserTest and TestUser I have read them to check which I am working with. For these samples, I have used TestUser. If you come back to my production code you will find FakeUser. I hope that doesn&#8217;t prove problematic in the long run as it isn&#8217;t really a fake.</p>]]></content:encoded>
			<wfw:commentRss>http://blog.goneopen.com/2008/11/fakes-arent-object-mothers-or-test-builders/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>jQuery and testing &#8212; JSUnit, QUnit, JsSpec [Part 2]</title>
		<link>http://blog.goneopen.com/2008/11/jquery-and-testing-jsunit-qunit-jsspec-part-2/</link>
		<comments>http://blog.goneopen.com/2008/11/jquery-and-testing-jsunit-qunit-jsspec-part-2/#comments</comments>
		<pubDate>Sat, 15 Nov 2008 10:34:14 +0000</pubDate>
		<dc:creator>todd</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[BDD]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[jsspec]]></category>
		<category><![CDATA[jsunit]]></category>
		<category><![CDATA[qunit]]></category>
		<category><![CDATA[TDD]]></category>
		<category><![CDATA[UnitTesting]]></category>

		<guid isPermaLink="false">http://blog.goneopen.com/2008/11/jquery-and-testing-jsunit-qunit-jsspec-part-2/</guid>
		<description><![CDATA[Trying QUnit with jQuery In the JSUnit entry, one of the main problems was with the sequencing of calls. Let&#8217;s see how QUnit handles this. QUnit has a simple implementation to this problem: stop() and start() commands to synchronise sequences. The basic approach is that it calls a test function. With the stop() command, it [...]]]></description>
			<content:encoded><![CDATA[<h1>Trying QUnit with jQuery</h1>

<p>In the <a href="../jquery-and-testing-jsunit-qunit-jsspec-part-1/"><span class="caps">JSU</span>nit entry</a>, one of the main problems was with the sequencing of calls. Let&#8217;s see how QUnit handles this. QUnit has a simple implementation to this problem: <code>stop()</code> and <code>start()</code> commands to synchronise sequences. The basic approach is that it calls a test function. With the <code>stop()</code> command, it will not call the next test until you say <code>start()</code>. But it does complete the rest of the current test. </p>

<p>The code that I ended up with was just what I wanted compared to JsUnit. Previously, I had said that basically I wanted to call my function and then process the result that it was in fact what I wanted. Here is the main javascript code (it&#8217;s nice and concise).</p>

<p>One point about the code at this stage. The tests had to be inside the <code>success</code> function to be run. I wonder if this is going to create a code smell in the long run. Plus there is no setup/teardown cycles, again I wonder what that will mean in the long run. Perhaps not?</p>



<pre>module(&quot;XML to object&quot;);

test(&quot;Check the xml to object conversion without showing the tree&quot;, function() {
  
  expect( 5 )
  stop();
  
   $().storyq({
        url: 'data/results-01.xml', 
        load: '',
        success: function(feed) {
          ok( feed, &quot;is an object&quot; )
          ok( !$.isFunction(feed), &quot;is not a function&quot; )
          ok( feed.version, &quot;has a version: &quot; + feed.version )
          ok( feed.items, &quot;has items&quot;)
          same( feed, reference, &quot;is the same as the reference object in data/results-01.js&quot;)
          start();
        }
    });

});
</pre>



<p>Honestly, it is that easy. </p>

<p>Here&#8217;s a couple of features that took me half an hour to work out restated from above. (1) <code>stop()</code> and <code>start()</code> almost work as you expect &#8211; but I had to put some alerts in to check the order of execution. Basically, <strong>a <code>stop()</code> halts any new tests from executing but it keeps the current test executing</strong>. The effect of this is that the asynchronise call can be completed. <code>start()</code> then tells the tests to start running again. If you don&#8217;t have a <code>start()</code> then you will find that your test runner halts altogether. There is another option and that is to put a timer on the stop and then you don&#8217;t need a start. I prefer to keep the tests running as quickly as possible.</p>

<p>Just another note. I decided to do a <code>same()</code> comparison. I have saved and preloaded an object from a file for ease. This kept the test easy to read &#8211; my reference object here is quite long. You can see the insertion of this file in the entire code below <code>&lt;script type=&quot;text/javascript&quot; src=&quot;data/results-01.js&quot;/&gt;</code></p>



<pre>
&amp;lt;html&gt;
&amp;lt;head&gt;
  &amp;lt;title&gt;Unit tests for StoryQ Results viewer&amp;lt;/title&gt;
  &amp;lt;link rel=&quot;stylesheet&quot; href=&quot;../../lib/qunit/testsuite.css&quot; type=&quot;text/css&quot; media=&quot;screen&quot; /&gt;

  &amp;lt;link rel=&quot;stylesheet&quot; href=&quot;../../lib/treeview/jquery.treeview.css&quot; /&gt;
  &amp;lt;link rel=&quot;stylesheet&quot; href=&quot;../../src/css/storyq.treeview.css&quot; /&gt;
  &amp;lt;link rel=&quot;stylesheet&quot; href=&quot;../../src/css/storyq.screen.css&quot; /&gt;

  &amp;lt;script src=&quot;../../lib/jquery/jquery.js&quot;&gt;&amp;lt;/script&gt;
  &amp;lt;script src=&quot;../../lib/jquery/jquery.cookie.js&quot; type=&quot;text/javascript&quot;&gt;&amp;lt;/script&gt;
  &amp;lt;script src=&quot;../../lib/treeview/jquery.treeview.js&quot; type=&quot;text/javascript&quot;&gt;&amp;lt;/script&gt;
  &amp;lt;script src=&quot;../../src/storyq.js&quot; type=&quot;text/javascript&quot;&gt;&amp;lt;/script&gt;
  &amp;lt;script src=&quot;../../src/storyq.treeview.js&quot; type=&quot;text/javascript&quot;&gt;&amp;lt;/script&gt;
  &amp;lt;script src=&quot;../../src/storyq.xml.js&quot; type=&quot;text/javascript&quot;&gt;&amp;lt;/script&gt;
  &amp;lt;script src=&quot;../../src/storyqitem.js&quot; type=&quot;text/javascript&quot;&gt;&amp;lt;/script&gt;
  &amp;lt;script src=&quot;../../src/storyqresults.js&quot; type=&quot;text/javascript&quot;&gt;&amp;lt;/script&gt; 

  &amp;lt;script type=&quot;text/javascript&quot; src=&quot;../../lib/qunit/testrunner.js&quot;&gt;&amp;lt;/script&gt; 
  &amp;lt;script type=&quot;text/javascript&quot; src=&quot;data/results-01.js&quot;&gt;&amp;lt;/script&gt;  
  
  &amp;lt;script type=&quot;text/javascript&quot;&gt;
    module(&quot;XML&quot;);

    test(&quot;Check the xml to object conversion without showing the tree&quot;, function() {

      expect( 5 )
      stop();

       $().storyq({
            url: 'data/results-01.xml', 
            load: '',
            success: function(feed) {
              ok( feed, &quot;is an object&quot; )
              ok( !$.isFunction(feed), &quot;is not a function&quot; )
              ok( feed.version, &quot;has a version: &quot; + feed.version )
              ok( feed.items, &quot;has items&quot;)
              same( feed, reference, &quot;is the same as the refefence object in data/results-01.js&quot;)
              start();
            }
        });

    });
  &amp;lt;/script&gt;
  
&amp;lt;/head&gt;
&amp;lt;body&gt;
  
 &amp;lt;h1&gt;QUnit tests&amp;lt;/h1&gt;
 &amp;lt;h2 id=&quot;banner&quot;&gt;&amp;lt;/h2&gt;
 &amp;lt;h2 id=&quot;userAgent&quot;&gt;&amp;lt;/h2&gt;
 &amp;lt;ol id=&quot;tests&quot;&gt;&amp;lt;/ol&gt;

 &amp;lt;div id=&quot;main&quot;&gt;&amp;lt;/div&gt;

&amp;lt;/div&gt;
&amp;lt;/div&gt;

&amp;lt;/body&gt;
&amp;lt;/html&gt;

</pre>



<p>The output results from QUnit are nice to look at and easy to read. I didn&#8217;t have a couple of errors that weren&#8217;t the easiest to debug given the output. Partly though because I was new to it, I was taking too big a step at times!</p>

<p>I&#8217;m happy with QUnit &#8211; and there are plenty of examples in the JQuery test suite. I can see that I would do <span class="caps">TDD </span>with this.</p>

<p>Being a <span class="caps">BDD </span>type of guy, I&#8217;m now off to see what <a href="../jquery-and-testing-jsunit-qunit-jsspec-part-3/" title="Part III">JsSpec</a> has to offer.</p>]]></content:encoded>
			<wfw:commentRss>http://blog.goneopen.com/2008/11/jquery-and-testing-jsunit-qunit-jsspec-part-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>jQuery and testing &#8211; JSUnit, QUnit, JsSpec [Part 1]</title>
		<link>http://blog.goneopen.com/2008/11/jquery-and-testing-jsunit-qunit-jsspec-part-1/</link>
		<comments>http://blog.goneopen.com/2008/11/jquery-and-testing-jsunit-qunit-jsspec-part-1/#comments</comments>
		<pubDate>Fri, 14 Nov 2008 17:32:11 +0000</pubDate>
		<dc:creator>todd</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[BDD]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[jsspec]]></category>
		<category><![CDATA[jsunit]]></category>
		<category><![CDATA[qunit]]></category>
		<category><![CDATA[TDD]]></category>
		<category><![CDATA[test automation pyramid]]></category>
		<category><![CDATA[UnitTesting]]></category>

		<guid isPermaLink="false">http://blog.goneopen.com/2008/11/jquery-and-testing-jsunit-qunit-jsspec-part-1/</guid>
		<description><![CDATA[Trying JsUnit with JQuery I have started first with JSUnit because it is tried and true (and to tell the truth I thought it would be fine and didn&#8217;t bother with a quick search for alternatives). For the impatient, I won&#8217;t be going with JSUnit and here are some reasons: the problem is that the [...]]]></description>
			<content:encoded><![CDATA[<h1>Trying JsUnit with JQuery</h1>

<p>I have started first with <span class="caps">JSU</span>nit because it is tried and true (and to tell the truth I thought it would be fine and didn&#8217;t bother with a quick search for alternatives).</p>

<p>For the impatient, I won&#8217;t be going with <span class="caps">JSU</span>nit and here are some reasons:</p>


<ul>
<li>the problem is that the integration of a setup (ie onload &#8211; pausing) to load the data doesn&#8217;t integrate well with jQuery. <span class="caps">JSU</span>nit has its own setup and document loader but I am still wondering how to do this transparently (ie I didn&#8217;t actually get the test to work &#8211; I wasn&#8217;t exhaustive but then again I don&#8217;t think that I should have needed to be to get this test going)</li>
<li>Firefox 3.0 on mac doesn&#8217;t integrate well (ie it doesn&#8217;t work), but safari does! Unfortunately, I am a little bound to firebug for development. </li>
<li><span class="caps">JSU</span>nit doesn&#8217;t report tests well either</li>
</ul>



<p>I went and had a look at how <span class="caps">JSU</span>nit does it. (Remember that this framework has been around a lot longer than jQuery.) Here is the extract from the code/test samples. The basic setup is to hook into an existing <code>testManager</code> that existing within a frame and then get the data from there. Furthermore, you need to manage your own flag that the process has been complete. <span class="caps">JSU</span>nit then looks through all functions that start with <code>test</code> in this case <code>testDocumentGetElementsByTagName</code> checks expected data. Here I assume that the tests are run in a particular frame (<code>buffer()</code>) that <code>testManager</code> gives us access to.</p>



<pre>var uri = 'tests/data/data.html';

function setUpPage() {
    setUpPageStatus = 'running';
    top.testManager.documentLoader.callback = setUpPageComplete;
    top.testManager.documentLoader.load(uri);
}

function setUpPageComplete() {
    if (setUpPageStatus == 'running')
        setUpPageStatus = 'complete';
}

function testDocumentGetElementsByTagName() {
    assertEquals(setUpPageStatus, 'complete');
    var buffer = top.testManager.documentLoader.buffer();
    var elms = buffer.document.getElementsByTagName('P');
    assert('getElementsByTagName(&quot;P&quot;) returned is null', elms != null);
    assert('getElementsByTagName(&quot;P&quot;) is empty', elms.length &gt; 0);
}</pre>



<p>Below is the rewritten code to exercise my code. Here&#8217;s a couple of the features:</p>


<ul>
<li>for setup, pass in the correct xml file via <code>uri</code> variable (obviously)</li>
<li>to test, I have written a test <code>testXML2Object</code>. <br />
 <br />
p. There is one major design problem with the code itself that didn&#8217;t allow me to use my own data loader. You will see the line <code>var feed = new StoryQResults(buffer);</code>. Where did that come from? It is nothing close to the code I said that I wanted to exercise. It is infact from <strong>within</strong> the code I want to exercise. The major issue I found here is that to load and test data I had to use the <code>testManager</code> rather than use my own  <code>().storyq()</code> call. </li>
</ul>



<p>The other problem was it wouldn&#8217;t return the result that I wanted either. I was expecting my <code>feed</code> variable to be an object of the results. Instead I was getting a reference to function <code>StoryQResults</code> &#8211; given now that it wasn&#8217;t running in Firefox and I didn&#8217;t have Firebug life was getting a little hard.<br />
 </p>


<pre>var uri = '../../xml/results-01.xml';

function setUpPage() {
    setUpPageStatus = 'running';
    top.testManager.documentLoader.callback = setUpPageComplete;
    top.testManager.documentLoader.load(uri);
}

function setUpPageComplete() {
    if (setUpPageStatus == 'running')
        setUpPageStatus = 'complete';
}

function testXML2Object() {
    assertEquals(setUpPageStatus, 'complete');
    var buffer = top.testManager.documentLoader.buffer();
    
    var feed = new StoryQResults(buffer);               

    assertEquals(feed.version, '0.1')
    assertEquals(&quot;Number of stories&quot;, $(feed).size(), 1)
    $.each(feed, function(){
      alert(this)               
    })

}</pre>



<p>Even though I know that I getting a <code>function</code> returned instead of an <code>object</code> I am still going to see if I can invoke my own loading function within <span class="caps">JSU</span>nit. Here&#8217;s what the code would look like below. I wouldn&#8217;t recommend running it &#8211; just take a look at it. The code to me is a mixtures of styles that start to bloat the code. On the one hand, <span class="caps">JSU</span>nit has this setup phase with explicit flags and no anonymous functions. On the other hand, because I am using JQuery conventions, I encapsulate alot of that logic. For example, <code>jQuery(function(){})</code> waits for the page to be loaded before executing <code>(&quot;#tree&quot;).story()</code>, Then I have the callback function inline. It looks good from the outside, but it doesn&#8217;t work. </p>

<p>The order of calls is: <code>loading</code>, <code>in test</code> and then <code>loaded</code>. Indicating that my <code>JQuery</code> function runs after the test has been run. The order should have been <code>loading</code>, <code>loaded</code> and then <code>in test</code>. In this sense, while <code>setUpPage</code> runs within its own setup/test/teardown cycle. But my JQuery call isn&#8217;t linked into this. JQuery waits is waiting on a document flag rather than a custom flag (within <code>testManager</code>). At this point, I do not wish to dig into these libraries to work them out to get it to all play nicely. It wasn&#8217;t designed to work this way. Let&#8217;s find one that was.</p>



<pre>var data = '';

function setUpPage() {
    setUpPageStatus = 'running';
    alert('loading')
    jQuery(function() {
      $(&quot;#tree&quot;).storyq({
          url: '../../xml/results-01.xml', 
          success: null, 
          load: function(feed) {
            data = feed;
            alert('loaded')
            setUpPageComplete()
            }
          });
    });
}

function setUpPageComplete() {
    if (setUpPageStatus == 'running')
        setUpPageStatus = 'complete';
}

function testXML2Object() {
    alert('in test')
    assertEquals(setUpPageStatus, 'complete');

    assertEquals(data.version, '0.1')
    assertEquals(&quot;Number of stories&quot;, $(feed).size(), 1)
}
</pre>



<p>I&#8217;m invoking the two-feet principle: I&#8217;m moving onto the next framework (after a quick search): <a href="../jquery-and-testing-jsunit-qunit-jsspec-part-2/">QUnit</a></p>]]></content:encoded>
			<wfw:commentRss>http://blog.goneopen.com/2008/11/jquery-and-testing-jsunit-qunit-jsspec-part-1/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>jQuery and testing &#8211; JSUnit, QUnit, JsSpec [Part 3]</title>
		<link>http://blog.goneopen.com/2008/11/jquery-and-testing-jsunit-qunit-jsspec-part-3/</link>
		<comments>http://blog.goneopen.com/2008/11/jquery-and-testing-jsunit-qunit-jsspec-part-3/#comments</comments>
		<pubDate>Fri, 14 Nov 2008 02:35:22 +0000</pubDate>
		<dc:creator>todd</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[BDD]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[jsspec]]></category>
		<category><![CDATA[jsunit]]></category>
		<category><![CDATA[qunit]]></category>
		<category><![CDATA[TDD]]></category>
		<category><![CDATA[test automation pyramid]]></category>
		<category><![CDATA[UnitTesting]]></category>

		<guid isPermaLink="false">http://blog.goneopen.com/2008/11/jquery-and-testing-jsunit-qunit-jsspec-part-3/</guid>
		<description><![CDATA[Trying JsSpec with jQuery This is part three of three. The previous two have been focussed around managing the problem of timing: JSUnit got too hard and QUnit is easy but you still have to manage timings yourself. With JsSpec there is no problem because it is all managed for you. Nice work! Here&#8217;s the [...]]]></description>
			<content:encoded><![CDATA[<h1>Trying JsSpec with jQuery</h1>

<p>This is part three of three. The previous two have been focussed around managing the problem of timing: <a href="../jquery-and-testing-jsunit-qunit-jsspec-part-1/" title="Part I"><span class="caps">JSU</span>nit</a> got too hard and <a href="../jquery-and-testing-jsunit-qunit-jsspec-part-2/" title="Part II">QUnit</a> is easy but you still have to manage timings yourself. With JsSpec there is no problem because it is all managed for you. Nice work! Here&#8217;s the code I had to write. </p>

<p>A couple of things to writing it. I had to dig into the code to find out the setup/teardown lifecycle keywords. There turns out to be setup/teardown per test (eg <code>before</code>) and per test suite (eg <code>before all</code>). I also had to dig around to find then comparators (eg <code>should_be</code>, <code>should_not_be_null</code>). I couldn&#8217;t find any documentation.</p>



<pre>
describe('I need to read the xml and convert into object', {
  'before all': function() {
    target = {};
    $().storyq({
        url: 'data/results-01.xml', 
        load: '',
        success: function(feed) {
          target = feed
      }
    })
   
  },
  
  'should return an object': function() {
    value_of(target).should_not_be_null()
  },
  
  'should not be a function': function() {
    value_of(typeof target).should_not_be(typeof Function )
  },
  
  'should have a version': function(){
    value_of(target.version).should_be('0.1')
  },
  
  'should have items': function(){
    value_of(target.items).should_not_be_empty()
  },
  
  'should have the same value as the reference object in data/results-01.js': function(){
    value_of(reference).should_not_be_undefined()
    value_of(target).should_be(reference)
  },
  
})
</pre>



<p>Ihe output looks nice too <img src='http://blog.goneopen.com/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' />  Here&#8217;s the overall code. Notice that I have also used the technique of a reference object in <code>results-01.js</code>:</p>



<pre>
&amp;lt;html&gt;
&amp;lt;head&gt;
&amp;lt;title&gt;JSSpec results&amp;lt;/title&gt;
&amp;lt;link rel=&quot;stylesheet&quot; type=&quot;text/css&quot; href=&quot;../lib/jsspec/JSSpec.css&quot; /&gt;
&amp;lt;script type=&quot;text/javascript&quot; src=&quot;../lib/jsspec/JSSpec.js&quot;/&gt;

&amp;lt;script src=&quot;../lib/jquery/jquery.js&quot;/&gt;
&amp;lt;script src=&quot;../lib/jquery/jquery.cookie.js&quot; type=&quot;text/javascript&quot;/&gt;
&amp;lt;script src=&quot;../lib/treeview/jquery.treeview.js&quot; type=&quot;text/javascript&quot;/&gt;
&amp;lt;script src=&quot;../build/dist/jquery.storyq.js&quot; type=&quot;text/javascript&quot;/&gt;

&amp;lt;script type=&quot;text/javascript&quot; src=&quot;data/results-01.js&quot;/&gt;
&amp;lt;script type=&quot;text/javascript&quot; src=&quot;specs/treeview.js&quot;/&gt;  

&amp;lt;script type=&quot;text/javascript&quot;&gt;

  describe('I need to read the xml and convert into object', {
    'before all': function() {
      target = {};
      $().storyq({
          url: 'data/results-01.xml', 
          load: '',
          success: function(feed) {
            target = feed
        }
      })

    },

    'should return an object': function() {
      value_of(target).should_not_be_null()
    },

    'should not be a function': function() {
      value_of(typeof target).should_not_be(typeof Function )
    },

    'should have a version': function(){
      value_of(target.version).should_be('0.1')
    },

    'should have items': function(){
      value_of(target.items).should_not_be_empty()
    },

    'should have the same value as the reference object in data/results-01.js': function(){
      value_of(reference).should_not_be_undefined()
      value_of(target).should_be(reference)
    },

  })
&amp;lt;/script&gt;

&amp;lt;/head&gt;
    &amp;lt;body&gt;
      &amp;lt;div style=&quot;display:none;&quot;&gt;&amp;lt;p&gt;A&amp;lt;/p&gt;&amp;lt;p&gt;B&amp;lt;/p&gt;&amp;lt;/div&gt;
    &amp;lt;/body&gt;
&amp;lt;/html&gt;
</pre>



<p><span class="caps">JSS</span>pec isn&#8217;t written using JQuery. So there are a couple of issues that I can&#8217;t pin down. When I get errors it stops the tests completely. I suspect that this is because these tests are using callbacks and they don&#8217;t return an (JQuery) object. JQuery does alot of object chaining and JsSpec isn&#8217;t cut out for it (I think).</p>

<p>Well, that&#8217;s it.</p>]]></content:encoded>
			<wfw:commentRss>http://blog.goneopen.com/2008/11/jquery-and-testing-jsunit-qunit-jsspec-part-3/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>jQuery and testing &#8211; JSUnit, QUnit, JsSpec [Introduction]</title>
		<link>http://blog.goneopen.com/2008/11/jquery-and-testing-jsunit-qunit-jsspec-introduction/</link>
		<comments>http://blog.goneopen.com/2008/11/jquery-and-testing-jsunit-qunit-jsspec-introduction/#comments</comments>
		<pubDate>Wed, 12 Nov 2008 06:32:42 +0000</pubDate>
		<dc:creator>todd</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[BDD]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[jsspec]]></category>
		<category><![CDATA[jsunit]]></category>
		<category><![CDATA[qunit]]></category>
		<category><![CDATA[TDD]]></category>
		<category><![CDATA[test automation pyramid]]></category>
		<category><![CDATA[UnitTesting]]></category>

		<guid isPermaLink="false">http://blog.goneopen.com/2008/11/jquery-and-testing-jsunit-qunit-jsspec-introduction/</guid>
		<description><![CDATA[I had been writing a jQuery parser and then realised once I had spiked it that I hadn&#8217;t actually written any tests. So, these are some results from a spike in unit testing a jQuery plugin. Some background, the plugin is a results viewer from an xml feed from storyq. So, I have run some [...]]]></description>
			<content:encoded><![CDATA[<p>I had been writing a jQuery parser and then realised once I had spiked it that I hadn&#8217;t actually written any tests. So, these are some results from a spike in unit testing a jQuery plugin.</p>

<p>Some background, the plugin is a results viewer from an xml feed from storyq. So, I have run some tests and have results. Now I want to see them in html format. The plugin merely transforms the xml to be displayed using the treeview plugin. I wanted to avoid handing in a json feed formatted specifically for the treeview. I wanted all this to happen client side.</p>

<p>The tests have two aspects:</p>


<ul>
<li>xml loading and parsing into an object</li>
<li>rendering the object into a tree (at that point treeview takes over)<br />
 <br />
In short, I want to test the code underlying this call that returns the <code>feed</code> before populating an <code>&lt;ul id=&quot;tree&quot;&gt;</code> element:</li>
</ul>





<pre>$('#tree').storyq({
    url: 'tests/data/results-01.xml',   
    success: function(feed) {

      $(&quot;#tree&quot;).treeview(); //populate the tree
  
  }    
});
</pre>



<h2>Problem for any framework: sequencing</h2>

<p>Let&#8217;s take a look at what I want as test code. In this code, I want to populate <code>data</code> with the <code>feed</code> variable returned in the <code>success</code> callback. The test can then check for values. Take a look at the code below. When I run the code, I should (ideally) see the sequence of alerts: <code>loaded</code>, <code>start test</code>, <code>end test</code>. Of course, I don&#8217;t. I see start <code>start test</code>, <code>end test</code>, <code>loaded</code> as the sequence. That should be obvious that the callback success hasn&#8217;t been called as yet: javascript is run sequentially. Okay, nothing here is surprising. I laboured this point because any of the frameworks must deal with this problem.</p>



<pre>var data = {};

jQuery(function() {
  $().storyq({
      url: '../../xml/results-01.xml', 
      success: function(feed) {
        data = feed;
        alert('loaded')       
        }
      });
});

function testXML2Object() {
  alert('start test')
  assertEquals(data, {&quot;result&quot;}, &quot;Assume that result is a real/correct object&quot;);
  alert('end test')     
}
</pre>



<h2>Frameworks looked at</h2>

<p>I looked at three frameworks for xml loading and parsing:</p>


<ul>
<li><a href="../jquery-and-testing-jsunit-qunit-jsspec-part-1/"><span class="caps">JSU</span>nit &#8211; Part I</a></li>
<li><a href="../jquery-and-testing-jsunit-qunit-jsspec-part-2/">QUnit &#8211; Part II</a></li>
<li><a href="../jquery-and-testing-jsunit-qunit-jsspec-part-3/">JsSpec &#8211; Part <span class="caps">III</span></a></li>
</ul>



<h2>Conclusions</h2>


<ul>
<li>In short, QUnit and JsSpec are both as easy as the other. <span class="caps">JSU</span>nit seems now to be too heavy given what we now have.</li>
<li>QUnit is a <span class="caps">TDD </span>framework is used by jQuery itself. I suspect it might survive longer. There are no setup/teardown phases.</li>
<li>JsSpec is a <span class="caps">BDD </span>framework and doesn&#8217;t use jQuery at all but can easily be used with JQuery plugins. There are good setup/teardown phases for tests and suites.</li>
<li>Your choice between the two is likely to be your preference between <span class="caps">TDD </span>or <span class="caps">BDD.</span> It probably depends upon which boundaries you want to test and how you want to go about specifying.</li>
</ul>



<h2>What I didn&#8217;t do:</h2>


<ul>
<li>integration with a CI system</li>
<li>cross-browser testing</li>
<li>test with selenium or watir</li>
</ul>

]]></content:encoded>
			<wfw:commentRss>http://blog.goneopen.com/2008/11/jquery-and-testing-jsunit-qunit-jsspec-introduction/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
