<?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>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>Unit Testing Servlets: A simple test for a complex servlet</title>
		<link>http://blog.caplin.com/2011/12/09/unit-testing-servlets-a-simple-test-for-a-complex-servlet/</link>
		<comments>http://blog.caplin.com/2011/12/09/unit-testing-servlets-a-simple-test-for-a-complex-servlet/#comments</comments>
		<pubDate>Fri, 09 Dec 2011 15:30:58 +0000</pubDate>
		<dc:creator>Andy Berry</dc:creator>
				<category><![CDATA[QA]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://blog.caplin.com/?p=7476</guid>
		<description><![CDATA[Testing Java servlets reliably can often be difficult. Generally the main business logic is contained in a different class which can be tested in isolation, but in some cases it is necessary to have some logic in the servlet itself. It&#8217;s also nice to have a quick sanity check that the servlet...]]></description>
			<content:encoded><![CDATA[<p>Testing Java servlets reliably can often be difficult. Generally the main business logic is contained in a different class which can be tested in isolation, but in some cases it is necessary to have some logic in the servlet itself. It&#8217;s also nice to have a quick sanity check that the servlet is loading as it should be and generating the correct responses.</p>
<p>Servlets, like many other things that have several reliant services, can be difficult to test as they tend to require a full web stack, such as an application server and database. These reliant services can often fail resulting in unreliable tests, which can be a nightmare in a continuous integration system. Thankfully the Jetty servlet tester can help overcome these issues.</p>
<h2>Jetty Servlet Tester</h2>
<p>The Jetty servlet tester library uses an embedded Jetty application server and can be used to write unit tests that test the functionality of our application server while mocking out any services the tests rely on.</p>
<p>Using the servlet tester is pretty straightforward. First, make sure the servlet tester jar is on the Java classpath either by manually adding it or adding it as a build dependency; you can find it in the Maven central repository <a  href="http://blog.caplin.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL212bnJlcG9zaXRvcnkuY29tL2FydGlmYWN0L29yZy5tb3J0YmF5LmpldHR5L2pldHR5LXNlcnZsZXQtdGVzdGVy">here</a>.</p>
<p>Using Maven, Gradle or similar to add it to the classpath is by far the easier option as there are some transitive dependencies, such as the servlet API, that the servlet tester relies on.</p>
<p>Once the jars are on our classpath we can start writing some tests.</p>
<p style="text-align: center;"><a  href="http://blog.caplin.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL2Jsb2cuY2FwbGluLmNvbS93cC1jb250ZW50L3VwbG9hZHMvalVuaXQudGVzdF8ucG5n"><img class="aligncenter size-medium wp-image-7489" title="jUnit.test" src="http://blog.caplin.com/wp-content/uploads/jUnit.test_-300x269.png" alt="jUnit.test" width="300" height="269" /></a></p>
<h2>Writing Tests</h2>
<div id="_mcePaste">For this example I have created a very complex servlet &#8211; it simply responds to every request with &#8220;It works&#8221; and sets a header field that we can test.</div>
<div>Using the servlet tester is pretty straightforward. In our test we first create the server and add our servlet to it, specifying the context for the servlet.</div>
<div id="_mcePaste">
<pre class="brush: java; title: ; notranslate">
ServletTester servletTester = new ServletTester();
servletTester.addServlet(com.caplin.example.MyServlet.class, &quot;/validUrl&quot;);
servletTester.start();
</pre>
</div>
<div id="_mcePaste">We then create a request to send to the servlet, make the request, and retrieve the content.</div>
<div id="_mcePaste">
<pre class="brush: java; title: ; notranslate">
HttpTester request = new HttpTester();
request.setMethod(&quot;GET&quot;);
request.setURI(&quot;/validUrl&quot;);
request.setVersion(&quot;HTTP/1.0&quot;);

HttpTester response = new HttpTester();
response.parse(servletTester.getResponses(request.generate()));
</pre>
</div>
<div id="_mcePaste">Once we have the response we can then perform several checks on the response code, the content and various other headers.</div>
<div id="_mcePaste">
<pre class="brush: java; title: ; notranslate">
assertEquals(200,response.getStatus());
assertEquals(&quot;It works&quot;,response.getContent());
assertEquals(&quot;yes&quot;,response.getHeader(&quot;did-it-work&quot;));
</pre>
</div>
<p>There we have it, a quick test for our very complex servlet. These unit tests can then be extended to work with real life scenarios, perhaps reading expected content from a file, mocking out any other services such as databases and still run quickly and reliably.</p>
<p>You can download the example source code including a servlet tester utility class <a  href="http://blog.caplin.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=L3dwLWNvbnRlbnQvdXBsb2Fkcy9TZXJ2bGV0VGVzdGVyRXhhbXBsZS56aXA=">here</a>.</p>
<p><a  href="http://blog.caplin.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL2Jsb2cuY2FwbGluLmNvbS93cC1jb250ZW50L3VwbG9hZHMvMDY4Xy1fVW5pdC10ZXN0aW5nMS5wbmc="><img class="aligncenter size-full wp-image-7493" title="Unit-testing" src="http://blog.caplin.com/wp-content/uploads/068_-_Unit-testing1.png" alt="Unit-testing" width="500" height="647" /></a></p>
<p style="text-align: center;">
 <img src="http://blog.caplin.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=7476" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://blog.caplin.com/2011/12/09/unit-testing-servlets-a-simple-test-for-a-complex-servlet/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Taking C unit testing to the next level</title>
		<link>http://blog.caplin.com/2010/10/11/taking-c-unit-testing-to-the-next-level/</link>
		<comments>http://blog.caplin.com/2010/10/11/taking-c-unit-testing-to-the-next-level/#comments</comments>
		<pubDate>Mon, 11 Oct 2010 09:29:11 +0000</pubDate>
		<dc:creator>Dom</dc:creator>
				<category><![CDATA[QA]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://blog.caplin.com/?p=3916</guid>
		<description><![CDATA[In terms of formalised unit testing, we were fairly late to start generating repeatable test cases for our C products. Sure we wrote code to test our new features but they were just thrown away once the code was working. Even so, over the past 6 years or so, as...]]></description>
			<content:encoded><![CDATA[<p>In terms of formalised unit testing, we were fairly late to start generating repeatable test cases for our C products. Sure we wrote code to test our new features but they were just thrown away once the code was working.</p>
<p>Even so, over the past 6 years or so, as we&#8217;ve added features and fixed bugs we&#8217;ve diligently been adding tests. We&#8217;ve now got to the stage where we&#8217;ve got thousands of unit tests and hundreds of integration tests. For some products, the size of the test code exceeds the product code, admittedly not to the scale of <a  href="http://blog.caplin.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3d3dy5zcWxpdGUub3JnL3Rlc3RpbmcuaHRtbA==">Sqlite</a> though.</p>
<p>To do this effectively, we&#8217;ve adopted <a  href="http://blog.caplin.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL2NoZWNrLnNmLm5ldA==">check</a> as our unit test framework and have incorporated the validating mock library from <a  href="http://blog.caplin.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3d3dy5sYXN0Y3JhZnQuY29tL2NncmVlbi5waHA=">cgreen</a> as well as our own mock JVM implementation that performs validation over the JNI interface. We&#8217;ve even changed our coding style, changing it so that the links between compilation units can be replaced at run time allowing release binary testing which is a huge confidence boost over the traditional C testing method of producing an individual binary for testing each compilation unit.</p>
<p><span id="more-3916"></span></p>
<h4>Testing the Released Binary</h4>
<p>Testing the released binary is a neat idea (subject to usual caveats of how to obtain <a  href="http://blog.caplin.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3d3dy5uZXR3b3JrLXRoZW9yeS5jby51ay9kb2NzL2djY2ludHJvL2djY2ludHJvXzgxLmh0bWw=">coverage</a>) &#8211; it means that you&#8217;re delivering to your end user compiled code that has actually been executed and tested as opposed to trusting the compiler not to change something between the test compile and the release compile (or more likely, some preprocessor macro changing the code path). Testing the release binary is something that we do with our .NET and Java products and so it would be great if we could do the same thing with our C products without needing to rewrite them all.</p>
<p>Coming across <a  href="http://blog.caplin.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3d3dy50eXBlbW9jay5jb20vaXNvbGF0b3JwcC1wcm9kdWN0LXBhZ2U=">TypeMock</a> which promises this functionality for Windows led me to think about how you could achieve the same thing on a Linux system and integrate it into the rest of our test tools.</p>
<p>What you need to do may be inherently non-portable and given that we need to build for so many platforms it may not be something that we pursue, but it&#8217;s an interesting thought exercise. So here are my thoughts on the ways it could be implemented.</p>
<p>The high level concepts that we need when testing on a release binary involve overriding the implementation with mocks and trapping changes to any global variables. Since we&#8217;ve already got a mock framework we can call that when we&#8217;ve performed the appropriate traps.</p>
<p>My initial thoughts were around manipulating the ELF relocations in the binary to point to mock functions, however I suspect that for running multiple test cases the overhead of reloading the binary and performing the manipulations may be excessive.</p>
<p>My current thoughts are revolving using the functionality present in <a  href="http://blog.caplin.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?url=aHR0cDovL3d3dy5nbnUub3JnL3NvZnR3YXJlL2dkYi8=">gdb</a>. With gdb you can trap access to global variables using watches and stop execution using breakpoints. If we can intercept these traps and call our mocks we&#8217;ve achieved our aim.  The functionality of adding breakpoints and watches appears to be exposed in libgdb which means that we should be able to do this in a portable way.</p>
<p>Performing unit testing on the release binary opens up a new range of testing strategies and would allow the testing of legacy code which is usually considered unviable for testing. Once the test coverage is in place, the code can be safely refactored to a more testable design.</p>
<p>Should I get a chance to try out this technique, I&#8217;ll report back, hopefully with an open source project for all to use.</p>
 <img src="http://blog.caplin.com/wp-content/plugins/wordpress-feed-statistics/feed-statistics.php?view=1&post_id=3916" width="1" height="1" style="display: none;" />]]></content:encoded>
			<wfw:commentRss>http://blog.caplin.com/2010/10/11/taking-c-unit-testing-to-the-next-level/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<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>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[QA]]></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...]]></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><strong>Compilation</strong></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><strong>Unit Tests</strong></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><strong>Acceptance Tests</strong></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><strong>API Tests</strong></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><strong>Only Running the API Tests</strong></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><strong>Dangers With Mocking</strong></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><strong>Getting the API Tests</strong></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><strong>Updating API Tests</strong></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><strong>Backward Compatibility With Older Versions</strong></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[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>

