<?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>Platformability &#187; Test Driven Development</title>
	<atom:link href="http://blog.caplin.com/tag/test-driven-development/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.caplin.com</link>
	<description>Single Dealer Platforms, Industry Expertise</description>
	<lastBuildDate>Fri, 03 Feb 2012 15:38:56 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>The beauty of small tests</title>
		<link>http://blog.caplin.com/2010/04/15/the-beauty-of-small-tests/</link>
		<comments>http://blog.caplin.com/2010/04/15/the-beauty-of-small-tests/#comments</comments>
		<pubDate>Thu, 15 Apr 2010 11:53:35 +0000</pubDate>
		<dc:creator>Andrew Darnell</dc:creator>
				<category><![CDATA[QA]]></category>
		<category><![CDATA[Agile]]></category>
		<category><![CDATA[Ajax Testing]]></category>
		<category><![CDATA[Dev Tips]]></category>
		<category><![CDATA[Software Engineering]]></category>
		<category><![CDATA[Test Driven Development]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://blog.caplin.com/?p=1342</guid>
		<description><![CDATA[When tests are small, a test failure means just one thing – somewhere in these ten lines of code which are being tested, there is an error.  Ok, sometimes this can mean that there is an error in the test script, or a there is a failure, or change of...]]></description>
			<content:encoded><![CDATA[<p>When tests are small, a test failure means just one thing – somewhere in these ten lines of code which are being tested, there is an error.  Ok, sometimes this can mean that there is an error in the test script, or a there is a failure, or change of expectation, but fundamentally, it pin-points the cause of the failure to a <strong>small</strong> target, which usually means that debugging becomes <strong>trivial</strong>.</p>
<p>When an end to end acceptance test fails, the failure could be due to any one of a large number of source lines or expectations changes across a large body of code.  Debugging may be quick, but often isn&#8217;t.</p>
<p><span id="more-1342"></span></p>
<p>Small tests run faster too! While a typical small test may take 10 milliseconds to run, a large acceptance test may take twenty minutes.</p>
<p>Just a small back of the envelope calculation tells us that if a developer checks in twice a day and saves an hour each time because potential issues had been found before check-in with fast small tests, and the faster feedback, or has reduced their time spent debugging &#8211; that is two hours a day per developer that could be put to better use.</p>
<blockquote><p>2 hours a day * thirty developers * two working weeks = <strong>600 additional hours</strong> per two week iteration available.</p></blockquote>
<p>This is equivalent to adding seven and a half developers to the team!</p>
<p><strong>What value do you get from tests of different sizes?</strong></p>
 <img src="http://blog.caplin.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=1342" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://blog.caplin.com/2010/04/15/the-beauty-of-small-tests/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Agile – Tests = Fragile</title>
		<link>http://blog.caplin.com/2010/04/09/agile-%e2%80%93-tests-fragile/</link>
		<comments>http://blog.caplin.com/2010/04/09/agile-%e2%80%93-tests-fragile/#comments</comments>
		<pubDate>Fri, 09 Apr 2010 14:55:46 +0000</pubDate>
		<dc:creator>Andrew Darnell</dc:creator>
				<category><![CDATA[QA]]></category>
		<category><![CDATA[Agile]]></category>
		<category><![CDATA[Dev Tips]]></category>
		<category><![CDATA[Software Engineering]]></category>
		<category><![CDATA[Test Driven Development]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://blog.caplin.com/?p=1341</guid>
		<description><![CDATA[The nature of agile projects, with lots of small releases mean that there are a lot of test runs to execute if you want to have any confidence in the code and the product. Ignoring this testing just generates projects which will fail – not may fail &#8211; will fail,...]]></description>
			<content:encoded><![CDATA[<p>The nature of agile projects, with lots of small releases mean that there are a lot of test runs to execute if you want to have any confidence in the code and the product.</p>
<p>Ignoring this testing just generates projects which will fail – not may fail &#8211; will fail, <strong>categorically will fail!</strong></p>
<p>There are two sets of tests that are critical here&#8230;</p>
<p><strong>Good unit test coverage and a TDD approach to development</strong> ensure that the rest of the organisation is supplied with product that works as developers expect it to.</p>
<p><strong>Component tests and functional acceptance test</strong>s ensure that the product does what the product owner expects it to.</p>
<ul>
<li>Practically, the only way to do solid testing on new features is to have a stable product.</li>
<li>Practically, the only way to assure a stable product is to either have solid regression testing on each release or to not make any changes.</li>
<li>Practically, the only way to make sure that adequate regression testing is done is to automate the regression tests (unit, component, functional).</li>
</ul>
<p>Without these tests in place, iterating quickly places an impossible to meet burden of verification demand on the testers and product owners, which just gives you a <strong>fragile</strong> process not an <strong>agile</strong> one.</p>
<p><strong> Is your process Agile or Fragile?</strong></p>
 <img src="http://blog.caplin.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=1341" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://blog.caplin.com/2010/04/09/agile-%e2%80%93-tests-fragile/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Tech Talk &#8211; Behaviour Driven Development</title>
		<link>http://blog.caplin.com/2010/03/18/tech-talk-behaviour-driven-development/</link>
		<comments>http://blog.caplin.com/2010/03/18/tech-talk-behaviour-driven-development/#comments</comments>
		<pubDate>Thu, 18 Mar 2010 11:37:32 +0000</pubDate>
		<dc:creator>Ian Alderson</dc:creator>
				<category><![CDATA[Tech Talks]]></category>
		<category><![CDATA[Behaviour Driven Development]]></category>
		<category><![CDATA[Software Engineering]]></category>
		<category><![CDATA[Tech Talk]]></category>
		<category><![CDATA[Test Driven Development]]></category>

		<guid isPermaLink="false">http://blog.caplin.com/?p=1634</guid>
		<description><![CDATA[Last week several of my colleagues and I watched a Google Tech Talk on Beyond Test Driven Development: Behaviour Driven Development, presented by Dave Astels way back in March 2006. Although four years can seem like an eternity within software development, I found this video extremely pertinent to what I...]]></description>
			<content:encoded><![CDATA[<p>Last week several of my colleagues and I watched a <a  href="http://blog.caplin.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3d3dy55b3V0dWJlLmNvbS91c2VyL0dvb2dsZVRlY2hUYWxrcw==">Google Tech Talk</a> on <b>Beyond Test Driven Development: Behaviour Driven Development</b>, presented by <a  href="http://blog.caplin.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL2VuLndpa2lwZWRpYS5vcmcvd2lraS9EYXZlX0FzdGVscw==">Dave Astels</a> way back in March 2006.</p>
<p><object width="480" height="385"><param name="movie" value="http://www.youtube.com/v/XOkHh8zF33o&#038;hl=en_GB&#038;fs=1&#038;"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/XOkHh8zF33o&#038;hl=en_GB&#038;fs=1&#038;" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="480" height="385"></embed></object></p>
<p>Although four years can seem like an eternity within software development, I found this video extremely pertinent to what I find myself doing today. I have been following the principles of <a  href="http://blog.caplin.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL2VuLndpa2lwZWRpYS5vcmcvd2lraS9UZXN0LWRyaXZlbl9kZXZlbG9wbWVudA==">Test Driven Development</a> (TDD) for many years now, however this is the first time I have really delved into <a  href="http://blog.caplin.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL2VuLndpa2lwZWRpYS5vcmcvd2lraS9CZWhhdmlvcl9kcml2ZW5fZGV2ZWxvcG1lbnQ=">Behaviour Driven Development</a> (BDD). I would thoroughly recommend watching <a  href="http://blog.caplin.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3ZpZGVvLmdvb2dsZS5jby51ay92aWRlb3BsYXk/ZG9jaWQ9ODEzNTY5MDk5MDA4MTA3NTMyNCYjMDM4O2VpPXNzV1lTN3o2RXRubS1BYlJqNGptQWcmIzAzODtxPUJleW9uZCtUZXN0K0RyaXZlbitEZXZlbG9wbWVudDorQmVoYXZpb3VyK0RyaXZlbitEZXZlbG9wbWVudCM=">the video</a> if you have 45 minutes to spare, however, if not, I have summarised the notes I took whilst watching it below.</p>
<p><span id="more-1634"></span></p>
<h2>My Notes</h2>
<ul>
<li>BDD is an evolution of TDD. Dave Astels described it as what TDD looks like if it is done well.</li>
<li>When talking about unit tests, what is a unit? Is it a method? Is it a class? The definition of unit is ambiguous.</li>
<li>BDD is attempting to move away from several of the words that Dave Astels believes have negative connotations after their use within TDD:
<ul>
<li>Instead of calling something a test it&#8217;s called a specification or <b>spec</b> for short.</li>
<li>Instead of using assertions we should use <b>expectations</b> instead. Anyone using mock objects will already be familiar with this concept.</li>
</ul>
</li>
<li>One of the key things to avoid is state based testing. Depending on the internal state of an object to verify a particular method works correctly breaks encapsulation, even if the test is intentionally meant to be friendly with the class it&#8217;s testing. This leads to fragile tests and creates a barrier to refactoring.</li>
<li>The focus with RSpec was to make it readable. The writer and reader should not have to remember things like whether the first argument to the assertion is the actual or expected value.</li>
<li>Although Dave Astels jokes that he has until version 1.0 to rename the <code>should</code> method with <code>must</code> it looks like he either lost the argument or changed his mind about it; RSpec is now version 1.3 and <code>should</code> is still being used.</li>
<li>In TDD there is a tendency to create a one-to-one relationship between a class and its test. BDD says that we should be creating specs that verify a particular behaviour, rather than writing tests for each class and its methods. A coverage tool can be used to ensure that all possible code paths have been exercised.
<ul>
<li>The example that was given for this were the specs for <code>EmptyCollection</code> which might be &#8220;should return empty iterator&#8221;, &#8220;should have zero size&#8221; and &#8220;should return is empty true&#8221;.</li>
</ul>
</li>
</ul>
<h2>Some BDD Frameworks</h2>
<ul>
<li><a  href="http://blog.caplin.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3JzcGVjLmluZm8v">RSpec</a> &#8211; The BDD framework for Ruby that Dave Astels is talking about in the video.</li>
<li><a  href="http://blog.caplin.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL2piZWhhdmUub3JnLw==">JBehave</a> &#8211; A BDD framework for Java.</li>
<li><a  href="http://blog.caplin.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3Zpc2lvbm1lZGlhLmdpdGh1Yi5jb20vanNwZWM=">JSpec</a> &#8211; A BDD framework for JavaScript.</li>
<li><a  href="http://blog.caplin.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL2N1a2VzLmluZm8v">Cucumber</a> &#8211; A BDD framework with implementations in various languages, including Ruby, Java, .NET, Flex and web applications.</li>
</ul>
<p>Please <a  href="http://blog.caplin.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL2VuLndpa2lwZWRpYS5vcmcvd2lraS9CZWhhdmlvcl9kcml2ZW5fZGV2ZWxvcG1lbnQjVG9vbHM=">look here</a> for a more comprehensive list.</p>
 <img src="http://blog.caplin.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=1634" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://blog.caplin.com/2010/03/18/tech-talk-behaviour-driven-development/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Pitfalls of Exception expectations in JsUnit</title>
		<link>http://blog.caplin.com/2010/01/29/pitfalls-of-exception-expectations-in-jsunit/</link>
		<comments>http://blog.caplin.com/2010/01/29/pitfalls-of-exception-expectations-in-jsunit/#comments</comments>
		<pubDate>Fri, 29 Jan 2010 12:00:25 +0000</pubDate>
		<dc:creator>Ian Alderson</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[JsCoverage]]></category>
		<category><![CDATA[Mock4JS]]></category>
		<category><![CDATA[Software Engineering]]></category>
		<category><![CDATA[Test Driven Development]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://blog.caplin.com/?p=1084</guid>
		<description><![CDATA[At Caplin we use the JsUnit framework to test our JavaScript code. Over time we have made minor modifications to it, integrating Mock4JS and JSCoverage, as well as adding a few of our own extensions that are sympathetic to our JavaScript coding style, however, by and large, our tests are...]]></description>
			<content:encoded><![CDATA[<p>At Caplin we use the <a  href="http://blog.caplin.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3d3dy5qc3VuaXQubmV0Lw==">JsUnit</a> framework to test our JavaScript code. Over time we have made minor modifications to it, integrating <a  href="http://blog.caplin.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL21vY2s0anMuc291cmNlZm9yZ2UubmV0Lw==">Mock4JS</a> and <a  href="http://blog.caplin.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3NpbGljb25mb3Jrcy5jb20vanNjb3ZlcmFnZS8=">JSCoverage</a>, as well as adding a few of our own extensions that are sympathetic to our JavaScript coding style, however, by and large, our tests are written using plain old JsUnit assertions.</p>
<p>One of the main reasons we were keen to adopt JsUnit five years ago was its similarity to <a  href="http://blog.caplin.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3d3dy5qdW5pdC5vcmcv">JUnit 3</a>. Back then our developers had been using JUnit for a few years, and familiarity of the JsUnit API meant that we could immediately start writing tests. Unfortunately the old adage &#8220;familiarity breeds contempt&#8221; reared its ugly head, and we discovered that our main issue with JsUnit were the occasional, very subtle, differences between it and JUnit. The logic for a test that works in JUnit might not work in JsUnit.<br />
<span id="more-1084"></span><br />
An example of this is highlighted by the test that would be written for the example <code>JobQueue</code> class defined below. Its purpose is to queue JavaScript functions for invocation at some point in the future. The <code>addJob()</code> method employs the <a  href="http://blog.caplin.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL2VuLndpa2lwZWRpYS5vcmcvd2lraS9GYWlsLWZhc3Q=">fast-fail</a> philosophy to throw an exception if the <code>fJobToExecuteLater</code> argument is <code>null</code> or <code>undefined</code>, rather than fail later on when an attempt is made to execute it.</p>
<pre class="brush: jscript; title: ; notranslate">
function JobQueue()
{
   this.m_pQueue = [];
}

JobQueue.prototype.addJob = function(fJobToExecuteLater)
{
   if (fJobToExecuteLater == null) // this is true if it is undefined
   {
      throw new Error(&quot;JobQueue.addJob: Job cannot be null or undefined&quot;);
   }
   this.m_pQueue.push(fJobToExecuteLater);
};

// other methods...
</pre>
<p>The JsUnit test written to verify the behaviour would look something like:</p>
<pre class="brush: jscript; title: ; notranslate">
var g_oJobQueue = null;

function setUp()
{
   g_oJobQueue= new JobQueue();
}

function testAddJobThrowsExceptionIfJobToExecuteLaterIsNull()
{
   try
   {
      g_oJobQueue.addJob(null);
      fail(&quot;Unexpected success invoking addJob() with null job&quot;);
   }
   catch (e)
   {
      // expected exception
   }
}
</pre>
<p>Casting a casual (JUnit 3) glance over this test, everything looks to be in order. The test checks that an exception is thrown if the <code>addJob()</code> method is passed a <code>null</code> argument and remembers to invoke <code>fail()</code> if the exception isn&#8217;t thrown. This latter point is important since if it is omitted then the test will pass regardless of whether an exception is thrown or not.</p>
<p>The equivalent test in Java would work without any problems, however in JavaScript there is a hidden bug within this test logic. Within JUnit the <code>fail()</code> method throws a subclass of <code>Error</code>, which <strong>won’t</strong> be caught by a catch block expecting an Exception. Unfortunately JavaScript has no such distinctions between errors and exceptions, and the call to <code>fail()</code> throws an exception which <strong>will</strong> be caught within the catch block.</p>
<p><strong>Solutions to the Exception expection issue</strong></p>
<p>There are two approaches that we have taken to resolving this issue.</p>
<p><strong>1.</strong> We extended the JsUnit API to add a new assertion method, <code>assertFails()</code>, that encapsulates the logic necessary to ensure that an exception is thrown, and fail if it hasn&#8217;t. It takes three arguments:</p>
<p><strong>i.</strong> A comment to output if the test fails<br />
<strong>ii.</strong> A reference to the function to invoke which is expected to throw an exception, if this doesn&#8217;t throw an exception then the assertion fails<br />
<strong>iii.</strong> The exception that is expected to be thrown (optional, if omitted the assertion just ensures that an exception is thrown)</p>
<p>Using the <code>addJob()</code> test can be rewritten to use <code>assertFails()</code>:</p>
<pre class="brush: jscript; title: ; notranslate">
function testAddJobThrowsExceptionIfJobToExecuteLaterIsNull()
{
   assertFails(&quot;Unexpected success invoking addJob() with null job&quot;,
                   function() {
                      g_oJobQueue.addJob(null);
                   });
}
</pre>
<p><strong>2.</strong> We verify that the exception that is thrown is the one that we expect. This particular approach has been met with trepidation from some of our developers who are concerned that verification of exceptions will lead to fragile test code, prone to break if someone changes the text within an exception (presumably to make it more helpful). There are certainly pros and cons to this, however in my experience it is rare that changes are made to the descriptions passed into the exceptions thrown by our code, and the overhead of these verifications is negligible.</p>
<p>The original test code can be rewritten to assert that the exception is the expected one:</p>
<pre class="brush: jscript; title: ; notranslate">
function testAddJobThrowsExceptionIfJobToExecuteLaterIsNull()
{
   try
   {
      g_oJobQueue.addJob(null);
      fail(&quot;Unexpected success invoking addJob() with null job&quot;);
   }
   catch (e)
   {
      var oExpectedException =
               new Error(&quot;JobQueue.addJob: Job cannot be null or undefined&quot;);
      assertEquals(oExpectedException.toString(), e.toString());
   }
}
</pre>
<p>Alternatively <code>assertFails()</code> can be used as such:</p>
<pre class="brush: jscript; title: ; notranslate">
function testAddJobThrowsExceptionIfJobToExecuteLaterIsNull()
{
   assertFails(&quot;Unexpected success invoking addJob() with null job&quot;,
                   function() {
                      g_oJobQueue.addJob(null);
                   },
                   new Error(&quot;JobQueue.addJob: Job cannot be null or undefined&quot;));
}
</pre>
<p><strong>Conclusion</strong></p>
<p>This article is not intended to be a criticism of JsUnit. The issue highlighted here is simply due to a difference between the JavaScript and Java languages with respect to their exception handling which led to some tests being marked as successful when they shouldn&#8217;t. Over the last five years I have found that JsUnit has been reliable unit testing framework and, combined with Mock4JS and a TDD philosophy, it can form the solid foundations from which enterprise level JavaScript APIs and applications can be built.</p>
<p>Since we made our decision to use JsUnit we have never really looked back. So far it has managed to do everything that we have needed from it. However if you are looking into unit testing your JavaScript, then <a  href="http://blog.caplin.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL2VuLndpa2lwZWRpYS5vcmcvd2lraS9MaXN0X29mX3VuaXRfdGVzdGluZ19mcmFtZXdvcmtzI0phdmFTY3JpcHQ=">this list of JavaScript unit testing frameworks</a> should be a good starting point to uncover one that is suitable for you. Just remember, it doesn&#8217;t matter which framework you choose, you need to be aware of the subtle nuisances of JavaScript, compared to any other languages you might be familiar with, to avoid the sort of trap that we fell into.</p>
 <img src="http://blog.caplin.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=1084" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://blog.caplin.com/2010/01/29/pitfalls-of-exception-expectations-in-jsunit/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>How to dynamically create a class definition for use with Mock4JS</title>
		<link>http://blog.caplin.com/2009/04/16/how-to-dynamically-create-a-class-definition-for-use-with-mock4js/</link>
		<comments>http://blog.caplin.com/2009/04/16/how-to-dynamically-create-a-class-definition-for-use-with-mock4js/#comments</comments>
		<pubDate>Thu, 16 Apr 2009 17:00:28 +0000</pubDate>
		<dc:creator>Phil Leggetter</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[ajax]]></category>
		<category><![CDATA[Ajax Testing]]></category>
		<category><![CDATA[Mock4JS]]></category>
		<category><![CDATA[Software Engineering]]></category>
		<category><![CDATA[Test Driven Development]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://blog.caplin.com/?p=187</guid>
		<description><![CDATA[Mock4JS is a really useful unit testing helper library that allows you to create mocks of your JavaScript classes. What it doesn&#8217;t presently support is mocking of objects that you can&#8217;t create an instance of yourself using new Class() or of objects that are dynamically created and have functions appended...]]></description>
			<content:encoded><![CDATA[<p><a  href="http://blog.caplin.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL21vY2s0anMuc291cmNlZm9yZ2UubmV0Lw==">Mock4JS</a> is a really useful unit testing helper library that allows you to create mocks of your JavaScript classes. What it doesn&#8217;t presently support is mocking of objects that you can&#8217;t create an instance of yourself using <code>new Class()</code> or of objects that are dynamically created and have functions appended to them.</p>
<p><span id="more-187"></span></p>
<h3>What do I mean by not being able to &#8220;create an instance of yourself using <code>new Class()</code>&#8220;?</h3>
<pre class="javascript">MyClassDefinition = function()
{
};

MyClassDefintion.prototype.myFunction = function()
{
    // do some stuff
};
MyClassDefinition = new MyClassDefinition();</pre>
<p>Here we lose the ability to do <code>new MyClassDefinition();</code></p>
<h3>What do I mean by &#8220;objects that are dynamically created&#8221;?</h3>
<pre class="javascript">// create an object using the object literal notation
var oObj = {};

// dynamically append a function
oObj.myFunction = function()
{
    // do some stuff
};</pre>
<p>Code written in both these ways make it more difficult to create a mock using Mock4JS because it expects a function reference to be passed to the mock method call.</p>
<p>A way around this is to dynamically create a definition from the object. This is done using the following piece of code:</p>
<pre class="javascript">function createMockDefinition(oObject)
{
    var oMockedDefinition = new Function();
    for( var x in oObject )
    {
        // Only add functions to the dynamically created prototype
        if( typeof oObject[ x ] == "function" )
        {
            oMockedDefinition.prototype[x] = function(){};
        }
    }
    return oMockedDefinition;
};</pre>
<p>With the above code we have now created a class definition that we can pass to the Mock4JS <code>mock()</code> function.</p>
<pre class="javascript">function myTest()
{
    var oObjectIWantToTest = {};
    oObjectIWantToTest.functionIWantToTest = function(){};

    var oMyMockDefinition = createMockDefinition( oObjectIWantToTest );
    var oMyMock = mock( oMyMockDefinition );
    var oMyMockProxy = oMyMock.proxy();

    // setup expectations
    oMyMock.expects(once()).functionIWantToTest("myArgument");

    // call function and execute mock method.
    oMyMockProxy.functionIWantToTest("myArgument");

    // Finally, verify the expected mock methods have been called.
    // If not, an exception will be thrown.
    Mock4JS.verifyAllMocks();
};</pre>
 <img src="http://blog.caplin.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=187" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://blog.caplin.com/2009/04/16/how-to-dynamically-create-a-class-definition-for-use-with-mock4js/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

