<?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>sides of march &#187; unit testing</title>
	<atom:link href="http://www.sidesofmarch.com/index.php/archive/tag/unit-testing/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.sidesofmarch.com</link>
	<description>Thoughts on life, liberty, and information technology</description>
	<lastBuildDate>Mon, 16 Jan 2012 02:43:26 +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>Mocking indexed properties with Moq</title>
		<link>http://www.sidesofmarch.com/index.php/archive/2009/03/06/mocking-indexed-properties-with-moq/</link>
		<comments>http://www.sidesofmarch.com/index.php/archive/2009/03/06/mocking-indexed-properties-with-moq/#comments</comments>
		<pubDate>Fri, 06 Mar 2009 17:05:18 +0000</pubDate>
		<dc:creator>brian</dc:creator>
				<category><![CDATA[Technology]]></category>
		<category><![CDATA[Moq]]></category>
		<category><![CDATA[unit testing]]></category>

		<guid isPermaLink="false">http://www.sidesofmarch.com/?p=343</guid>
		<description><![CDATA[<p>A coworker of mine (who just got back from the Microsoft MVP events in Seattle, congrats, Matt!) has turned me on to using <a href="http://code.google.com/p/moq/">Moq</a>, which I must say is an impressive mocking framework that has made unit testing notably easier.</p>
<p>Recently I had the need to mock the <a href="http://api.castleproject.org/html/AllMembers_T_Castle_MonoRail_Framework_IRequest.htm">IRequest</a> interface of the <a href="http://www.castleproject.org/MonoRail">Castle MonoRail</a> framework – specifically, two properties: the indexed property and the QueryString property, both of which expose a NameValueCollection.</p>
<p>I found some guidance on <a href="http://stackoverflow.com/questions/340827/how-to-moq-an-indexed-property">mocking the indexed property via Stack Overflow</a>, which turned me on to the following solution.</p>

var request = new Mock&#60;IRequest&#62;();
request.ExpectGet(r =&#62; r[It.Is&#60;string&#62;(x =&#62; x == "someName")]).Returns("someValue");

<p>To mock the QueryString property took a different approach: create a NameValueCollection, add my test data to it, and wire the collection to the mocked object.</p>

var request = new Mock&#60;IRequest&#62;();
var query = new NameValueCollection();
query.Add("someName", "someValue");
request.ExpectGet(r =&#62; r.QueryString).Returns(query);

<p>With this, I can now pass my mocked IRequest to other classes, which will be able to access the following:</p>

request["someName"] = "someValue";
request.QueryString["someName"] <span style="color:#777"> . . .<br /><br />&#8594; Read More: <a href="http://www.sidesofmarch.com/index.php/archive/2009/03/06/mocking-indexed-properties-with-moq/">Mocking indexed properties with Moq</a></span>]]></description>
			<content:encoded><![CDATA[<p>A coworker of mine (who just got back from the Microsoft MVP events in Seattle, congrats, Matt!) has turned me on to using <a href="http://redirectingat.com?id=17923X751173&xs=1&url=http%3A%2F%2Fcode.google.com%2Fp%2Fmoq%2F&sref=rss">Moq</a>, which I must say is an impressive mocking framework that has made unit testing notably easier.</p>
<p>Recently I had the need to mock the <a href="http://redirectingat.com?id=17923X751173&xs=1&url=http%3A%2F%2Fapi.castleproject.org%2Fhtml%2FAllMembers_T_Castle_MonoRail_Framework_IRequest.htm&sref=rss"><code>IRequest</code></a> interface of the <a href="http://redirectingat.com?id=17923X751173&xs=1&url=http%3A%2F%2Fwww.castleproject.org%2FMonoRail&sref=rss">Castle MonoRail</a> framework – specifically, two properties: the indexed property and the QueryString property, both of which expose a NameValueCollection.</p>
<p>I found some guidance on <a href="http://redirectingat.com?id=17923X751173&xs=1&url=http%3A%2F%2Fstackoverflow.com%2Fquestions%2F340827%2Fhow-to-moq-an-indexed-property&sref=rss">mocking the indexed property via Stack Overflow</a>, which turned me on to the following solution.</p>
<pre class="brush:C#">
var request = new Mock&lt;IRequest&gt;();
request.ExpectGet(r =&gt; r[It.Is&lt;string&gt;(x =&gt; x == "someName")]).Returns("someValue");
</pre>
<p>To mock the <code>QueryString</code> property took a different approach: create a <code>NameValueCollection</code>, add my test data to it, and wire the collection to the mocked object.</p>
<pre class="brush:c#">
var request = new Mock&lt;IRequest&gt;();
var query = new NameValueCollection();
query.Add("someName", "someValue");
request.ExpectGet(r =&gt; r.QueryString).Returns(query);
</pre>
<p>With this, I can now pass my mocked <code>IRequest</code> to other classes, which will be able to access the following:</p>
<pre class="brush:c#">
request["someName"] = "someValue";
request.QueryString["someName"] = "someValue";
</pre>
<p>In all, it makes unit testing web requests a lot easier!</p>
<img src="http://www.sidesofmarch.com/?ak_action=api_record_view&id=343&type=feed" alt="" /><div class="addthis_toolbox addthis_default_style addthis_32x32_style" addthis:url='http://www.sidesofmarch.com/index.php/archive/2009/03/06/mocking-indexed-properties-with-moq/' addthis:title='Mocking indexed properties with Moq ' ><a class="addthis_button_preferred_1"></a><a class="addthis_button_preferred_2"></a><a class="addthis_button_preferred_3"></a><a class="addthis_button_preferred_4"></a><a class="addthis_button_compact"></a></div>]]></content:encoded>
			<wfw:commentRss>http://www.sidesofmarch.com/index.php/archive/2009/03/06/mocking-indexed-properties-with-moq/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Unit testing an Activerecord domain model with NUnit</title>
		<link>http://www.sidesofmarch.com/index.php/archive/2009/01/14/unit-testing-an-activerecord-domain-model-with-nunit/</link>
		<comments>http://www.sidesofmarch.com/index.php/archive/2009/01/14/unit-testing-an-activerecord-domain-model-with-nunit/#comments</comments>
		<pubDate>Wed, 14 Jan 2009 14:11:38 +0000</pubDate>
		<dc:creator>brian</dc:creator>
				<category><![CDATA[Technology]]></category>
		<category><![CDATA[ActiveRecord]]></category>
		<category><![CDATA[NUnit]]></category>
		<category><![CDATA[unit testing]]></category>

		<guid isPermaLink="false">http://www.sidesofmarch.com/?p=329</guid>
		<description><![CDATA[<p><em>[Digression] This post has been sitting in a somewhat unfinished state for a long time. It feels good to finally post it!</em></p>
<p>In rewriting my baseball game, <a href="http://www.csfbl.com">CSFBL</a>, I made the decision to use <a href="http://www.castleproject.org/activerecord">Castle ActiveRecord</a> (built on top of <a href="http://www.nhforge.org">NHibernate</a>) to handle the persistence of my domain model. As a result, I needed to find a simple but effective way to unit test this implementation.</p>
<p>The unit tests needed to accomplish the following:</p>

Test the initialization of ActiveRecord (which validates the database schema against the object mappings).
Test object validation (since I am using <a href="http://api.castleproject.org/html/N_Castle_Components_Validator.htm">Castle’s Validation component</a> and the ActiveRecordValidationBase&#60;T&#62; base class).
Ensure that a domain object can be persisted to the database.
Ensure that a domain object can be retrieved from the database.
Ensure that multiple instances of an object with the same persisted primary key are equal.

<p>How, then, do we do this?</p>
<p><strong>Testing against a real database with test data</strong></p>
<p>One thing I knew I needed to do was to test against a <span style="color:#777"> . . .<br /><br />&#8594; Read More: <a href="http://www.sidesofmarch.com/index.php/archive/2009/01/14/unit-testing-an-activerecord-domain-model-with-nunit/">Unit testing an Activerecord domain model with NUnit</a></span>]]></description>
			<content:encoded><![CDATA[<p><em>[Digression] This post has been sitting in a somewhat unfinished state for a long time. It feels good to finally post it!</em></p>
<p>In rewriting my baseball game, <a href="http://redirectingat.com?id=17923X751173&xs=1&url=http%3A%2F%2Fwww.csfbl.com&sref=rss">CSFBL</a>, I made the decision to use <a href="http://redirectingat.com?id=17923X751173&xs=1&url=http%3A%2F%2Fwww.castleproject.org%2Factiverecord&sref=rss">Castle ActiveRecord</a> (built on top of <a href="http://redirectingat.com?id=17923X751173&xs=1&url=http%3A%2F%2Fwww.nhforge.org&sref=rss">NHibernate</a>) to handle the persistence of my domain model. As a result, I needed to find a simple but effective way to unit test this implementation.</p>
<p>The unit tests needed to accomplish the following:</p>
<ol>
<li>Test the initialization of ActiveRecord (which validates the database schema against the object mappings).</li>
<li>Test object validation (since I am using <a href="http://redirectingat.com?id=17923X751173&xs=1&url=http%3A%2F%2Fapi.castleproject.org%2Fhtml%2FN_Castle_Components_Validator.htm&sref=rss">Castle’s Validation component</a> and the <code>ActiveRecordValidationBase&lt;T&gt;</code> base class).</li>
<li>Ensure that a domain object can be persisted to the database.</li>
<li>Ensure that a domain object can be retrieved from the database.</li>
<li>Ensure that multiple instances of an object with the same persisted primary key are equal.</li>
</ol>
<p>How, then, do we do this?<span id="more-329"></span></p>
<p><strong>Testing against a real database with test data</strong></p>
<p>One thing I knew I needed to do was to test against a true database instance, not a <a title="Rhino Mocks" href="http://redirectingat.com?id=17923X751173&xs=1&url=http%3A%2F%2Fayende.com%2Fprojects%2Frhino-mocks.aspx&sref=rss">mock</a>. I wanted to make sure this was a live test of the persistence model, not just a test of the conceptual model. Since CSFBL will only run off an MSSQL database, and the schema is constantly changing, and the domain model has many foreign key dependencies, unit testing against the database is important.</p>
<p>To accomplish this, I wrote a short SQL script which would insert <strong>test data</strong> into a blank copy of the database. (All database scripts and build scripts are also in <a title="Subversion version control system" href="http://redirectingat.com?id=17923X751173&xs=1&url=http%3A%2F%2Fsubversion.tigris.org&sref=rss">SVN</a>; I’ll blog about that solution another time.) By inserting well-defined test data, I can then write unit tests easily.</p>
<p>A sample of the SQL test script follows.</p>
<pre class="brush: sql; ">

-- start bb_leagues
print &#039;bb_leagues&#039;

declare @leagueid int

insert into bb_leagues ( name, createdon, simfrequency,
startyear, date, forumid, ispremier, stadiumchangeallowed )
values ( &#039;testleague&#039;, getdate(), 2, 1981, &#039;1981-01-01&#039;, null, 0, 1 )

set @leagueid = scope_identity()
-- end bb_leagues

-- start bb_conferences
print &#039;bb_conferences&#039;

declare @conferenceid int

insert into bb_conferences ( name, allowdh, leagueid )
values ( &#039;testconference&#039;, 0, @leagueid )

set @conferenceid = scope_identity()
--end bb_conferences
</pre>
<p>Notice how I saved the primary key of the first insert (a <strong>league</strong>) and used it on the second insert (a <strong>conference</strong>). By cascading down the dependency chain of my database model, I can easily build my test data.</p>
<p><strong>The <code>ActiveRecordTest</code> base class</strong></p>
<p>Once the test data is available, it’s a matter of writing the unit tests. Since there will be one test class for each model class (e.g. <code>LeagueTests</code> for the <code>League</code> class, which maps to <code>bb_leagues</code>), we can have an abstract base class for our unit tests that will provide baseline functionality.</p>
<p>The base class will be responsible for a number of tasks, each corresponding to an NUnit task.</p>
<ol>
<li>[<code>TestFixtureSetUp</code>] Initialize the ActiveRecord framework when the test fixture starts.</li>
<li>[<code>SetUp</code>] Prepare the schema before each test (to ensure each test is somewhat atomic).</li>
<li>[<code>TearDown</code>] Clean up after each test is run.</li>
<li>[<code>TestFixtureTearDown</code>] Reset ActiveRecord after each text fixture ends to ensure other tests can don’t break when running step #1.</li>
</ol>
<p>By abstracting lots of the functionality, you only need to override a few methods:</p>
<ul>
<li><code>FetchARAssembly</code>() gets the assembly which contains your ActiveRecord model classes. This should be overridden to return the assembly name containing your model classes.</li>
<li><code>FetchARConfig</code>() gets the configuration source for ActiveRecord. The default implementation uses the ActiveRecord section in your application configuration file, which often is correct.</li>
<li>The other methods – <code>TestFixtureSetUp</code>, <code>SetUp</code>, <code>TearDown</code>, <code>TestFixtureTearDown</code> – only need to be overridden if you need additional functionality at those phases of your unit test. In all cases, you should always call the base class implementation first.</li>
</ul>
<p>On to the code!</p>
<pre class="brush: c-sharp; ">

using System;
using System.Reflection;
using Castle.ActiveRecord;
using Castle.ActiveRecord.Framework;
using Castle.ActiveRecord.Framework.Config;
using NUnit.Framework;

namespace ComputerSims.Common.Tests
{
///
/// Abstract class for unit tests that depend on ActiveRecord.
/// Ensures that ActiveRecord is initialized before the tests are run.
///
public abstract class ActiveRecordTest
{
#region SetUp/TearDown
///
/// Sets up the test fixture.
///
///
/// When overriding, be sure to call the base method.
///
[TestFixtureSetUp]
protected virtual void TestFixtureSetUp()
{
InitFramework();
}

///
/// Sets up before each test.
///
///
/// When overriding, be sure to call the base method.
///
[SetUp]
protected virtual void SetUp()
{
ClearSchema();
}

///
/// Tears down after each test.
///
///
/// When overriding, be sure to call the base method.
///
[TearDown]
protected virtual void TearDown()
{
}

///
/// Tears down the test fixture.
///
///
/// When overriding, be sure to call the base method.
///
[TestFixtureTearDown]
protected virtual void TestFixtureTearDown()
{
ActiveRecordStarter.ResetInitializationFlag();
}
#endregion

#region Protected Methods
///
/// Clears (deletes) all data in the data schema to allow each
/// test to run in isolation.
///
///
/// Currently this does nothing, as schema creation is handled by SQL scripts.
/// However, to run tests in isolation, we should recreate the database using
/// default data each time a unit test is run. Implementing that functionality
/// here would support this.
///
protected virtual void ClearSchema()
{
}

///
/// Gets the ActiveRecord configuration.
///
/// The ActiveRecord configuration settings.
///
/// Default implementation uses
/// .
///
protected virtual IConfigurationSource FetchARConfig()
{
IConfigurationSource source = ActiveRecordSectionHandler.Instance;
return source;
}

///
/// Gets the assembly that contains ActiveRecord entities.
///
/// The assembly.
///
/// Default implementation returns the executing assembly.
///
protected virtual Assembly FetchARAssembly()
{
return Assembly.GetExecutingAssembly();
}
#endregion

#region Private Methods
private void InitFramework()
{
ActiveRecordStarter.Initialize(
this.FetchARAssembly(),
this.FetchARConfig());
}
#endregion
}
}
</pre>
<p>Note that there’s nothing specific to my domain model in there. This base class can therefore be used for any ActiveRecord-based domain model.</p>
<p>Writing an implementation of this class is easy &#8212; and I&#8217;ll write about that soon.</p>
<img src="http://www.sidesofmarch.com/?ak_action=api_record_view&id=329&type=feed" alt="" /><div class="addthis_toolbox addthis_default_style addthis_32x32_style" addthis:url='http://www.sidesofmarch.com/index.php/archive/2009/01/14/unit-testing-an-activerecord-domain-model-with-nunit/' addthis:title='Unit testing an Activerecord domain model with NUnit ' ><a class="addthis_button_preferred_1"></a><a class="addthis_button_preferred_2"></a><a class="addthis_button_preferred_3"></a><a class="addthis_button_preferred_4"></a><a class="addthis_button_compact"></a></div>]]></content:encoded>
			<wfw:commentRss>http://www.sidesofmarch.com/index.php/archive/2009/01/14/unit-testing-an-activerecord-domain-model-with-nunit/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Unit testing a WMI reboot</title>
		<link>http://www.sidesofmarch.com/index.php/archive/2008/12/08/unit-testing-a-wmi-reboot/</link>
		<comments>http://www.sidesofmarch.com/index.php/archive/2008/12/08/unit-testing-a-wmi-reboot/#comments</comments>
		<pubDate>Mon, 08 Dec 2008 14:11:31 +0000</pubDate>
		<dc:creator>brian</dc:creator>
				<category><![CDATA[Technology]]></category>
		<category><![CDATA[unit testing]]></category>
		<category><![CDATA[WMI]]></category>

		<guid isPermaLink="false">http://www.sidesofmarch.com/?p=303</guid>
		<description><![CDATA[<p>The other day I started working on a <a title="Windows Management Instrumentation" href="http://www.google.com/url?sa=t&#38;source=web&#38;ct=res&#38;cd=1&#38;url=http%3A%2F%2Fmsdn.microsoft.com%2Fen-us%2Flibrary%2Faa394582(VS.85).aspx&#38;ei=2So9SbjeB4mIecSWqP4G&#38;usg=AFQjCNEjx7EGWT2ONH2eXjwxji-mtYEzYw&#38;sig2=2vAAWfrzuHlcZwJsUY47UQ">WMI</a> wrapper that would encapsulate workstation management functionality (starting and stopping services, querying workstations, etc.). Unit testing, as always, is important, but I inevitably came to one problem.</p>
<p>How do you unit test a method that reboots a workstation?</p>
<p>The answer: Run the unit test, and if your machine starts to shut down, that means it&#8217;s the end of the workday, and your test passed. (It was already 6PM on a Friday, so such behavior was justified.)</p>
<a class="addthis_button_preferred_1"></a><a class="addthis_button_preferred_2"></a><a class="addthis_button_preferred_3"></a><a <span style="color:#777"> . . .<br /><br />&#8594; Read More: <a href="http://www.sidesofmarch.com/index.php/archive/2008/12/08/unit-testing-a-wmi-reboot/">Unit testing a WMI reboot</a></span>]]></description>
			<content:encoded><![CDATA[<p>The other day I started working on a <a title="Windows Management Instrumentation" href="http://redirectingat.com?id=17923X751173&xs=1&url=http%3A%2F%2Fwww.google.com%2Furl%3Fsa%3Dt%26amp%3Bsource%3Dweb%26amp%3Bct%3Dres%26amp%3Bcd%3D1%26amp%3Burl%3Dhttp%253A%252F%252Fmsdn.microsoft.com%252Fen-us%252Flibrary%252Faa394582%28VS.85%29.aspx%26amp%3Bei%3D2So9SbjeB4mIecSWqP4G%26amp%3Busg%3DAFQjCNEjx7EGWT2ONH2eXjwxji-mtYEzYw%26amp%3Bsig2%3D2vAAWfrzuHlcZwJsUY47UQ&sref=rss">WMI</a> wrapper that would encapsulate workstation management functionality (starting and stopping services, querying workstations, etc.). Unit testing, as always, is important, but I inevitably came to one problem.</p>
<p>How do you unit test a method that reboots a workstation?</p>
<p>The answer: Run the unit test, and if your machine starts to shut down, that means it&#8217;s the end of the workday, and your test passed. (It was already 6PM on a Friday, so such behavior was justified.)</p>
<img src="http://www.sidesofmarch.com/?ak_action=api_record_view&id=303&type=feed" alt="" /><div class="addthis_toolbox addthis_default_style addthis_32x32_style" addthis:url='http://www.sidesofmarch.com/index.php/archive/2008/12/08/unit-testing-a-wmi-reboot/' addthis:title='Unit testing a WMI reboot ' ><a class="addthis_button_preferred_1"></a><a class="addthis_button_preferred_2"></a><a class="addthis_button_preferred_3"></a><a class="addthis_button_preferred_4"></a><a class="addthis_button_compact"></a></div>]]></content:encoded>
			<wfw:commentRss>http://www.sidesofmarch.com/index.php/archive/2008/12/08/unit-testing-a-wmi-reboot/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

