<?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; Unit Testing</title>
	<atom:link href="http://blog.caplin.com/tag/unit-testing/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.caplin.com</link>
	<description>SWIMMING WITH TECHNOLOGY</description>
	<lastBuildDate>Sun, 29 Aug 2010 11:55:00 +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>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[Quality Assurance]]></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 expectation, but fundamentally, it pin-points [...]]]></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[Quality Assurance]]></category>
		<category><![CDATA[Agile]]></category>
		<category><![CDATA[Dev Tips]]></category>
		<category><![CDATA[Software Engineering]]></category>
		<category><![CDATA[Test Driven Development]]></category>
		<category><![CDATA[Testing]]></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, categorically will fail! There are [...]]]></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>Testing APIs for Backwards Compatibility</title>
		<link>http://blog.caplin.com/2010/02/19/testing-apis-for-backwards-compatibility/</link>
		<comments>http://blog.caplin.com/2010/02/19/testing-apis-for-backwards-compatibility/#comments</comments>
		<pubDate>Fri, 19 Feb 2010 17:07:22 +0000</pubDate>
		<dc:creator>Ian Alderson</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Quality Assurance]]></category>
		<category><![CDATA[Caplin Trader]]></category>
		<category><![CDATA[Software Engineering]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://blog.caplin.com/?p=1137</guid>
		<description><![CDATA[A couple of weeks ago, I wrote about Agile Framework Development and the various techniques that we have used here at Caplin to build our APIs in a way that is sympathetic to agile methodologies. One of the key problems with the iterative development of an API is how to ensure that it remains backwardly [...]]]></description>
			<content:encoded><![CDATA[<p>A couple of weeks ago, I wrote about <a  href="http://blog.caplin.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=LzIwMTAvMDIvMDIvYWdpbGUtZnJhbWV3b3JrLWRldmVsb3BtZW50Lw==">Agile Framework Development</a> and the various techniques that we have used here at Caplin to build our APIs in a way that is sympathetic to agile methodologies. One of the key problems with the iterative development of an API is how to ensure that it remains backwardly compatible. Although each new release of an API is focussed on providing more functionality, easier use, or increased robustness for its users, those same users want their existing code to continue working when they upgrade.</p>
<p>This article addresses the issue of how to identify, with confidence, whether an API is backwardly compatible or not. As I mentioned previously  there are times when an API is just too incorrect to be kept, however the decision for a breaking change must be a deliberate one &#8211; not an accidental one that is typically only discovered when the users of the API find that their existing code no longer works.</p>
<p><span id="more-1137"></span></p>
<h2>Preventing Breaking Changes</h2>
<p>It is easy to tell developers that they should keep an API backwardly compatible, however even with the best of intentions it is possible to introduce subtle changes to the behaviour, particularly if you are refactoring collaborating classes that may not directly be part of the public interface. Every developer should be aware of the importance of keeping the API backwardly compatible, however this cannot be relied upon. After all, every developer should be striving to keep their code bug free, but we still write tests to verify this.</p>
<p>The solution is to detect any API changes before it is released, preferably in an automated fashion, so that it can be fixed. The problem is how to know whether an API has actually changed.</p>
<p><b>Compilation</b></p>
<p>A starting point for a compiled language, such as Java, is whether some code that was written against the old API still compiles against the new one. Any interfaces that have changed, including those with changes to method signatures and so on, will be flagged up immediately by the compiler. However this is no guarantee that the behaviour of the API hasn&#8217;t changed, and this simple verification isn&#8217;t available for non-compiled languages like JavaScript.</p>
<p><b>Unit Tests</b></p>
<p>The next obvious tool to detect a change are unit tests. The problem with this is that the unit tests will also be updated when the underlying code is modified. The fact that a unit test for a public API is having to be changed should start alarm bells ringing for the developer making the change; are the changes that they are making backwardly compatible or not? Again, however, the problem with this is that sometimes the changes can be subtle and the breaking change may be missed, particularly if the changes are made to a collaborating class rather that the one that is directly part of the public API.</p>
<p><b>Acceptance Tests</b></p>
<p>Acceptance tests can be used to detect breaking changes in a similar way to the unit tests. My problem with this approach is that they tend to be less granular and therefore susceptible to missing subtle breaking changes. Ideally I want my tests for API changes to have excellent coverage and to test all possible code paths, which is usually something that isn&#8217;t done by acceptance tests.</p>
<p><b>API Tests</b></p>
<p>Taking a step back, it does look like unit tests seem a good match for solving this particular problem. The only issue is that the unit tests will be modified when the code is changed, which may mask any breaking changes that have unwittingly been introduced. However we do have a set of unit tests perfectly suited to this which haven&#8217;t been modified, those from our previous release. We know that they proved the API for that release worked, so if the same tests pass against the new code it stands to reason that we should be backwardly compatible.</p>
<h2>Creating API Tests</h2>
<p>At Caplin we have a set of API tests that are a specialised group of unit tests aimed at verifying that all aspects and behaviours of the public API have not changed. They are usually a subset of the unit tests written for a particular library.</p>
<p><b>Only Running the API Tests</b></p>
<p>The first problem is specifying which tests are those for the API and which are standard unit tests. This is important since the implementation of collaborating classes can be changed without impacting the public API. As a result the old unit tests for refactored collaborating classes may now fail, however these are unimportant if they have no impact on the API.</p>
<p>Within our JavaScript unit tests we have added the ability to flag a particular test as an API test. We can specify whether we want to run only the API tests or all the tests, including the API tests.</p>
<p>Alternate approaches would be to create different test suites for the API and standard tests, or perhaps to use a custom annotation like <code>@ApiTest</code> rather than <code>@Test</code> in <a  href="http://blog.caplin.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3d3dy5qdW5pdC5vcmcv">JUnit 4</a>.</p>
<p><b>Dangers With Mocking</b></p>
<p>One danger with testing APIs is the use of <a  href="http://blog.caplin.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3d3dy5tb2Nrb2JqZWN0cy5jb20v">mock objects</a>. Mock objects combined with <a  href="http://blog.caplin.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL2VuLndpa2lwZWRpYS5vcmcvd2lraS9EZXBlbmRlbmN5X2luamVjdGlvbg==">dependency injection</a> provide a powerful way to test the logic of a particular piece of code as a single unit, without having to rely on the real logic in the collaborating objects. Instead the mock object acts as a replacement for the real collaborating object, verifying that it is invoked in the correct way and returns the appropriate values.</p>
<p>The danger is that changes to the collaborating object, such as the addition of a statement that throws a runtime exception if an argument is null, will not be emulated by the mock object. These problems are not insurmountable, however you need to be aware of the potential risks. In the case above there is a reasonable argument that there should have been an API test written for the collaborating class that demonstrated that the arguments could have been null previously which would now fail.</p>
<p><b>Getting the API Tests</b></p>
<p>At Caplin we upload the API tests to our <a  href="http://blog.caplin.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL21hdmVuLmFwYWNoZS5vcmcv">Maven</a> repository along with the other build artifacts for our libraries. For example when we release version 1.0 of a library, the API tests for 1.0 are uploaded to Maven. When we are building version 1.1 of the library we download the API tests for 1.0 to verify that the API has not changed.</p>
<p>Alternatives to getting the tests from Maven are to use another dependency management system, to pull the tests from a branch or label from source control, or even copying them from a network share.</p>
<p><b>Updating API Tests</b></p>
<p>It is possible that a public API hasn&#8217;t changed, however the API test for it fails. The reason for this could be that the interaction between the API method and its collaborating objects, particularly if they have been mocked out, have changed, and the test expectations are no longer valid. As a result the code for the API tests will need to be updated.</p>
<p>This change needs to be managed via source control, with a new version of the API tests pushed into Maven, or wherever they are being stored.</p>
<p><b>Backward Compatibility With Older Versions</b></p>
<p>At the moment we are only checking backward compatibility against the previous version of the API. I believe that if an API is compatible with the previous one, and that previous one was compatible with the one before, and so on, then it stands to reason that the current API should be compatible with the oldest one.</p>
<h2>Conclusions</h2>
<p>We are still in the early days of trying out this approach, however the early signs have been encouraging.</p>
<p>Ultimately a large amount of the responsibility still lies with developers to ensure that their code changes to a public API maintain backwards compatibility. The API tests are a safety net that gives confidence that it really is backwardly compatible and provide an early warning of any breaking changes, allowing them to be fixed before a release is made.</p>
<p>Any breaking changes within an API must be a conscious decision, not an inadvertent one.</p>
 <img src="http://blog.caplin.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=1137" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://blog.caplin.com/2010/02/19/testing-apis-for-backwards-compatibility/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[Development]]></category>
		<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 written using plain old JsUnit [...]]]></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;">
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;">
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>&nbsp;&nbsp;&nbsp;<strong>i.</strong> A comment to output if the test fails<br />
&nbsp;&nbsp;&nbsp;<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 />
&nbsp;&nbsp;&nbsp;<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;">
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;">
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;">
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[Development]]></category>
		<category><![CDATA[ajax]]></category>
		<category><![CDATA[Ajax Testing]]></category>
		<category><![CDATA[JavaScript]]></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 to them. What do I [...]]]></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" name="code">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" name="code">// 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" name="code">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" name="code">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>
