<?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>Bugfree.dk - Ronnie Holm&#039;s blog &#187; Testing</title>
	<atom:link href="http://www.bugfree.dk/blog/tag/testing/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.bugfree.dk/blog</link>
	<description>Not anti-anything, just pro-quality</description>
	<lastBuildDate>Wed, 08 Sep 2010 13:57:28 +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>Unit testing LINQ to SQL using TypeMock</title>
		<link>http://www.bugfree.dk/blog/2010/05/04/unit-testing-linq-to-sql-using-typemock/</link>
		<comments>http://www.bugfree.dk/blog/2010/05/04/unit-testing-linq-to-sql-using-typemock/#comments</comments>
		<pubDate>Tue, 04 May 2010 19:23:00 +0000</pubDate>
		<dc:creator>Ronnie Holm</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Tool]]></category>

		<guid isPermaLink="false">http://www.bugfree.dk/blog/?p=1050</guid>
		<description><![CDATA[Recent months have brought about a proliferation of mocking frameworks that mocks what more traditional framework like Rhino Mocks cannot. Instead of creating and loading a mock implementation at runtime, the new breed of mocking frameworks hooks into the CLR to intercept and redirect calls. This opens up virtually every aspect of a class to [...]]]></description>
			<content:encoded><![CDATA[<p>Recent months have brought about a proliferation of mocking frameworks that mocks what more traditional framework like <a href="http://www.ayende.com/projects/rhino-mocks.aspx">Rhino Mocks</a> cannot. Instead of creating and loading a mock implementation at runtime, the new breed of mocking frameworks hooks into the CLR to <a href="http://www.bugfree.dk/blog/2009/02/11/an-example-of-unit-testing-using-typemock">intercept and redirect calls</a>. This opens up virtually every aspect of a class to mocking, which is useful for testing code not written with explicit testability in mind. Until recently, <a href="http://site.typemock.com/typemock-isolator-product">TypeMock</a> was the only mocking framework around that took the latter approach, but it’s now being challenged by <a href="http://research.microsoft.com/en-us/projects/moles">Moles</a> from Microsoft Research and <a href="http://www.telerik.com/products/mocking.aspx">JustMock</a> from Telerik.</p>
<h4>Why traditional dependency-breaking techniques come short</h4>
<p>After watching a screencast on how to <a href="http://www.dimecasts.net/Casts/CastDetails/170">use Moles to unit test LINQ to SQL</a> without hitting the database, I thought it would be interesting to do the same with TypeMock. But first, let’s make sure we understand why traditional dependency-breaking techniques come short in testing LINQ to SQL. Assuming we want to put a repository under test, our goal is to mock how it accesses the database. Here’s a simple implementation of a repository that queries the Employee table of the <a href="http://sqlserversamples.codeplex.com">AdventureWorks</a> database:</p>
<pre class="prettyprint lang-cs">    public class EmployeeRepository {
        public List&lt;Employee&gt; GetEmployeesByHireDate(DateTime start, DateTime end) {
            using (var ctx = new AdventureWorksDataContext())
                return (from e in ctx.Employees
                        where e.HireDate &gt;= start &amp;&amp; e.HireDate &lt;= end
                        select e).ToList();
        }
    }
</pre>
<p>All calls to the database are routed through the AdventureWorksDataContext generated by Visual Studio. To mock access to the database, we therefore have to mock part of the data context. Easier said than done, though, for the context doesn’t expose an interface that a fake can implement. In addition, the tables are accessed through properties on the context that return a type of <a href="http://msdn.microsoft.com/en-us/library/bb358844">Table&lt;TEntity&gt;</a>. Unfortunately, the constructor of Table&lt;TEntity&gt; is internal and the class itself is sealed, eliminating the hope of instantiating or subclassing the type by traditional means:</p>
<pre class="prettyprint lang-cs">    public sealed class Table&lt;TEntity&gt; : IQueryProvider,
            ITable, IListSource, ITable&lt;TEntity&gt;, IQueryable&lt;TEntity&gt;,
            IEnumerable&lt;TEntity&gt;, IQueryable, IEnumerable
            where TEntity : class {
        internal Table(DataContext context, MetaTable metaTable) {
            ...
        }
    }</pre>
<p>For an example of how the data context itself creates an instance of Table&lt;TEntity&gt;, take a look at the Employees property on the AdventureWorksDataContext. It relies on the GetTable&lt;Employee&gt; method on the DataContext class to create an instance of Table&lt;Employee&gt;. Despite its constructors being internal, the GetTable&lt;TEntity&gt; method has no trouble constructing an instance of the Table&lt;TEntity&gt; type, as they both reside in the System.Data.Linq assembly:</p>
<pre class="prettyprint lang-cs">    public partial class AdventureWorksDataContext : DataContext {
        public Table&lt;Employee&gt; Employees {
            get {
                return GetTable&lt;Employee&gt;();
            }
        }
    }</pre>
<h4>How to break the unbreakable</h4>
<p>The design of LINQ to SQL leaves us short of a traditional testing seam, as <a href="http://www.amazon.com/Working-Effectively-Legacy-Robert-Martin/dp/0131177052">Michael Feathers</a> would phrase it; a place at which we can alter the behavior of a program without editing in that place. This explains why, with LINQ to SQL, traditionally we’ve had to test against a real database with all its constraints, making our tests brittle, slow, and painful to write and maintain. With the new breed of mocking frameworks the issues of not being able to subclass or not being able to call an internal constructor go away (and new issues take their place). Regardless, here’s how to write a unit test for the CustomerRepository that doesn’t hit the database:</p>
<pre class="prettyprint lang-cs">    [TestClass]
    public class CustomerRepositoryTest {
        private EmployeeRepository _repository;

        [TestInitialize]
        public void Initialize() {
            _repository = new EmployeeRepository();

            var fakeEmployees = new List&lt;Employee&gt; {
                new Employee {EmployeeID = 1, HireDate = new DateTime(2004, 12, 1)},
                new Employee {EmployeeID = 2, HireDate = new DateTime(2006, 7, 1)},
                new Employee {EmployeeID = 3, HireDate = new DateTime(2009, 3, 1)}
            }.AsQueryable();

            var fakeDataContext = Isolate.Fake.Instance&lt;AdventureWorksDataContext&gt;();
            Isolate.Swap.NextInstance&lt;AdventureWorksDataContext&gt;().With(fakeDataContext);

            // var fakeEmployeeTable = Isolate.Fake.Instance&lt;Table&lt;Employee&gt;&gt;();
            // Isolate.WhenCalled(() =&gt; fakeDataContext.Employees).WillReturn(fakeEmployeeTable);
            // Isolate.WhenCalled(() =&gt; fakeEmployeeTable).WillReturnCollectionValuesOf(fakeEmployees);
            // or by transitivity
            Isolate.WhenCalled(() =&gt; fakeDataContext.Employees).WillReturnCollectionValuesOf(fakeEmployees);
        }

        [TestMethod]
        public void GetEmployeesByHireDate_should_return_hires_from_2008_until_present() {
            var employees = _repository.GetEmployeesByHireDate(new DateTime(2008, 1, 1), DateTime.Now);
            Assert.AreEqual(1, employees.Count());
            Assert.AreEqual(3, employees[0].EmployeeID);
        }
    }
</pre>
<p>The test method itself looks exactly as if we’d been testing against a real database. The difference lies in the Initialize method, where we setup the fake data context and database contents. We instruct TypeMock to return the fake context in place of the real one inside EmployeeRepository. And whenever someone calls the Employees property on the fake context, we have TypeMock intercept the call and return a fake collection of type <a href="http://msdn.microsoft.com/en-us/library/bb351562.aspx">IQueryable&lt;Employee&gt;</a>. We could’ve returned an instance of Table&lt;Employee&gt;, which implements IQueryable&lt;Employee&gt;, but in this case returning the collection is simpler and sufficient. Had we had more methods on our repository, we likely would’ve added additional rows to the Employee table and populated more of its columns.</p>
<p><a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save"><img src="http://www.bugfree.dk/blog/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a> </p>]]></content:encoded>
			<wfw:commentRss>http://www.bugfree.dk/blog/2010/05/04/unit-testing-linq-to-sql-using-typemock/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>The given-expect testing pattern</title>
		<link>http://www.bugfree.dk/blog/2010/04/25/the-given-expect-testing-pattern/</link>
		<comments>http://www.bugfree.dk/blog/2010/04/25/the-given-expect-testing-pattern/#comments</comments>
		<pubDate>Sun, 25 Apr 2010 20:31:58 +0000</pubDate>
		<dc:creator>Ronnie Holm</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[SharePoint]]></category>
		<category><![CDATA[Asp.Net]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Testing]]></category>

		<guid isPermaLink="false">http://www.bugfree.dk/blog/?p=1047</guid>
		<description><![CDATA[I was watching Brett Schuchert’s TDD screencast on implementing the shunting yard algorithm in C#. In it Brett builds up his tests in a style I hadn’t come across before. Each test is expressed as a given-expect statement. A pattern that is particularly useful in situations in which a class has a main method that [...]]]></description>
			<content:encoded><![CDATA[<p>I was watching <a href="http://schuchert.wikispaces.com">Brett Schuchert</a>’s TDD <a href="http://vimeo.com/album/210446">screencast</a> on implementing the <a href="http://en.wikipedia.org/wiki/Shunting-yard_algorithm">shunting yard algorithm</a> in C#. In it Brett builds up his tests in a style I hadn’t come across before. Each test is expressed as a given-expect statement. A pattern that is particularly useful in situations in which a class has a main method that accepts an open-ended number of dissimilar inputs.</p>
<p>I found the given-expect pattern useful in testing a piece of code that I was working on this week. I was refactoring and adding tests around an ASP.NET control adapter that makes SharePoint 2007 pages more XHTML compliant. I wanted to reuse the transformations outside the control adapter and hence ended up moving the transformation logic to a new class. It accepts possibly malformed HTML and relies on heuristics of the <a href="http://htmlagilitypack.codeplex.com">HTML Agility Pack</a> to build a DOM off of it. I can then query the DOM, looking for known violations, and patch them before returning XHTML to the caller.</p>
<pre class="prettyprint lang-cs">    public class HtmlToXHtmlTransformer {
        private readonly HtmlDocument _document;

        public HtmlToXHtmlTransformer(string html) {
            _document = new HtmlDocument();
            _document.DetectEncoding(new StringReader(html));
            _document.LoadHtml(html);
        }

        private void Transform(string xpath, Action&lt;HtmlNode&gt; nodeMatch) {
            var nodes = _document.DocumentNode.SelectNodes(xpath);
            if (nodes != null)
                foreach (var node in nodes)
                    nodeMatch.Invoke(node);
        }

        private void FixDuplicateBorderAttributeOnSPGridViewControl() {
            Transform(&quot;//table[count(@border)=2]&quot;, node =&gt; node.Attributes.Remove(&quot;border&quot;));
        }

        public string Transform() {
            FixDuplicateBorderAttributeOnSPGridViewControl();
            _document.OptionWriteEmptyNodes = true;
            return _document.DocumentNode.WriteTo();
        }
    }</pre>
<p>The complete HtmlToXHtmlTransformer collects a dozen transformations. Its Transform method is what we want to call with various HTML fragments to verify that they come out as XHTML. For this purpose, we might do the tests as <a href="http://msdn.microsoft.com/en-us/library/ms182527.aspx">Visual Studio data-driven tests</a> that read their input and output from a text file. But in most cases I prefer traditional tests, so I can describe the purpose of a test with a descriptive method name and possibly a comment.</p>
<pre class="prettyprint lang-cs">
    [TestClass]
    public class HtmlToXHtmlTransformerTest {
        private string _result;

        [TestMethod]
        public void Must_selfclose_nodes_when_allowed() {
            Given(&quot;&lt;br&gt;&quot;);
            Expect(&quot;&lt;br /&gt;&quot;);
        }

        [TestMethod]
        public void Must_remove_duplicate_border_on_SPGridView_control {
            Given(@&quot;&lt;table border=&quot;&quot;0&quot;&quot; border=&quot;&quot;0&quot;&quot;&gt;&lt;/table&gt;&quot;);
            Expect(@&quot;&lt;table border=&quot;&quot;0&quot;&quot;&gt;&lt;/table&gt;&quot;);
        }

        private void Expect(string xhtml) {
            Assert.AreEqual(xhtml, _result);
        }

        private void Given(string html) {
            var transformer = new HtmlToXHtmlTransformer(html);
            _result = transformer.Transform();
        }
    }</pre>
<p>I particularly like the clarity of the given-expect pattern and find that for a reasonable number of tests it’s a viable alternative to data-driven test. I do, however, recognize the value of data-driven tests in situations where a non-developer wants to test a class. Though at the unit test level I’ve never experienced this. It’s more characteristic of <a href="http://en.wikipedia.org/wiki/FitNesse">FitNesse for acceptance testing</a>. However you unit test, just make sure your tests run with a minimum of effort on your part and that they run fast.</p>
<p><a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save"><img src="http://www.bugfree.dk/blog/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a> </p>]]></content:encoded>
			<wfw:commentRss>http://www.bugfree.dk/blog/2010/04/25/the-given-expect-testing-pattern/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Basic unit testing guidelines</title>
		<link>http://www.bugfree.dk/blog/2009/06/19/basic-unit-testing-guidelines/</link>
		<comments>http://www.bugfree.dk/blog/2009/06/19/basic-unit-testing-guidelines/#comments</comments>
		<pubDate>Fri, 19 Jun 2009 21:02:39 +0000</pubDate>
		<dc:creator>Ronnie Holm</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Mocking]]></category>
		<category><![CDATA[Presentation]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Quality]]></category>
		<category><![CDATA[Testing]]></category>

		<guid isPermaLink="false">http://www.bugfree.dk/blog/?p=111</guid>
		<description><![CDATA[Update, Aug 5, 2009: This post grew out of a couple of presentations that I did on the subject back in May and June. Here are my slides from The Unit testing and mocking presentation. Among other things, they contain a few C# samples elaborating on some of the points below. This post is born [...]]]></description>
			<content:encoded><![CDATA[<p><b>Update, Aug 5, 2009</b>: This post grew out of a couple of presentations that I did on the subject back in May and June. Here are my slides from <a href="http://www.bugfree.dk/blog/wp-content/uploads/2009/08/Unit-testing-and-mocking.pdf">The Unit testing and mocking presentation</a>. Among other things, they contain a few C# samples elaborating on some of the points below.
</p>
<p>
This post is born of the need to formalize a set of guidelines on how to write and organize tests. In the past I couldn’t help feeling that with the lack of guidelines I had to start over explaining my views on every new project. With no guidelines the tests written quickly grew unmaintainable, giving unit testing a bad name.
</p>
<h4>Why unit test</h4>
<p>
Unit testing done right helps build confidence in the code base and drives forward development. Both in terms of forcing one to reflect on the requirements by authoring tests, but also by providing a foundation for developing more modular and testable code.
</p>
<p>
Given the <a href="http://en.wikipedia.org/wiki/Cyclomatic_complexity">cyclomatic complexity</a> of even simple methods, however, not every path through a method is worth exercising with a test. Instead, focus on writing representative unit tests for good and bad scenarios.
</p>
<h4>Unit test != integration test</h4>
<p>
For object-oriented code a unit test is one that exercises a class in isolation, without the code under test relying on other classes to carry out its operation. Similarly, a unit test shouldn&#8217;t rely on the presence of a database or a key/value pair in a configuration file for it to run. If it did, it would be an integration test. Not that there&#8217;s anything wrong with integration tests. They just take on more dependencies and hence tend to be more brittle. And so they cause more false positives because some dependent part isn&#8217;t properly configured. The key point, though, is not to confuse unit testing with integration testing.
</p>
<p>
Typically, an object delegates part of its operation to other objects. Writing modular and testable code therefore involves the application of design patterns, such as <a href="http://www.martinfowler.com/articles/injection.html#SignificantRevisions">Inversion of Control (IoC)</a>. With IoC a test can inject (fake) components into the object under test. The fake components share their interfaces with the real ones, but the test controls how they interact with the object under test and hence how the object under test behaves.
</p>
<h4>Keep up quality</h4>
<p>
As tests are written it&#8217;s vital for the understandability and maintainability of the test suite to keep them small and focused. As a rule of thumb a test should amount to no more than 10-15 lines of code. Longer tests are indicative of too much functionality being tested at once or that code common to multiple tests should be refactored into helper methods.
</p>
<p>
In terms of quality, the code comprising the tests should be of production code quality, i.e., the code must be kept clean and refactored as the need arises. Otherwise, tests will start to emit the <a href="http://martinfowler.com/bliki/CodeSmell.html">classic code smells</a>. In the longer run code smells lead to tests that are not maintainable and for the time that went into writing them to be wasted.
</p>
<h4>Organizing test code</h4>
<p>
Assuming the use of Visual Studio (VS), for each VS project with code that one wants to test, create matching projects that host the various kinds of tests, i.e., for the Acme.Intranet.Search project, create the following test related projects:
</p>
<pre>
    Acme.Intranet.Search.Common
    Acme.Intranet.Search.UnitTest
    Acme.Intranet.Search.IntegrationTest
</pre>
<p>
The Acme.Intranet.Common project is optional and may include code that is shared between test projects, such as custom assertions. As for the Acme.Intranet.Search.UnitTest project it should be fairly self-contained. One should be able to move the common assembly, the test assembly, and the business code assembly to another machine and have the tests execute there without further setup. Should a test rely on, say, a data file with test data, then include the file as an embedded resource within the test assembly.
</p>
<p>
Finally, within each test project, a class should be created for each class under test. In addition, the directory structure should match the namespace structure of the class under test, e.g., suppose the fully qualified name of a class is Acme.Intranet.Search.Business.Crawler, then create the following directory structure within the test assembly:
</p>
<pre>
    Acme.Intranet.Search.UnitTest
        Acme
            Intranet
                Search
                    Buesiness
                        CrawlerTest.cs
</pre>
<p>While it’s important to write tests, it’s even more important to know where to put and find tests for a given functional area.</p>
<h4>Naming tests</h4>
<p>As far as naming and structure goes, a test should look something along these lines:</p>
<pre class="prettyprint lang-cs">
    [TestClass]
    public class SomeClassTest {
        [TestMethod]
        public void SomeMethod_should_set_error_message_when_no_<br/>                    connection_string_is_configured() {
            // arrange
            // act
            // assert
        }
    }
</pre>
<p>
The test should generally start with the name of the method or property being tested, followed by the word &#8220;should&#8221; followed by the successful outcome in a descriptive form. Because names of tests tend to be longer than those of regular methods, underscores are used for ease of readability. In addition, the body of most tests should be composed of three parts: (1) the arrange part that sets up the object under test and possibly injects fake dependencies into it. (2) The act part then exercises the method under test, and finally (3) the assert part that verifies that expected state and/or behavioral changes did indeed take place.
</p>
<h4>Gathering metrics</h4>
<p>
Whenever a build is kicked of (on a build server) it should exercise all tests. Should a test fail, it should cause the entire build to fail, stressing the importance of keeping tests green at all times. Furthermore, a build report should include basic metrics such as code coverage, number of tests run, time spend running the tests, and so forth.
</p>
<p>
Keep in mind, though, that a high degree of code coverage isn&#8217;t a goal in itself. Instead, focus on writing solid, focused, and representative tests that eventually drive up code coverage.
</p>
<h4>Tooling</h4>
<p>
As far as .Net and tooling goes, <a href="http://en.wikipedia.org/wiki/MSTest">MSTest</a> or <a href="http://nunit.org">NUnit</a> should be used in concert with <a href="http://www.bugfree.dk/blog/2009/02/11/an-example-of-unit-testing-using-typemock">TypeMock</a> or <a href="http://ayende.com/projects/rhino-mocks.aspx">Rhino Mocks</a>. The use of TypeMock may be preferred over Rhino Mocks because of its unique approach to mocking. TypeMock doesn&#8217;t create fake objects by emitting MSIL and dynamically loading a runtime-generated assembly into the test runner. Instead, TypeMock hooks into the CLR APIs and intercepts calls as the unit test executes. From a coding point of view the TypeMock approach may not change much, but from a functionality point of view it enables the testing of legacy code or new code not written with IoC in mind.</p>
<p><a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save"><img src="http://www.bugfree.dk/blog/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a> </p>]]></content:encoded>
			<wfw:commentRss>http://www.bugfree.dk/blog/2009/06/19/basic-unit-testing-guidelines/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>An example of unit testing using TypeMock</title>
		<link>http://www.bugfree.dk/blog/2009/02/11/an-example-of-unit-testing-using-typemock/</link>
		<comments>http://www.bugfree.dk/blog/2009/02/11/an-example-of-unit-testing-using-typemock/#comments</comments>
		<pubDate>Wed, 11 Feb 2009 04:00:07 +0000</pubDate>
		<dc:creator>Ronnie Holm</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[SharePoint]]></category>
		<category><![CDATA[Mocking]]></category>
		<category><![CDATA[Quality]]></category>
		<category><![CDATA[Testing]]></category>

		<guid isPermaLink="false">http://www.bugfree.dk/blog/2009/02/11/an-example-of-unit-testing-using-typemock/</guid>
		<description><![CDATA[This post details my first use of TypeMock, a commercial mocking framework, for testing a web part that displays a dropdown bound to a LINQ query. Based on the item selected, the web part then displays a result bound to another LINQ query. For the purpose of becoming familiar with TypeMock, though, the focus of [...]]]></description>
			<content:encoded><![CDATA[<p>This post details my first use of <a href="http://www.typemock.com">TypeMock</a>, a commercial mocking framework, for testing a web part that displays a dropdown bound to a LINQ query. Based on the item selected, the web part then displays a result bound to another LINQ query. For the purpose of becoming familiar with TypeMock, though, the focus of this post is on testing the code that initializes the LINQ data context. It does so by reading a connection string from a configuration file and passing it to the data context.
</p>
<p>In order to test code whose branching behavior depends on a value read from a configuration file, the test should provide various inputs and assert that the code under test acts accordingly. In addition, the test should run in milliseconds to encourage frequent runs and it should be self-contained, meaning no setup should be required before running the test. These requirements are best met with the web part running in a controlled environment. Yet, as far as the code under test goes, it should behave as if part of an Asp.Net page.
</p>
<p>For the sake of brevity, here&#8217;s my web part with the code to initialize the data context:</p>
<pre class="prettyprint lang-cs">
    public class MyWebPart : WebPart {
        MyDataContext _db;    /* LINQ database context */
        string _error;        /* Early stage error message */    	

        public MyWebPart() {
            Initialize();
        }

        private void Initialize() {
            string c = GetMyConnectionString();
            if (c == null)
                 _error = "Unable to do something";
            else
                _db = new MyDataContext(c);
        }

        private string GetMyConnectionString() {
            System.Configuration.ConnectionStringSettings c =
                System.Configuration.ConfigurationManager.
                    ConnectionStrings["MyConnection"];
            return c == null ? null : c.ConnectionString;
        }

        protected override void Render(HtmlTextWriter w) {
            // display error message if set
        }
    }
</pre>
<p>Notice how the constructor calls out to an Initialize method. Otherwise code within the constructor would fire before I&#8217;d have a chance to setup a controlled environment around the web part and I wouldn&#8217;t be able to test it. Turning the attention to Initialize itself, it’s made up of only a simple if statement. The idea is that if I can&#8217;t mock something as simple as reading a value from a configuration file, most likely I can&#8217;t mock something more involved either. On the other hand, for a developer already familiar with TypeMock and test first development, the code above may be born of the need to satisfy a failing test.
</p>
<p>I want to test Initialize by controlling how GetMyConnectionString gets to return the connection string. While running in an Asp.Net context, GetMyConnectionString would attempt to read the string from web.config. Within my controlled environment, however, I want to inject into the web part an alternate implementation that returns a value of my choosing. That way I can control the path through Initialize and inspecting the state of the  _error or _db fields, I&#8217;m able to determine if the code behaved as intended.
</p>
<p>Using the method chaining DSL of TypeMock, the test takes on this form (of course, having more tests, I&#8217;d move shared code into helper methods decreasing the test to code ratio):
</p>
<pre class="prettyprint lang-cs">
    [TestClass, ClearMocks]
    public class MyWebPartTest {
        [TestMethod, Isolated, VerifyMocks]
        public void Should_set_error_message_when_no_
                    connection_string_is_configured() {
            // arrange
            MyWebPart fake = Isolate.Fake.Instance&lt;MyWebPart&gt;();
            Isolate.NonPublic.WhenCalled(fake,
                "Initialize").CallOriginal();
            Isolate.NonPublic.WhenCalled(fake,
                "GetMyConnectionString").WillReturn(null);
            PrivateObject handle = new PrivateObject(fake);

            // act
            handle.Invoke("Initialize", null); 

            // assert
            Isolate.Verify.NonPublic.WasCalled(fake,
                "GetMyConnectionString");
            string error = (string)handle.GetField("_error");
            MyDataContext ctx = (MyDataContext)handle.GetField("_db");
            Assert.AreEqual("Unable to do something", error);
            Assert.AreEqual(null, ctx);
        }
    }
</pre>
<p>There&#8217;re three parts to tests using TypeMock: (1) the arrange part sets up expectations of what’s going to happen when a method, a property, or some other part of the code under test is invoked; (2) the act part carries out the actual interaction with the object under test, turning to <a href="http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.testtools.unittesting.privateobject.aspx">PrivateObject</a> to invoke the Initialize method; and finally (3) the assert part verifies that what was supposed to happen did happen. Worth noting is that this test asserts both state and behavior, i.e., as part of executing the code under test, _error or _db should&#8217;ve been set to an appropriate state and GetMyConnectionString should’ve been called once and only once.
</p>
<p>This concludes my example, which I believe illustrates the basics of testing and mocking using MS Test and TypeMock. Comparing and contrasting TypeMock to <a href="http://weblogs.asp.net/rosherove/archive/2007/04/26/choosing-a-mock-object-framework.aspx">other popular mocking frameworks</a>, TypeMock has the distinct feature that it can mock almost anything, with or without using interfaces. <a href="http://www.mockobjects.com/2007/03/stop-designing-for-testability.html">Some</a> argue that not enforcing the use of interfaces is also the disadvantage of TypeMock, because for code to be truly testable, it should be modularized using the <a href="http://en.wikipedia.org/wiki/Inversion_of_control">Inversion of Control principle</a>. However, with legacy code, such as the .Net framework or the SharePoint API, to me TypeMock appears to bridge the two worlds nicely, leaving the developer in charge.</p>
<p>To learn more about the basic concepts of mocking, Inversion of Control, and Dependency Injection (containers), I&#8217;d recommend listening to a couple of <a href="http://altnetpodcast.com">Alt.Net podcasts</a>: <a href="http://altnetpodcast.com/episodes/5-di-and-ioc">Dependency Injection and Inversion of Control</a> and <a href="http://altnetpodcast.com/episodes/6-more-di-and-ioc">More Dependency Injection and Inversion of Control</a>.</p>
<p><a class="a2a_dd addtoany_share_save" href="http://www.addtoany.com/share_save"><img src="http://www.bugfree.dk/blog/wp-content/plugins/add-to-any/share_save_171_16.png" width="171" height="16" alt="Share/Bookmark"/></a> </p>]]></content:encoded>
			<wfw:commentRss>http://www.bugfree.dk/blog/2009/02/11/an-example-of-unit-testing-using-typemock/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>
