<?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>Elegant Code &#187; Unit Testing</title>
	<atom:link href="http://elegantcode.com/category/unit-testing/feed/" rel="self" type="application/rss+xml" />
	<link>http://elegantcode.com</link>
	<description></description>
	<lastBuildDate>Tue, 15 May 2012 10:00:00 +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>AutoTest.NET</title>
		<link>http://elegantcode.com/2010/11/30/autotest-net/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=autotest-net</link>
		<comments>http://elegantcode.com/2010/11/30/autotest-net/#comments</comments>
		<pubDate>Tue, 30 Nov 2010 11:00:00 +0000</pubDate>
		<dc:creator>Jan Van Ryswyck</dc:creator>
				<category><![CDATA[TDD]]></category>
		<category><![CDATA[Tools and Utilities]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/11/30/autotest-net/</guid>
		<description><![CDATA[I just want to quickly point out a tool that I’ve been playing with for a couple of days now, named AutoTest.NET. Its an open-source tool that originates from a popular tool in the Ruby community called ZenTest, which basically runs all your valuable unit tests when you save your source files or when you [...]]]></description>
			<content:encoded><![CDATA[<p>I just want to quickly point out a tool that I’ve been playing with for a couple of days now, named <a href="https://github.com/acken/AutoTest.Net" target="_blank">AutoTest.NET</a>. Its an open-source tool that originates from a popular tool in the Ruby community called <a href="http://www.zenspider.com/ZSS/Products/ZenTest/" target="_blank">ZenTest</a>, which basically runs all your valuable unit tests when you save your source files or when you build your code. It enables you to get feedback about your changes as soon as possible.</p>  <p>The project started out a couple of years ago on <a href="http://code.google.com/p/autotestnet/" target="_blank">Google code</a> and was first initiated by <a href="http://averyblog.com/" target="_blank">James Avery</a>. Contribution stopped at some point until recently where <a href="http://ackenpacken.blogspot.com/" target="_blank">Svein Arne Ackenhausen</a> forked the source code and <a href="https://github.com/acken/AutoTest.Net" target="_blank">put it on GitHub</a>. Now it runs both for .NET as well as Mono, with NUnit, MSTest and xUnit as the currently supported unit test frameworks. </p>  <p>Here’s a screenshot from the feedback window when all tests pass:</p>  <p><a href="http://elegantcode.com/wp-content/uploads/2010/11/Success.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="Success" border="0" alt="Success" src="http://elegantcode.com/wp-content/uploads/2010/11/Success_thumb.png" width="540" height="189" /></a> </p>  <p>And here you can see the same window after I broke one of my unit tests:</p>  <p><a href="http://elegantcode.com/wp-content/uploads/2010/11/Failure.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="Failure" border="0" alt="Failure" src="http://elegantcode.com/wp-content/uploads/2010/11/Failure_thumb.png" width="538" height="319" /></a> </p>  <p>Here you can see which particular unit test has been broken and by clicking the specified link you end up at the right source file in Visual Studio. </p>  <p>I encourage you to pick up this small tool and learn how it can facilitate your TDD flow. Take a look at <a href="https://github.com/acken/AutoTest.Net/wiki/Get-started!" target="_blank">this page</a> in order to get up-and-running in no time. Also don’t forget to provide the owner(s) of this project with some feedback that you might have. Svein has been very helpful over the last week answering all my stupid questions and remarks (and the Nobel price for this year’s most patient person goes to … ;-) ). </p>  <p>I would definitely like to see this tool becoming more popular, so go check it out.&#160;&#160; </p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/11/30/autotest-net/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>If Self-Documenting Code is the What, Unit Tests are the Why</title>
		<link>http://elegantcode.com/2010/04/25/if-self-documenting-code-is-the-what-unit-tests-are-the-why/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=if-self-documenting-code-is-the-what-unit-tests-are-the-why</link>
		<comments>http://elegantcode.com/2010/04/25/if-self-documenting-code-is-the-what-unit-tests-are-the-why/#comments</comments>
		<pubDate>Sun, 25 Apr 2010 19:09:04 +0000</pubDate>
		<dc:creator>John Sonmez</dc:creator>
				<category><![CDATA[Agile]]></category>
		<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Craftsmanship]]></category>
		<category><![CDATA[Documentation]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/04/25/if-self-documenting-code-is-the-what-unit-tests-are-the-why/</guid>
		<description><![CDATA[It is not enough to just write code that is clean and self-documenting.  Eliminating comments and replacing them with clear variable and method names, will tell the reader of your code clearly what it is doing, but it will not properly express why it is doing it. If you recall from my original post on [...]]]></description>
			<content:encoded><![CDATA[It is not enough to just write code that is clean and self-documenting.  <a href="http://elegantcode.com/2010/04/18/eliminating-comments-the-road-to-clarity/">Eliminating comments</a> and replacing them with clear variable and method names, will tell the reader of your code clearly what it is doing, but it will not properly express why it is doing it.

If you recall from my <a href="http://elegantcode.com/2010/04/09/what-does-elegant-code-mean-to-me/">original post</a> on Elegant code, I stated that elegant code is:
<blockquote>Something that is simple yet effective, delivered with grace.</blockquote>
By writing self-documenting code we are hopefully able to achieve some of the aspects of simplicity and grace, but it tells us nothing about the effectiveness of the code.
<h2>Bringing the dead to life</h2>
<a href="http://elegantcode.com/wp-content/uploads/2010/04/zombies.jpg"><img style="border-right-width: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto" title="zombies" src="http://elegantcode.com/wp-content/uploads/2010/04/zombies_thumb.jpg" border="0" alt="zombies" width="441" height="295" /></a>

Throwing out comments is a debatable topic.  <a href="http://www.reddit.com/r/programming/comments/bsutx/">It raises quite a bit of controversy</a>, as you can see from some of the comments on my post about the subject.  The reason, perhaps, that so many people are so staunchly opposed to the idea, is because they are worried, and rightly so, that throwing out comments will reduce the documentation of what the code is doing.

Think about that for a second.  Is documentation of what the code is doing important?  It better be.  What we are trying to accomplish by writing self-documenting code instead of comments, is to take the vessel, which is the code itself, and make that same vessel be the documentation of what the code does.  It is by doing this that we creating a living representation of the functionality of the code.  Comments are akin to a dead representation of the functionality of the code because they do not change automatically with the code.

I diverge to talk about comments so that I can draw a parallel to another form of documentation which is valuable and should be considered necessary.  That other set of documentation is requirements.  Have you ever written requirements documents?  Have you ever captured requirements from the customer and put them into UML diagrams, or perhaps plopped them into some templated Word document, which is never updated again, and no one reads, because no one trusts it is correct?  Wouldn’t it be great if we would replace that dead document or set of documents, with a living one?

The good news is we can, and some of us have.  And I fully expect this recommendation will be just as controversial, because <strong>I am suggesting that we don’t have to write low level specifications of the system at all, instead we can write good unit tests. </strong>When we do this, we are taking a dead form of document and bringing it to life.
<h2>Unit tests tell us why and how our code is effective</h2>
If
<pre class="csharpcode">i = 5;  // Widget count defaults to five.</pre>
is replaced with
<pre class="csharpcode">widgetCount = DEFAULT_WIDGET_COUNT;</pre>
<!--.csharpcode, .csharpcode pre { 	font-size: small; 	color: black; 	font-family: consolas, "Courier New", courier, monospace; 	background-color: #ffffff; 	/*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt  { 	background-color: #f4f4f4; 	width: 100%; 	margin: 0em; } .csharpcode .lnum { color: #606060; } -->

then
<blockquote><span style="background-color: #ffffff;">1.1.5 When a new widget is created, the widget count should be increased by one.</span></blockquote>
is replaced with
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">void</span> When_NewWidgetIsCreated_Then_WidgetCountIsIncreasedByOne()
{
     WidgetFactory.Count = 3;
     WidgetFactory.CreateNew();
     assertEquals(4, WidgetFactory.Count);
}</pre>
The unit test is replacing the low level requirement, which is somewhat open to interpretation and untied to the code, with an absolute and completely tied-to-the-code, specific requirement.

The unit test is telling us why our code is built the way it is.  It is telling us what requirement that particular structure of code is trying to address.  <strong>It is telling us what end result that code is trying to accomplish and what the expectations are on the results of a given condition.</strong>

The unit test is telling us how the code is to be used in order to achieve its result.  It is serving as a living reference to the syntax and use of the code we built.  <strong>Instead of providing instructions on how to use our API, we are providing a living example, and proof that it will indeed work.</strong> Examples are often much more effective than instructions anyway.
<h2>What exactly are we replacing?</h2>
At this point we are not trying to replace all the documentation of the system (at this point).

With self-documenting code, we sought to eliminate comments, and replace them with good variable and method names.

With unit tests, we seek to eliminate technical documentation and requirements of the system, that is targeted at a developer or technical audience.

We are NOT trying to eliminate high level specifications of the system, or use cases. <strong>Unit tests DO NOT replace that kind of documentation! </strong>We will talk about replacing that kind of documentation when we talk about automated functional or system tests.

Simply put, any kind of documentation that you would give to a developer so they understand how the system works and how to use the code or APIs, can be easily replaced by writing good unit tests.

Our simple goal is to replace the “dead” documentation (meaning that it does not update automatically with the thing it is documenting), with “living” documentation in the form of unit tests.

One last point.  I want to be clear that I am not saying that having unit tests automatically results in the ability to replace technical documentation.  Just like having long-named methods and variables doesn’t automatically replace the need for comments.  It is a matter of the quality of the unit tests that are written, just as it is a matter of the quality of the self-documenting code.
<h5>As always, you can subscribe to this <a href="http://feeds2.feedburner.com/ElegantCode">RSS feed</a> to follow my posts on elegant code.  Feel free to check out my main personal blog at <a href="http://simpleprogrammer.com">http://simpleprogrammer.com</a>, which has a wider range of posts, updated 2-3 times a week.  Also, you can follow me on twitter <a href="http://twitter.com/jsonmez">here</a>.</h5>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/04/25/if-self-documenting-code-is-the-what-unit-tests-are-the-why/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Behaviors with MSpec</title>
		<link>http://elegantcode.com/2010/02/26/behaviors-with-mspec/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=behaviors-with-mspec</link>
		<comments>http://elegantcode.com/2010/02/26/behaviors-with-mspec/#comments</comments>
		<pubDate>Fri, 26 Feb 2010 23:33:28 +0000</pubDate>
		<dc:creator>Jan Van Ryswyck</dc:creator>
				<category><![CDATA[BDD]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/02/26/behaviors-with-mspec/</guid>
		<description><![CDATA[In my previous posts, I showed the syntax for context/specifications using Machine.Specifications (or MSpec for short) and how to use an auto mocking container in conjunction with this excellent Behavior-Driven Development (BDD) framework. For this post, I want to show you one of the nice features of MSpec called behaviors. Suppose we have to create [...]]]></description>
			<content:encoded><![CDATA[<p>In my previous posts, I showed the <a href="http://elegantcode.com/2010/02/19/getting-started-with-machine-specifications-mspec/">syntax for context/specifications</a> using <a href="http://github.com/machine/machine.specifications">Machine.Specifications</a> (or MSpec for short) and <a href="http://elegantcode.com/2010/02/23/mspec-and-auto-mocking">how to use an auto mocking container</a> in conjunction with this excellent Behavior-Driven Development (BDD) framework. For this post, I want to show you one of the nice features of MSpec called <em>behaviors</em>.</p>  <p>Suppose we have to create some sort of specification that validates the format of an e-mail address. We typically use some regular expression in order to ensure that a specified e-mail address is properly formatted.</p>  <pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">class</span> EmailSpecification
{
    <span class="kwrd">private</span> <span class="kwrd">const</span> String EmailRegexPattern = <span class="str">@&quot;.. SOME_REGEX_PATTERN ...&quot;</span>;

    <span class="kwrd">public</span> Boolean IsSatisfiedBy(String candidate)
    {
        var regex = <span class="kwrd">new</span> Regex(EmailRegexPattern);
        <span class="kwrd">return</span> regex.IsMatch(candidate);
    }
}</pre>
<style type="text/css">

.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>I guess this is pretty common and straightforward. One way to provide some unit tests for this particular piece of code is to check a whole number of e-mail addresses that either pass or fail the specification. The following example shows only a couple of scenarios:</p>

<pre class="csharpcode">[TestFixture]
<span class="kwrd">public</span> <span class="kwrd">class</span> When_validating_an_email
    : ContextSpecification&lt;EmailSpecification&gt;
{
    <span class="kwrd">protected</span> <span class="kwrd">override</span> EmailSpecification Create_subject_under_test()
    {
        <span class="kwrd">return</span> <span class="kwrd">new</span> EmailSpecification();
    }

    [Test]
    <span class="kwrd">public</span> <span class="kwrd">void</span> ShouldBeSatisfied()
    {
        Assert.That(SUT.IsSatisfiedBy(<span class="str">&quot;one2@three.com&quot;</span>));
        Assert.That(SUT.IsSatisfiedBy(<span class="str">&quot;one@two3.com&quot;</span>));
    }

    [Test]
    <span class="kwrd">public</span> <span class="kwrd">void</span> ShouldNotBeSatisfied()
    {
        Assert.That(SUT.IsSatisfiedBy(<span class="str">&quot;one_two.com&quot;</span>), Is.False);
        Assert.That(SUT.IsSatisfiedBy(<span class="str">&quot;one_two@&quot;</span>), Is.False);
    }
}</pre>
<style type="text/css">

.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>A slightly more concise approach for these kind of unit tests can be accomplished by utilizing a feature of any decent unit test framework called <em>row tests. </em>With this approach we can, at the very least, reduce the number of asserts we have to write for each unit test.<em>&#160;</em></p>

<pre class="csharpcode">[TestFixture]
<span class="kwrd">public</span> <span class="kwrd">class</span> When_validating_an_email__approach_2
    : ContextSpecification&lt;EmailSpecification&gt;
{
    <span class="kwrd">protected</span> <span class="kwrd">override</span> EmailSpecification Create_subject_under_test()
    {
        <span class="kwrd">return</span> <span class="kwrd">new</span> EmailSpecification();
    }

    [RowTest]
    [Row(<span class="str">&quot;one2@three.com&quot;</span>)]
    [Row(<span class="str">&quot;one@two3.com&quot;</span>)]
    <span class="kwrd">public</span> <span class="kwrd">void</span> ShouldBeSatisfied(String email)
    {
        Assert.That(SUT.IsSatisfiedBy(email));
    }

    [RowTest]
    [Row(<span class="str">&quot;one_two.com&quot;</span>)]
    [Row(<span class="str">&quot;one_two@&quot;</span>)]
    <span class="kwrd">public</span> <span class="kwrd">void</span> ShouldNotBeSatisfied(String email)
    {
        Assert.That(SUT.IsSatisfiedBy(email), Is.False);
    }
}</pre>
<style type="text/css">

.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>Notice that I explicitly called both of these approaches <em>unit tests</em> as they don’t have much to do with BDD in my opinion. I’m not saying that using regular unit tests is a bad thing, but with&#160; behavior-driven development context is king. So these unit tests are perfect examples of ‘<a href="http://elegantcode.com/2008/12/30/dont-sell-out-on-the-context-dude/">context betrayal</a>’ when following the BDD approach. </p>

<p>Lets see what MSpec can bring to the table for these kind of scenarios:</p>

<pre class="csharpcode">[Subject(<span class="kwrd">typeof</span>(EmailSpecification), <span class="str">&quot;is satisfied&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_validating_an_email_address_with_a_number_in_the_local_part
    : email_specification_specs
{
    Establish context = () =&gt;
        EmailAddress = <span class="str">&quot;one2@three.com&quot;</span>;

    Behaves_like&lt;SatisfiedSpecificationBehavior&gt; a_satisfied_specification;
}

[Subject(<span class="kwrd">typeof</span>(EmailSpecification), <span class="str">&quot;is satisfied&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_validating_an_email_address_with_a_number_in_the_domain_name
    : email_specification_specs
{
    Establish context = () =&gt;
        EmailAddress = <span class="str">&quot;one@two3.com&quot;</span>;

    Behaves_like&lt;SatisfiedSpecificationBehavior&gt; a_satisfied_specification;
}

[Subject(<span class="kwrd">typeof</span>(EmailSpecification), <span class="str">&quot;is satisfied&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_validating_an_email_address_without_an_At_sign
    : email_specification_specs
{
    Establish context = () =&gt;
        EmailAddress = <span class="str">&quot;one_two.com&quot;</span>;

    Behaves_like&lt;UnsatisfiedSpecificationBehavior&gt; an_unsatisfied_specification;
}

[Subject(<span class="kwrd">typeof</span>(EmailSpecification), <span class="str">&quot;is satisfied&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_validating_an_email_address_without_a_domain
    : email_specification_specs
{
    Establish context = () =&gt;
        EmailAddress = <span class="str">&quot;one_two@&quot;</span>;

    Behaves_like&lt;UnsatisfiedSpecificationBehavior&gt; an_unsatisfied_specification;
}</pre>
<style type="text/css">

.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>In order to escape ‘context betrayal’, we’ve split up every context into a separate context/specification. In order to reduce the amount of effort caused by duplicate code, we stripped the context setup to the bare minimum (just a particular e-mail address in this case). The observations are isolated into MSpec behaviors which provides a very readable description of their outcome. Lets take a look at what is needed in order to get these <em>behaviors</em> to work.</p>

<p>But first lets take at look at the abstract base class that we’ve used for the context/specifications we’ve just shown.</p>

<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">abstract</span> <span class="kwrd">class</span> email_specification_specs
{
    Establish context = () =&gt;
    {
        SUT = <span class="kwrd">new</span> EmailSpecification();
    };

    Because of = () =&gt;
        Result = SUT.IsSatisfiedBy(EmailAddress);

    <span class="kwrd">protected</span> <span class="kwrd">static</span> Boolean Result;
    <span class="kwrd">protected</span> <span class="kwrd">static</span> String EmailAddress { get; set; }
    <span class="kwrd">protected</span> <span class="kwrd">static</span> EmailSpecification SUT { get; set; }
}</pre>

<p><style type="text/css">

.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style></p>

<p>&#160;</p>

<p>We abstracted as much as possible into this base class in order to remove duplication in the context/specifications. The creation of the subject-under-test and the calling of its <em>IsSatisfiedBy</em> method, but the important one is the declaration of the <em>Result</em> field. This field contains the outcome of the <em>IsSatisfiedBy</em> method. Finally, lets have a look at the behaviors themselves:</p>

<pre class="csharpcode">[Behaviors]
<span class="kwrd">public</span> <span class="kwrd">class</span> SatisfiedSpecificationBehavior
{
    <span class="kwrd">protected</span> <span class="kwrd">static</span> Boolean Result;
    
    It should_satisfy_the_specification = () =&gt;
        Result.ShouldBeTrue();
}

[Behaviors]
<span class="kwrd">public</span> <span class="kwrd">class</span> UnsatisfiedSpecificationBehavior
{
    <span class="kwrd">protected</span> <span class="kwrd">static</span> Boolean Result;

    It should_not_satisfy_the_specification = () =&gt;
        Result.ShouldBeFalse();
}</pre>
<style type="text/css">

.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>In order to create an MSpec behavior, we just have to create a separate class that we decorate with the <em>Behaviors</em> attribute. Also notice that we have the same declaration of the <em>Result</em> field. MSpec ensures that this field gets initialized with the value of the other <em>Result</em> field that is set in the base class of the context/specifications. Note that you don’t necessarily need to put this field in a base class. You can have that field in every context/specification if you’d like (not sure why) as long as the names match with the fields used in the defined behaviors.</p>

<p>I personally like the way how the MSpec contributors tried to solve testing the same logic with different input patterns and the syntax they provided to back this up.&#160;&#160; </p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/02/26/behaviors-with-mspec/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>MSpec and Auto Mocking</title>
		<link>http://elegantcode.com/2010/02/23/mspec-and-auto-mocking/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=mspec-and-auto-mocking</link>
		<comments>http://elegantcode.com/2010/02/23/mspec-and-auto-mocking/#comments</comments>
		<pubDate>Tue, 23 Feb 2010 20:38:54 +0000</pubDate>
		<dc:creator>Jan Van Ryswyck</dc:creator>
				<category><![CDATA[BDD]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/02/23/mspec-and-auto-mocking/</guid>
		<description><![CDATA[In my previous post, I explained how to get started with Machine.Specifications (or MSpec for short) and showed you how the syntax for context/specifications looks like when using this BDD framework. For this post, I want to show you how to use an auto mocking container (we’ll be using the one provided by StructureMap off [...]]]></description>
			<content:encoded><![CDATA[<p>In my <a href="http://elegantcode.com/2010/02/19/getting-started-with-machine-specifications-mspec/">previous post</a>, I explained how to get started with <a href="http://github.com/machine/machine.specifications">Machine.Specifications</a> (or MSpec for short) and showed you how the syntax for context/specifications looks like when using this BDD framework. For this post, I want to show you how to use an <a href="http://vanryswyckjan.blogspot.com/2008/01/automocking-container.html">auto mocking container</a> (we’ll be using the one provided by StructureMap off course).</p>  <p>We’ll use the same example as the one used in the previous post, but now we’ll deal with the message handler that makes a particular customer preferred.</p> <style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>  <pre class="csharpcode"><span class="rem">//</span>
<span class="rem">// Subject under test</span>
<span class="rem">//</span>
<span class="kwrd">public</span> <span class="kwrd">class</span> MakeCustomerPreferredMessageHandler
{
    <span class="kwrd">private</span> <span class="kwrd">readonly</span> ICustomerRepository&lt;ICanMakeCustomerPreferred&gt; _repository;

    <span class="kwrd">public</span> MakeCustomerPreferredMessageHandler(
        ICustomerRepository&lt;ICanMakeCustomerPreferred&gt; repository)
    {
        _repository = repository;
    }

    <span class="kwrd">public</span> <span class="kwrd">void</span> Handle(MakeCustomerPreferredMessage message)
    {
        var customer = _repository.Get(message.CustomerId);
        <span class="kwrd">if</span>(<span class="kwrd">null</span> == customer)
            <span class="kwrd">throw</span> <span class="kwrd">new</span> InvalidOperationException(
                <span class="str">&quot;No customer for specified identifier&quot;</span>);
        
        customer.MakePreferred();
        _repository.Save(customer);
    }
}</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>The <em>Customer</em> class implements a ‘<a href="http://martinfowler.com/bliki/RoleInterface.html">role interface’</a> called <em>ICanMakeCustomerPreferred</em>. We retrieve a customer from the repository and make it preferred. We throw an exception in case the customer cannot be found in the data store.</p>

<p>Here are the context/specifications for this easy example:</p>

<pre class="csharpcode">[Subject(<span class="str">&quot;Making a customer preferred&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_making_a_customer_preferred
    : context_specification&lt;MakeCustomerPreferredMessageHandler&gt;
{
    Establish context = () =&gt;
    {
        _message = <span class="kwrd">new</span> MakeCustomerPreferredMessage { CustomerId = 6412 };

        Repository.Stub(repository =&gt; repository.Get(_message.CustomerId))
            .Return(Customer);
    };

    Because of = () =&gt; 
        SUT.Handle(_message);
    
    It should_mark_the_customer_as_preferred = () =&gt;
        Customer.AssertWasCalled(customer =&gt; customer.MakePreferred());

    It should_save_the_customer_in_the_repository = () =&gt;
        Repository.AssertWasCalled(repository =&gt; repository.Save(Customer));

    <span class="kwrd">private</span> <span class="kwrd">static</span> ICanMakeCustomerPreferred Customer
    {
        get { <span class="kwrd">return</span> Dependency&lt;ICanMakeCustomerPreferred&gt;(); }
    }

    <span class="kwrd">private</span> <span class="kwrd">static</span> ICustomerRepository&lt;ICanMakeCustomerPreferred&gt; Repository
    {
        get { <span class="kwrd">return</span> Dependency&lt;ICustomerRepository&lt;ICanMakeCustomerPreferred&gt;&gt;(); }
    }

    <span class="kwrd">private</span> <span class="kwrd">static</span> MakeCustomerPreferredMessage _message;
}

[Subject(<span class="str">&quot;Making a customer preferred&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_making_an_unexisting_customer_preferred
    : context_specification&lt;MakeCustomerPreferredMessageHandler&gt;
{
    Establish context = () =&gt;   
    {
        _message = <span class="kwrd">new</span> MakeCustomerPreferredMessage() { CustomerId = 61544 };

        Dependency&lt;ICustomerRepository&lt;ICanMakeCustomerPreferred&gt;&gt;()
            .Stub(repository =&gt; repository.Get(_message.CustomerId))
            .Return(<span class="kwrd">null</span>);
    };

    Because of = () =&gt;
        _resultingException = Catch.Exception(() =&gt; SUT.Handle(_message));

    It should_result_in_an_error = () =&gt;
        _resultingException.ShouldBeOfType&lt;InvalidOperationException&gt;();

    <span class="kwrd">private</span> <span class="kwrd">static</span> MakeCustomerPreferredMessage _message;
    <span class="kwrd">private</span> <span class="kwrd">static</span> Exception _resultingException;
}</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>I want to point out that all fields and properties are made static. This is needed so that the anonymous methods can access them. I’m also using a base class for these specifications which I’ll show next. This base class uses an auto mocking container for providing the requested mocks and stubs through the <em>Dependency</em> and <em>Stub</em> methods. </p>

<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">abstract</span> <span class="kwrd">class</span> context_specification&lt;TSubjectUnderTest&gt;
    <span class="kwrd">where</span> TSubjectUnderTest : <span class="kwrd">class</span>
{
    <span class="kwrd">private</span> <span class="kwrd">static</span> IAutoMockingContainer&lt;TSubjectUnderTest&gt; _autoMockingContainer;
    <span class="kwrd">protected</span> <span class="kwrd">static</span> TSubjectUnderTest SUT { get; set; }

    Establish context = () =&gt;
    {
        _autoMockingContainer = <span class="kwrd">new</span> StructureMapAMC&lt;TSubjectUnderTest&gt;();
        SUT = _autoMockingContainer.Create();     
    };
    
    Cleanup stuff = () =&gt; 
    {
        SUT = <span class="kwrd">null</span>;
        _autoMockingContainer = <span class="kwrd">null</span>;
    };

    <span class="kwrd">protected</span> <span class="kwrd">static</span> TDependency Dependency&lt;TDependency&gt;()
        <span class="kwrd">where</span> TDependency : <span class="kwrd">class</span>
    {
        <span class="kwrd">return</span> _autoMockingContainer.GetMock&lt;TDependency&gt;();
    }

    <span class="kwrd">protected</span> <span class="kwrd">static</span> TStub Stub&lt;TStub&gt;()
        <span class="kwrd">where</span> TStub : <span class="kwrd">class</span>
    {
        <span class="kwrd">return</span> _autoMockingContainer.GetStub&lt;TStub&gt;();
    }
}

<span class="kwrd">public</span> <span class="kwrd">interface</span> IAutoMockingContainer&lt;TSubject&gt;
    <span class="kwrd">where</span> TSubject : <span class="kwrd">class</span>
{
    TSubject Create();
    TMock GetMock&lt;TMock&gt;() <span class="kwrd">where</span> TMock : <span class="kwrd">class</span>;
    TStub GetStub&lt;TStub&gt;() <span class="kwrd">where</span> TStub : <span class="kwrd">class</span>;
}

<span class="kwrd">public</span> <span class="kwrd">class</span> StructureMapAMC&lt;TSubject&gt; 
    : IAutoMockingContainer&lt;TSubject&gt;
    <span class="kwrd">where</span> TSubject : <span class="kwrd">class</span>
{
    <span class="kwrd">private</span> <span class="kwrd">readonly</span> RhinoAutoMocker&lt;TSubject&gt; _rhinoAutoMocker;

    <span class="kwrd">public</span> StructureMapAMC()
    {
        _rhinoAutoMocker = 
            <span class="kwrd">new</span> RhinoAutoMocker&lt;TSubject&gt;(MockMode.AAA);
    }

    <span class="kwrd">public</span> TSubject Create()
    {
        <span class="kwrd">return</span> _rhinoAutoMocker.ClassUnderTest;
    }

    <span class="kwrd">public</span> TMock GetMock&lt;TMock&gt;() 
        <span class="kwrd">where</span> TMock : <span class="kwrd">class</span>
    {
        <span class="kwrd">return</span> GetDependency&lt;TMock&gt;();
    }

    <span class="kwrd">public</span> TStub GetStub&lt;TStub&gt;() 
        <span class="kwrd">where</span> TStub : <span class="kwrd">class</span>
    {
        <span class="kwrd">return</span> GetDependency&lt;TStub&gt;();
    }

    <span class="kwrd">private</span> TDependency GetDependency&lt;TDependency&gt;() 
        <span class="kwrd">where</span> TDependency : <span class="kwrd">class</span>
    {
        <span class="kwrd">return</span> _rhinoAutoMocker.Get&lt;TDependency&gt;();
    }
}</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>Notice that I’m using the <em>Establish</em> and <em>Cleanup</em> delegates in the <em>context_specification</em> base class. This doesn’t prevent that these can be used again in derived context/specifications. MSpec ensures that the anonymous methods are called in the right order. This means that the <em>Establish</em> method of the base class is called before the <em>Establish</em> method of the derived context/specifications.&#160;&#160;&#160;&#160; </p>

<p>Absolutely no rocket science here, but I figured it might come in handy when you need it. For the next post I’ll try to demonstrate how to deal with reusable behaviors.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/02/23/mspec-and-auto-mocking/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Getting Started With Machine.Specifications (MSpec)</title>
		<link>http://elegantcode.com/2010/02/19/getting-started-with-machine-specifications-mspec/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=getting-started-with-machine-specifications-mspec</link>
		<comments>http://elegantcode.com/2010/02/19/getting-started-with-machine-specifications-mspec/#comments</comments>
		<pubDate>Fri, 19 Feb 2010 21:34:17 +0000</pubDate>
		<dc:creator>Jan Van Ryswyck</dc:creator>
				<category><![CDATA[BDD]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/02/19/getting-started-with-machine-specifications-mspec/</guid>
		<description><![CDATA[Its been a while since I evaluated and evolved my approach to BDD. The way I’ve been doing BDD up until now is described in this blog post which goes way back to 2008. Everyone has kind of their own style nowadays. Below you can find the code of two context/specifications for a method named [...]]]></description>
			<content:encoded><![CDATA[<p>Its been a while since I evaluated and evolved my approach to BDD. The way I’ve been doing BDD up until now is described in <a href="http://elegantcode.com/2008/10/25/refining-contextspecification-bdd-using-rhino-mocks-35/">this blog post</a> which goes way back to 2008. Everyone has kind of their own style nowadays. Below you can find the code of two context/specifications for a method named <em>MakePreferred</em> on a <em>Customer </em>class. This simple example clarifies the style that I’ve been following up until now.</p> <style type="text/css">


.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style><style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>  <pre class="csharpcode">[TestFixture]
<span class="kwrd">public</span> <span class="kwrd">class</span> When_making_a_regular_customer_preferred
    : ContextSpecification&lt;Customer&gt;
{
    <span class="kwrd">protected</span> <span class="kwrd">override</span> Customer Create_subject_under_test()
    {
        <span class="kwrd">return</span> <span class="kwrd">new</span> Customer(<span class="kwrd">new</span>[] { _order });
    }

    <span class="kwrd">protected</span> <span class="kwrd">override</span> <span class="kwrd">void</span> Establish_context()
    {
        _order = <span class="kwrd">new</span> Order(<span class="kwrd">new</span>[] { <span class="kwrd">new</span> OrderItem(12), 
                                   <span class="kwrd">new</span> OrderItem(16) });
                                   
        _totalAmountWithoutDiscount = _order.TotalAmount;
    }

    <span class="kwrd">protected</span> <span class="kwrd">override</span> <span class="kwrd">void</span> Because()
    {
        SUT.MakePreferred();
    }

    [Test]
    <span class="kwrd">public</span> <span class="kwrd">void</span> Then_the_customer_should_be_marked_as_preferred()
    {
        SUT.IsPreferred.ShouldBeTrue();
    }

    [Test]
    <span class="kwrd">public</span> <span class="kwrd">void</span> Then_a_ten_percent_discount_should_be_applied_to_all_outstanding_orders()
    {
        _order.TotalAmount.ShouldBeEqualTo(
            _totalAmountWithoutDiscount * 0.9);
    }

    <span class="kwrd">private</span> Order _order;
    <span class="kwrd">private</span> Double _totalAmountWithoutDiscount;
}

[TestFixture]
<span class="kwrd">public</span> <span class="kwrd">class</span> When_making_a_preferred_customer_preferred
    : ContextSpecification&lt;Customer&gt;
{
    <span class="kwrd">protected</span> <span class="kwrd">override</span> Customer Create_subject_under_test()
    {
        var customer = <span class="kwrd">new</span> Customer(<span class="kwrd">new</span>[] { _order });
        customer.MakePreferred();
        <span class="kwrd">return</span> customer;
    }

    <span class="kwrd">protected</span> <span class="kwrd">override</span> <span class="kwrd">void</span> Establish_context()
    {
        _order = <span class="kwrd">new</span> Order(<span class="kwrd">new</span>[] { <span class="kwrd">new</span> OrderItem(12), 
                                   <span class="kwrd">new</span> OrderItem(16) });
        _totalAmountWithoutDiscount = _order.TotalAmount;
    }

    <span class="kwrd">protected</span> <span class="kwrd">override</span> <span class="kwrd">void</span> Because()
    {
        SUT.MakePreferred();
    }

    [Test]
    <span class="kwrd">public</span> <span class="kwrd">void</span> Then_no_additional_discount_should_be_applied_to_the_outstanding_orders()
    {
        _order.TotalAmount.ShouldNotBeEqualTo(
            _totalAmountWithoutDiscount * 0.81);
    }

    <span class="kwrd">private</span> Order _order;
    <span class="kwrd">private</span> Double _totalAmountWithoutDiscount;
}

<span class="rem">//</span>
<span class="rem">// Subject under test</span>
<span class="rem">//</span>
<span class="kwrd">public</span> <span class="kwrd">class</span> Customer
{
    <span class="kwrd">private</span> <span class="kwrd">readonly</span> List&lt;Order&gt; _orders;
    <span class="kwrd">public</span> Boolean IsPreferred { get; <span class="kwrd">private</span> set; }

    <span class="kwrd">public</span> Customer(IEnumerable&lt;Order&gt; orders)
    {
        _orders = <span class="kwrd">new</span> List&lt;Order&gt;(orders);
    }

    <span class="kwrd">public</span> <span class="kwrd">void</span> MakePreferred()
    {
        <span class="kwrd">if</span>(IsPreferred)    
            <span class="kwrd">return</span>;
    
        IsPreferred = <span class="kwrd">true</span>;
        _orders.ForEach(order =&gt; order.ApplyDiscount(10));
    }
}</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>The bottom line of this example is that preferred customers get a 10 percent discount. Customers that are already preferred do not get an additional discount or otherwise we’re out of business ;-). </p>

<p>I’ve been pretty happy with this approach so far, although sometimes there were some quirks associated with this. So it was time for me to look beyond the horizon again, trying to look for ways to improve. </p>

<p><a href="http://github.com/machine/machine.specifications">Machine.Specifications</a> or MSpec for short is something that has been on my ‘cool-things-to-learn-list’ for quite some time now. As you will see later in this post, the syntax is a bit different as one would come to expect from a context/specification framework that targets the C# programming language. Its seems to be heavily inspired by Scott Bellware’s <a href="http://code.google.com/p/specunit-net/">SpecUnit framework</a> and <a href="http://rspec.info/">RSpec</a>.</p>

<p>Lets see how to set things up first. </p>

<p>The most obvious starting point is downloading the bits and bytes. You can grab the <a href="http://github.com/machine/machine.specifications">source code</a> from GitHub and build it or you can wuss out like I did and get the latest build from the <a href="http://teamcity.codebetter.com/login.html">TeamCity.CodeBetter.com</a> builder server (you can log on as a guest and search the artifacts for a latest build).&#160; </p>

<p>When you’re heavily addicted to <a href="http://www.testdriven.net/">TestDriven.NET</a> like I am, then its possible to keep using this wonderful Visual Studio add-in for running MSpec context/specifications. Just create a directory named <em>Machine.Specifications</em> in {$Program_Files}\TestDriven.NET 2.0 and copy the following files:</p>

<ul>
  <li>Machine.Specifications.dll</li>

  <li>Machine.Specifications.TDNetRunner.dll</li>

  <li>InstallTDNetRunner.bat</li>
</ul>

<ul>Run the InstallTDNetRunner.bat file and you’re able to run all MSpec context/specifications using TestDriven.NET.</ul>

<p>I also strongly encourage you to install the plugin for the Resharper test runner (if only to prevent some Resharper warnings later on). First step is to add a directory named <em>Plugins</em> to the <em>Bin</em> directory of Resharper ({$Program_Files}\JetBrains\ReSharper\v4.5\Bin\). Then create a directory named <em>Machine.Specifications</em> in the <em>Plugins</em> directory you just created and copy the following files:</p>

<ul>
  <li>Machine.Specifications.dll</li>

  <li>Machine.Specifications.ReSharperRunner.4.5.dll</li>

  <li>InstallResharperRunner.4.5.bat</li>
</ul>

<p>Run the InstallResharperRunner.4.5.bat file and you’re also able to run MSpec context/specifications using the Resharper test runner.</p>

<p>I’m not going to put this off any longer. Lets look at the code of the context/specifications shown earlier but completely revamped using the MSpec syntax:</p>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<pre class="csharpcode">[Subject(<span class="str">&quot;Making a customer preferred&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_a_regular_customer_is_made_preferred 
{
    Establish context = () =&gt;
    {
        _order = <span class="kwrd">new</span> Order(<span class="kwrd">new</span>[] { <span class="kwrd">new</span> OrderItem(12), 
                                   <span class="kwrd">new</span> OrderItem(16) });
        _totalAmountWithoutDiscount = _order.TotalAmount;

        SUT = <span class="kwrd">new</span> Customer(<span class="kwrd">new</span>[] { _order });
    };

    Because of = () =&gt; 
        SUT.MakePreferred();

    It should_mark_the_customer_as_preferred = () =&gt;
        SUT.IsPreferred.ShouldBeTrue();
        
    It should_apply_a_ten_percent_discount_to_all_outstanding_orders = () =&gt;
        _order.TotalAmount.ShouldEqual(_totalAmountWithoutDiscount * 0.9);      

    <span class="kwrd">private</span> <span class="kwrd">static</span> Customer SUT;
    
    <span class="kwrd">private</span> <span class="kwrd">static</span> Order _order;
    <span class="kwrd">private</span> <span class="kwrd">static</span> Double _totalAmountWithoutDiscount;
}

[Subject(<span class="str">&quot;Making a customer preferred&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_a_preferred_customer_is_made_preferred
{
    Establish context = () =&gt;
    {
        _order = <span class="kwrd">new</span> Order(<span class="kwrd">new</span>[] { <span class="kwrd">new</span> OrderItem(12), 
                                   <span class="kwrd">new</span> OrderItem(16) });
        _totalAmountWithoutDiscount = _order.TotalAmount;

        SUT = <span class="kwrd">new</span> Customer(<span class="kwrd">new</span>[] { _order });
        SUT.MakePreferred();
    };

    Because of = () =&gt;
        SUT.MakePreferred();

    It should_apply_no_additional_discount_to_the_outstanding_orders = () =&gt; 
        _order.TotalAmount.ShouldNotEqual(_totalAmountWithoutDiscount * 0.81);

    <span class="kwrd">private</span> <span class="kwrd">static</span> Customer SUT;

    <span class="kwrd">private</span> <span class="kwrd">static</span> Order _order;
    <span class="kwrd">private</span> <span class="kwrd">static</span> Double _totalAmountWithoutDiscount;
}</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>I warned you about the syntax, didn’t I :-). It only took me a couple of seconds to get used to this syntax but now I’m completely hooked. Instead of using methods and attributes, MSpec utilizes delegates and anonymous methods. But there’s more. </p>

<p>When using <a href="http://www.nunit.com/index.php">NUnit</a> for writing context/ specifications, the <em>Establish_context</em> and <em>Because</em> methods of the example shown earlier is executed before every observation (test). With MSpec, the <em>Establish</em> and <em>Because</em> anonymous methods are executed only once for every context no matter how many observations a particular context class contains. Big difference? Well, at first glance not but on second hand it does make <a href="http://elegantcode.com/2008/12/30/dont-sell-out-on-the-context-dude/">selling out on the context</a> a bit more difficult as it will probably blow up in your face sooner than later. You can force MSpec to execute the <em>Establish</em> and <em>Because</em> anonymous methods before every observation by applying the <em>SetupForEachSpecification</em> attribute to the context class, but I strongly encourage you to stay away from that unless absolutely needed.</p>

<p>Also notice that the fields in the contexts are now all static. This is needed so that the anonymous methods can access those.&#160;&#160;&#160;&#160;&#160; </p>

<p>Running these context/specifications using TestDriven.NET yields the following output in the output window of Visual Studio:</p>

<blockquote>
  <p><font face="Arial">Making a customer preferred, when a regular customer is made preferred
      <br />» should mark the customer as preferred

      <br />» should apply a ten percent discount to all outstanding orders</font></p>

  <p><font face="Arial">Making a customer preferred, when a preferred customer is made preferred
      <br />» should apply no additional discount to the outstanding orders</font></p>
</blockquote>

<p>What’s not to like? Well, the only downside so far is that Resharper was giving me some warnings about classes and fields not being used etc. … . Many of those warnings disappeared by registering the MSpec plugin for the Resharper test runner as I explained earlier.</p>

<p>So far, so good. I’ve got two more posts coming up on MSpec, so stay tuned.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/02/19/getting-started-with-machine-specifications-mspec/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Unity/Moq &#8211; AutoMocker or AutoMockingContainer</title>
		<link>http://elegantcode.com/2010/01/03/unitymoq-automocker-or-automockingcontainer/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=unitymoq-automocker-or-automockingcontainer</link>
		<comments>http://elegantcode.com/2010/01/03/unitymoq-automocker-or-automockingcontainer/#comments</comments>
		<pubDate>Sun, 03 Jan 2010 16:52:33 +0000</pubDate>
		<dc:creator>Jason Jarrett</dc:creator>
				<category><![CDATA[TDD]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Tools and Utilities]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/01/03/unitymoq-automocker-or-automockingcontainer/</guid>
		<description><![CDATA[What is an Auto Mocking Container? This post started to get a little long, so I won’t re-explain the concept. Joshua Flanagan wrote a nice overview at his Los Techies blog: Auto mocking Explained. My post is mainly here to describe the Unity version of an automocking container I threw together. In Jan 2009 I [...]]]></description>
			<content:encoded><![CDATA[<h4>What is an Auto Mocking Container?</h4>  <p>This post started to get a little long, so I won’t re-explain the concept.</p>  <p><a href="http://www.lostechies.com/blogs/joshuaflanagan/default.aspx">Joshua Flanagan</a> wrote a nice overview at his <a href="http://www.lostechies.com/">Los Techies</a> blog: <a href="http://www.lostechies.com/blogs/joshuaflanagan/archive/2009/02/03/auto-mocking-explained.aspx"><strong>Auto mocking Explained</strong></a>.</p>  <p>My post is mainly here to describe the Unity version of an automocking container I threw together.</p>  <h4>In Jan 2009 I blogged about my initial version of the Unity AutoMocker - Why am I blogging about it again?</h4>  <p>I originally wrote the AutoMocker for the Unity container a year ago (Jan 2009, in Silverlight), and finally got around to placing the code up in the <a href="http://code.google.com/p/moq-contrib/">moq-contrib</a> project in June of 2009.</p>  <p>I’m writing another post today in hopes to:</p>  <ol>   <li>Get some feedback on how this little snippet of code should continue. </li>    <li>Give a little more how-to/example code </li>    <li>Describe some updates I made since I originally created it.&#160; </li> </ol>  <h4>Where can I get it?</h4>  <p><strong>This is one part where I’d appreciate some feedback.</strong></p>  <p>I have two slightly different versions out there (currently).</p>  <p>I have one version at the <a href="http://code.google.com/p/elegantcode/source/browse/#svn/trunk/Coders/JasonJarrett/UnityAutoMocker">ElegantCode</a> repository where I was working on it, and the other I threw up at <a href="http://code.google.com/p/moq-contrib/">moq-contrib</a>.</p>  <p>The core of the UnityAutoMockContainer is the same in both places, it’s how the tests are separated out that differ.</p>  <p>In the <a href="http://code.google.com/p/elegantcode/source/browse/#svn/trunk/Coders/JasonJarrett/UnityAutoMocker">ElegantCode repository</a> it’s an all in one self contained single file (that you can copy into your own test project(s)). You can then setup a single test in your own testing framework that runs all internal automocker tests (in case you need to modify it yourself, and don’t want to break any existing functionality). EX: test</p>  <pre class="brush: csharp;">[Test]
public void Should_run_all_UnityAutoMockContainer_internal_tests()
{
    Moq.AutoMocking.SelfTesting.UnityAutoMockContainerFixture
        .RunAllTests(Console.WriteLine);
}</pre>

<p>I kind of like this format as it makes it easy to port between test libraries. Can’t say I like having the tests in the same file as the core, but it certainly is not a large chunk of code (so far) so it’s relatively small to maintain and definitely easier to manage as a single .cs file than another assembly (which would have to be version dependent on both Unity and Moq).</p>

<p>The <a href="http://code.google.com/p/moq-contrib/">moq-contrib</a> is definitely where I think this helper should end up (and it is there). I just happened to break the tests out into the Silverlight test project and the core is alone in a file. </p>

<p>It’s current state isn’t as easy to copy to a test library (Silverlight/Desktop/Unity 1.2/Unity 2.0) as the one at <a href="http://elegantcode.com/">ElegantCode</a>. <strong>What does anyone think?</strong> Should I put them all together in one file?</p>

<p>However it ends up (1. all in one file or two (1 test) (1 core)) it will continue to be maintained on the <a href="http://code.google.com/p/moq-contrib/">moq-contrib</a> project.</p>

<h4>What is the high level API of the container?</h4>

<p>It’s pretty simple, (currently) there are four methods on the container.</p>

<p><strong>Two for registering items with the container</strong>. Say you want to register an already created instance, or say you want to map an interface to a concrete class and _not_ have the container generate mocks automatically for special cases. </p>

<p>And <strong>two for pulling items out of the container</strong>. Whether you want a instance of T or a Mock&lt;T&gt;, it gives you ways to retrieve both.</p>

<blockquote>
  <p><a href="http://elegantcode.com/wp-content/uploads/2010/01/image.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://elegantcode.com/wp-content/uploads/2010/01/image_thumb.png" width="396" height="106" /></a> </p>
</blockquote>

<h4>How can I setup my own registrations with the container? </h4>

<p>Say I don’t want to have the container generate mocks for specific items and I want to supply specific configuration to the UnityContainer.</p>

<blockquote>
  <p>public UnityAutoMockContainer RegisterInstance&lt;TService&gt;(TService instance)</p>

  <p>public UnityAutoMockContainer Register&lt;TService, TImplementation&gt;() 
    <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; where TImplementation : TService</p>
</blockquote>

<p><strong>Note</strong>: both of these registration methods return the container itself so you can fluently stack registration. <strong>EX:</strong></p>

<pre class="brush: csharp;">AutoMockContainer
    .Register&lt;IServiceA, ServiceA&gt;()
    .Register&lt;IServiceB, ServiceB&gt;();</pre>

<p><strong>Let me know</strong>: I haven’t tested or played around with how this automocking container deals with any container specific xml configuration… So although I don’t think you should probably have that in a test assembly (stuff happens). Let me know if there are any issues.</p>

<h4>How do I get items out of the container?</h4>

<p>First is the Resolve&lt;T&gt;(). It will pull an item T out of the container. (Creating it if not already existing)</p>

<blockquote>
  <p>public T Resolve&lt;T&gt;()</p>
</blockquote>

<p>When T is an interface Resolve&lt;T&gt; (unless you setup registration specifically with the container) should return basically “(new Mock&lt;T&gt;()).Object”</p>

<p>When T is a concrete Class, the container should return an instance of T and any of it’s dependencies will be satisfied by mocks. (Note that T will not be any sort of mocked instance of T, unless you used the GetMock&lt;T&gt; as described below first)</p>

<blockquote>
  <p>public Mock&lt;T&gt; GetMock&lt;T&gt;() where T : class</p>
</blockquote>

<p>When T is an interface GetMock&lt;T&gt; should return basically “(new Mock&lt;T&gt;())” </p>

<p>When T is a concrete Class, the container should return a new Mock&lt;T&gt;() and any of it’s dependencies will be satisfied by mocks.</p>

<h4>How do I use the UnityAutoMockContainer?</h4>

<p>It’s pretty basic, you first create an instance of the UnityAutoMockContainer, and from there you can ask it for mocks of an (Interface, Class, or Abstract Class).</p>

<p>If you request an instance of a concrete class, or abstract class, the UnityAutoMockContainer will stuff mocks in for any constructor dependencies of your concrete class (if it can). You can then request from the container those same dependencies one at a time and either apply mocking setups or verifications.</p>

<blockquote>
  <p><strong>NOTE:</strong> Anything the container creates will live as a singleton instance in the container. So any other requests from the container will always return the originally created instance. Therefore, each distinct scenario in a test suite should have their own instances of the container.</p>
</blockquote>

<p>Below his an example of how you can leverage the container in some tests. Given this base fixture class…</p>

<pre class="brush: csharp;">public class FixtureBase
{
    private readonly UnityAutoMockContainer _autoMockContainer = new UnityAutoMockContainer();

    protected UnityAutoMockContainer AutoMockContainer
    {
        get { return _autoMockContainer; }
    }

    [TestFixtureSetUp]
    public void SetupContext_ALL()
    {
        Before_all_tests();
        Because();
    }

    [TestFixtureTearDown]
    public void TearDownContext_ALL()
    {
        After_all_tests();
    }

    protected virtual void Before_all_tests()
    {
    }

    protected virtual void Because()
    {
    }

    protected virtual void After_all_tests()
    {
    }
}</pre>

<p>If I were given the following system to test.</p>

<pre class="brush: csharp;">public interface IServiceA { void RunA(); }
public interface IServiceB { void RunB(); }

public class TestComponent
{
    public TestComponent(IServiceA serviceA, IServiceB serviceB)
    {
        ServiceA = serviceA;
        ServiceB = serviceB;
    }

    public IServiceA ServiceA { get; private set; }
    public IServiceB ServiceB { get; private set; }

    public void RunAll()
    {
        if (!HowDidItGo())
            return;
        ServiceA.RunA();
        ServiceB.RunB();
    }

    public virtual bool HowDidItGo()
    {
        // some really nasty untestable code
        return true;
    }
}</pre>

<p>The below example demonstrates simply verifying some behavior on the mocked dependencies of the system under test.</p>

<pre class="brush: csharp;">[TestFixture]
public class Example__how_to_pull_items_from_the_UnityAutoMockContainer_when_verifying_behavior_after_an_action_was_taken 
    : FixtureBase
{
    private TestComponent _testComponent;

    protected override void Before_all_tests()
    {
        base.Before_all_tests();
        _testComponent = AutoMockContainer.Resolve&lt;TestComponent&gt;();
    }

    protected override void Because()
    {
        _testComponent.RunAll();
    }

    [Test]
    public void Should_run_ServiceA_RunA()
    {
        AutoMockContainer
            .GetMock&lt;IServiceA&gt;()
            .Verify(v =&gt; v.RunA(), Times.Once());
    }

    [Test]
    public void Should_run_ServiceB_RunB()
    {
        AutoMockContainer
            .GetMock&lt;IServiceB&gt;()
            .Verify(v =&gt; v.RunB(), Times.Once());
    }
}</pre>

<p>Next, you may have noticed that the system under test had a complicated internal method (that may not necessarily be testable). You can use the AutoMocker to create the system under test as a Mock itself, so we can override some of the behavior. Here’s how you could quickly do that. </p>

<blockquote>
  <p><strong>Aside</strong>: I’m not saying this is a good practice or aids in good component design, just saying it’s possible</p>
</blockquote>

<pre class="brush: csharp;">[TestFixture]
public class Example__how_to_use_the_UnityAutoMockContainer_to_override_a_method_on_the_SystemUnderTest_to_test_a_certain_behavior
    : FixtureBase
{

    private TestComponent _testComponent;

    protected override void Before_all_tests()
    {
        base.Before_all_tests();
        var mockTestComponent = AutoMockContainer.GetMock&lt;TestComponent&gt;();

        mockTestComponent
            .Setup(s =&gt; s.HowDidItGo())
            .Returns(false);

        _testComponent = mockTestComponent.Object;
    }

    protected override void Because()
    {
        _testComponent.RunAll();
    }

    [Test]
    public void Should_run_ServiceA_RunA()
    {
        AutoMockContainer
            .GetMock&lt;IServiceA&gt;()
            .Verify(v =&gt; v.RunA(), Times.Never());
    }

    [Test]
    public void Should_run_ServiceB_RunB()
    {
        AutoMockContainer
            .GetMock&lt;IServiceB&gt;()
            .Verify(v =&gt; v.RunB(), Times.Never());
    }
}</pre>

<p>&#160;</p>

<p>It’s amazing how much redundant test setup code this little helper has saved me in my tests. I hope others can find some use with this as well.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/01/03/unitymoq-automocker-or-automockingcontainer/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>StatLight &#8211; Goes Open Source</title>
		<link>http://elegantcode.com/2009/12/10/statlight-goes-open-source/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=statlight-goes-open-source</link>
		<comments>http://elegantcode.com/2009/12/10/statlight-goes-open-source/#comments</comments>
		<pubDate>Fri, 11 Dec 2009 03:26:55 +0000</pubDate>
		<dc:creator>Jason Jarrett</dc:creator>
				<category><![CDATA[Esoterica]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[TDD]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Tools and Utilities]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/12/10/statlight-goes-open-source/</guid>
		<description><![CDATA[Although I made a very minor attempt at making StatLight a “for-sale” product, I knew when I started that open-source was most likely going to be my long term path for StatLight. What is it? (Silverlight Testing Automation Tool) StatLight is a tool developed for automating the setup, running, and gathering results of Silverlight unit [...]]]></description>
			<content:encoded><![CDATA[Although I made a very minor attempt at making <a href="http://statlight.net" target="_blank">StatLight</a> a “for-sale” product, I knew when I started that open-source was most likely going to be my long term path for <a href="http://statlight.net" target="_blank">StatLight</a>.
<h5>What is it? (Silverlight Testing Automation Tool)</h5>
StatLight is a tool developed for automating the setup, running, and gathering results of Silverlight unit tests. StatLight helps to speed up the feedback cycles while practicing<a href="http://en.wikipedia.org/wiki/Test-driven_development"> TDD</a>/<a href="http://en.wikipedia.org/wiki/Behavior_Driven_Development">BDD</a>/(insert your test style here) during Silverlight development.
<h5>Where can I get StatLight?</h5>
<a href="http://StatLight.CodePlex.com">http://StatLight.CodePlex.com</a>
<h4>Happy Coding !!!</h4>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/12/10/statlight-goes-open-source/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Wrapping up the StructureMap Automocking Container</title>
		<link>http://elegantcode.com/2009/11/30/wrapping-up-the-structuremap-automocking-container/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=wrapping-up-the-structuremap-automocking-container</link>
		<comments>http://elegantcode.com/2009/11/30/wrapping-up-the-structuremap-automocking-container/#comments</comments>
		<pubDate>Mon, 30 Nov 2009 07:21:43 +0000</pubDate>
		<dc:creator>Richard Cirerol</dc:creator>
				<category><![CDATA[TDD]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Unit Testing]]></category>
		<category><![CDATA[StructureMap; Automocking; MSpec;]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/11/30/wrapping-up-the-structuremap-automocking-container/</guid>
		<description><![CDATA[<p><font color="#804040"><strong>UPDATE</strong>: I apologize…the original wrapper did not allow injected dependencies.&#160; I have fixed this bug and updated the sample.</font></p> I have been using StructureMap.AutoMocking with MSpec (Machine.Specifications) and Rhino.Mocks for a few months now.  Although I am very comfortable with the patterns that emerge from using the frameworks together, introducing StructureMap.Automocking to other developers is sometimes challenging. I decided to wrap the details of the container to make the intention clearer and explanation easier.  I have started using this wrapper in my projects, and have found it makes building up specifications more efficient in my daily coding.]]></description>
			<content:encoded><![CDATA[<span style="color: #804040;"><strong>UPDATE</strong>: I apologize…the original wrapper did not allow injected dependencies.  I have fixed this bug and updated the sample.</span>

I have been using StructureMap.AutoMocking with MSpec (Machine.Specifications) and Rhino.Mocks for a few months now.  Although I am very comfortable with the patterns that emerge from using the frameworks together, introducing StructureMap.Automocking to other developers is sometimes challenging.

When viewing a specification or test set up with the Rhino.Mocks or Moq automocking container, what is being tested is not readily apparent.  Once the concept is explained and demonstrated, these same developers seem to have no issue with maintaining the specifications/tests.

I decided to wrap the details of the container to make the intention clearer and explanation easier.  I have started using this wrapper in my projects, and have found it makes building up specifications more efficient in my daily coding.

Let me know whether this is useful to you, or how it could be made more useful.
<h4>The Examples</h4>
Let’s contrive an example.  We’ll say we have a coffee machine that grinds its own beans before brewing. However, the hopper has to have beans before starting the grind.  Here is the basic specification:
<table border="1" cellspacing="0" cellpadding="2" width="533">
<tbody>
<tr>
<td width="117" valign="top">Action/Behavior</td>
<td width="414" valign="top">Prepare coffee grounds for 12 cups of coffee</td>
</tr>
<tr>
<td rowspan="2" width="117" valign="top">Expectations</td>
<td width="414" valign="top">Should check that hopper has beans (mock returns true)</td>
</tr>
<tr>
<td width="414" valign="top">Because hopper has beans, should ask grinder to grind enough beans for 12 cups of coffee</td>
</tr>
</tbody></table>
We could start without a container, using Rhino.Mocks to build up the CoffeeMachine dependencies manually:
<pre class="brush: csharp;">[Subject(typeof(CoffeeMachine),"using vanilla Rhino.Mocks")]
public class Example01_when_preparing_coffee_grounds
{
    Establish context = () =&gt;
        {
            Grinder = MockRepository.GenerateMock&lt;IGrinder&gt;();
            Hopper = MockRepository.GenerateMock&lt;IHopper&gt;();
            Hopper.Expect(x =&gt; x.HasBeans()).Return(true);
            CoffeeMachine = new CoffeeMachine(Grinder, Hopper);
        };

    Because of = () =&gt; _coffeeMachine.PrepareCoffeeGrounds(12);

    It should_check_if_hopper_has_beans = () =&gt; Hopper.VerifyAllExpectations();
    It should_grind_coffee = () =&gt; Grinder.AssertWasCalled(x =&gt; x.Grind(12));

    static IGrinder Grinder;
    static IHopper Hopper;
    static CoffeeMachine CoffeeMachine;
}</pre>
For those of you not familiar with the MSpec style, please refer to the following posts:
<ul>
	<li><a href="http://blog.wekeroad.com/blog/make-bdd-your-bff-2/" target="_blank">Make BDD Your BFF</a></li>
	<li><a href="http://www.lostechies.com/blogs/seanbiefeld/archive/2009/08/25/step-by-step-to-using-machine-specifications-with-resharper.aspx" target="_blank">Step by Step to Using MSpec (Machine.Specifications) with ReSharper</a></li>
	<li><a href="http://elegantcode.com/2009/07/05/mspec-take-2/" target="_blank">MSpec - Take 2</a></li>
	<li><a href="http://marcinobel.com/index.php/mspec-bdd-installer/" target="_blank">MSpec BDD framework installer</a></li>
	<li><strong>Updated! </strong>From the <a href="http://blog.cwa.me.uk/2009/11/30/the-morning-brew-487/" target="_blank">Morning Brew #487</a>: BDD with MSpec and Rhino Auto Mocks, parts  <a href="http://telldontask.wordpress.com/2009/11/10/bdd-with-mspec-and-rhino-auto-mocks/" target="_blank">1</a>, <a href="http://telldontask.wordpress.com/2009/11/19/bdd-with-mspec-and-rhino-auto-mocks-part-2/" target="_blank">2</a>, and <a href="http://telldontask.wordpress.com/2009/11/29/bdd-with-mspec-and-rhino-auto-mocks-part-3/" target="_blank">3</a>
Here is the same specification using the RhinoAutoMocker&lt;T&gt; class provided by StructureMap.AutoMocking:</li>
</ul>
<pre class="brush: csharp;">[Subject(typeof(CoffeeMachine),"using RhinoAutoMocker&lt;CoffeeMachine&gt;")]
public class Example02_when_preparing_coffee_grounds
{
    Establish context = () =&gt;
        {
            CoffeeMachine = new RhinoAutoMocker&lt;CoffeeMachine&gt;();
            Grinder = CoffeeMachine.Get&lt;IGrinder&gt;();
            Hopper = CoffeeMachine.Get&lt;IHopper&gt;();
            Hopper.Expect(x =&gt; x.HasBeans()).Return(true);
        };

    Because of = () =&gt; v.ClassUnderTest.PrepareCoffeeGrounds(12);

    It should_check_if_hopper_has_beans = () =&gt; Hopper.VerifyAllExpectations();
    It should_grind_coffee = () =&gt; Grinder.AssertWasCalled(x =&gt; x.Grind(12));

    static IGrinder Grinder;
    static IHopper Hopper;
    static RhinoAutoMocker&lt;CoffeeMachine&gt; CoffeeMachine;
}</pre>
Although I think this looks cleaner, the initialization of CoffeeMachine causes some confusion. Unfortunately, a common question would be, “Is RhinoAutoMocker&lt;CoffeeMachine&gt; creating a mocked version of CoffeeMachine?” Well, not exactly.

RhinoAutoMocker is an implementation of the AutoMocker base class which uses StructureMap to fill dependencies.  The RhinoAutoMocker implementation of the container uses Rhino.Mocks to generate all of dependencies of the target class, whereas the MoqAutoMocker implementation uses Moq.  (Optionally, the target class can be partially mocked in order to further isolate behavior.)  We then retrieve the class under test (in this case, CoffeeMachine) and its dependencies (IGrinder and IHopper) from the container for use.

If you do not need to setup any expectations in the specification, there is no need to retrieve the dependency from the container.  However, in this specification, we need both dependencies.

<em>(Incidentally, I do not like the ClassUnderTest name.  I may end up changing this to Instance, ClassInstance, TargetClass, or something similar.  Suggestions?)</em>

By moving the initialization of the RhinoAutoMocker to a base class, some of the chattiness of the context can be hidden.
<ul>
<pre class="brush: csharp;">[Subject(typeof(CoffeeMachine),"using RhinoAutoMocker base")]
public class Example03_when_preparing_coffee_grounds : with_rhinoautomocker
{
    Establish context = () =&gt; Hopper.Expect(x =&gt; x.HasBeans()).Return(true);

    Because of = () =&gt; CoffeeMachine.ClassUnderTest.PrepareCoffeeGrounds(12);

    It should_check_if_hopper_has_beans = () =&gt; Hopper.VerifyAllExpectations();
    It should_grind_coffee = () =&gt; Grinder.AssertWasCalled(x =&gt; x.Grind(12));

}

[Subject("using RhinoAutoMocker&lt;T&gt;")]
public class with_rhinoautomocker
{
    protected static IGrinder Grinder;
    protected static IHopper Hopper;
    protected static RhinoAutoMocker&lt;CoffeeMachine&gt; CoffeeMachine;

    Establish context = () =&gt;
    {
        CoffeeMachine = new RhinoAutoMocker&lt;CoffeeMachine&gt;();
        Grinder = CoffeeMachine.Get&lt;IGrinder&gt;();
        Hopper = CoffeeMachine.Get&lt;IHopper&gt;();
    };
}</pre>
However, we are still initializing and accessing the class in a less than optimal manner.To make the usage of the container a little more seamless, I decided to create a wrapper and factory for the AutoMocker.  Setup of the dependencies and expectations are done through an AutoMocker wrapper object.  The instance of the class under test is accessed through a ClassUnderTest object.
<h4>The Result</h4>
The specification (and base class) now look like this:
<pre class="brush: csharp;">[Subject(typeof(CoffeeMachine),"using coffee machine base")]
public class Example05_when_preparing_coffee_grounds : with_coffee_machine
{
    Establish context = () =&gt; Hopper.Expect(x =&gt; x.HasBeans()).Return(true);

    Because of = () =&gt; ClassUnderTest.PrepareCoffeeGrounds(12);

    It should_check_if_hopper_has_beans = () =&gt; Hopper.VerifyAllExpectations();
    It should_grind_coffee = () =&gt; Grinder.AssertWasCalled(x =&gt; x.Grind(12));
}

[Subject("using SpecificationFor&lt;CoffeeMachine&gt;")]
public class with_coffee_machine : SpecificationFor&lt;CoffeeMachine&gt;
{
    protected static IGrinder Grinder;
    protected static IHopper Hopper;

    public with_coffee_machine
    {
        Grinder = AutoMocker.Get&lt;IGrinder&gt;();
        Hopper = AutoMocker.Get&lt;IHopper&gt;();
    }
}</pre>
As you can see, the base class inherits from SpecificationFor&lt;T&gt;.  The default constructor uses Rhino.Mocks(MockMode.AAA) to generate the dependencies.  It then exposes a AutoMocker object, which is just the wrapper around the AutoMocker base class.  It also exposes a ClassUnderTest object.  If I didn’t need to use the dependencies, I could make the <em>Example05_when_preparing_coffee_grounds</em> class inherit from <em>SpecificationFor&lt;CoffeeMachine&gt; </em>instead of inheriting from the base class<em>.</em>
<h4>The Code</h4>
I have included the code for the wrapper below for your review.  The code and six examples are available on my <a href="http://codeprogression.googlecode.com/svn/trunk/CodeProgression.Framework.Testing" target="_blank">Google code repository</a>. The repository also includes an example using the MoqAutoMocker.  All the examples have the same assertions, but are built up using the different techniques.
<pre class="brush: csharp;">namespace CodeProgression.Framework.Testing
{
    public abstract class SpecificationFor&lt;T&gt; where T: class
    {
        protected static ClassUnderTest&lt;T&gt; Factory;

        // UPDATE 2009-12-21:
        //   Moved initialization here
        protected static T ClassUnderTest {get {return AutoMocker.Instance;} }

        protected SpecificationFor()
        {
            AutoMocker = AutoMockFactory.CreateTarget&lt;T&gt;();

            // UPDATE 2009-12-21:
            //    Initializing here prevented injected dependencies!
            // AutoMocker.PartialMockTheClassUnderTest();
            // ClassUnderTest = AutoMocker.Instance;
        }

        protected SpecificationFor(AutoMockType type)
        {
            AutoMocker = AutoMockFactory.CreateTarget&lt;T&gt;(type);

            // UPDATE 2009-12-21:
            // Initializing here prevented injected dependencies!
            // AutoMocker.PartialMockTheClassUnderTest();
            // ClassUnderTest = AutoMocker.Instance;
        }
    }

    public static class AutoMockFactory
    {
        public static ClassUnderTest&lt;TARGETCLASS&gt; CreateTarget&lt;TARGETCLASS&gt;() where TARGETCLASS : class
        {
            return CreateTarget&lt;TARGETCLASS&gt;(AutoMockType.RhinoMocksAAA);
        }

        public static ClassUnderTest&lt;TARGETCLASS&gt; CreateTarget&lt;TARGETCLASS&gt;(AutoMockType framework) where TARGETCLASS : class
        {
            AutoMocker&lt;TARGETCLASS&gt; mocker;
            ServiceLocator serviceLocator;
            switch (framework)
            {
                case AutoMockType.RhinoMocksAAA:
                    mocker = new RhinoAutoMocker&lt;TARGETCLASS&gt;(MockMode.AAA);
                    serviceLocator = new RhinoMocksAAAServiceLocator();
                    break;
                case AutoMockType.RhinoMocksClassic:
                    mocker = new RhinoAutoMocker&lt;TARGETCLASS&gt;(MockMode.RecordAndReplay);
                    serviceLocator = new RhinoMocksClassicServiceLocator();
                    break;
                case AutoMockType.Moq:
                    mocker = new MoqAutoMocker&lt;TARGETCLASS&gt;();
                    serviceLocator = new MoqServiceLocator();
                    break;
                default:
                    throw new ArgumentOutOfRangeException("framework");
            }
            return new ClassUnderTest&lt;TARGETCLASS&gt;(mocker, serviceLocator);
        }
    }

    public enum AutoMockType
    {
        Moq,
        RhinoMocksAAA,
        RhinoMocksClassic
    }

    public class ClassUnderTest&lt;TARGETCLASS&gt; where TARGETCLASS : class
    {
        readonly IAutoMocker&lt;TARGETCLASS&gt; _mocker;
        readonly ServiceLocator _serviceLocator;

        public ClassUnderTest(IAutoMocker&lt;TARGETCLASS&gt; mocker, ServiceLocator serviceLocator)
        {
            _mocker = mocker;
            _serviceLocator = serviceLocator;
        }

        public AutoMockedContainer Container
        {
            get { return _mocker.Container; }
        }

        public TARGETCLASS Instance
        {
            get { return _mocker.ClassUnderTest; }
        }

        public void MockObjectFactory()
        {
            _mocker.MockObjectFactory();
        }

        public void PartialMockTheClassUnderTest()
        {
            _mocker.PartialMockTheClassUnderTest();
        }

        public T Get&lt;T&gt;() where T : class
        {
            return _mocker.Get&lt;T&gt;();
        }

        public void Inject(Type pluginType, object stub)
        {
            _mocker.Inject(pluginType, stub);
        }

        public void Inject&lt;T&gt;(T target)
        {
            _mocker.Inject(target);
        }

        public T AddAdditionalMockFor&lt;T&gt;() where T : class
        {
            return _mocker.AddAdditionalMockFor&lt;T&gt;();
        }

        public void UseConcreteClassFor&lt;T&gt;()
        {
            _mocker.UseConcreteClassFor&lt;T&gt;();
        }

        public T[] CreateMockArrayFor&lt;T&gt;(int count) where T : class
        {
            return _mocker.CreateMockArrayFor&lt;T&gt;(count);
        }

        public void InjectArray&lt;T&gt;(T[] stubs)
        {
            _mocker.InjectArray(stubs);
        }

        public T Mock&lt;T&gt;() where T : class
        {
            return _serviceLocator.Service&lt;T&gt;();
        }
        public object Mock(Type serviceType)
        {
            return _serviceLocator.Service(serviceType);
        }
        public T PartialMock&lt;T&gt;() where T : class
        {
            return _serviceLocator.PartialMock&lt;T&gt;();
        }
    }
}</pre>
</ul>
<script type="text/javascript">// <![CDATA[
 var cirerolGaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."); document.write(unescape("%3Cscript src='" + cirerolGaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
// ]]&gt;</script>

<script type="text/javascript">// <![CDATA[
 var cirerolPageTracker = _gat._getTracker('UA-8257866-3'); cirerolPageTracker._initData(); cirerolPageTracker._trackPageview();
// ]]&gt;</script>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/11/30/wrapping-up-the-structuremap-automocking-container/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Integration Test Brought to you by Powershell &amp; NUnit &#8211; with a Little Specification Syntax for Flavoring</title>
		<link>http://elegantcode.com/2009/10/25/integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring</link>
		<comments>http://elegantcode.com/2009/10/25/integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring/#comments</comments>
		<pubDate>Mon, 26 Oct 2009 05:00:40 +0000</pubDate>
		<dc:creator>Jason Jarrett</dc:creator>
				<category><![CDATA[Esoterica]]></category>
		<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/10/25/integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring/</guid>
		<description><![CDATA[One of the tools I’ve used the last half of a year and really enjoyed is the C# specification extension methods when writing unit test assertions. If you’re looking for a little more background on the topic, I wrote about Fluent Specification Extensions in a past blog. Recently I wanted to execute a PowerShell script [...]]]></description>
			<content:encoded><![CDATA[One of the tools I’ve used the last half of a year and really enjoyed is the C# specification extension methods when writing unit test assertions. If you’re looking for a little more background on the topic, I wrote about <a href="http://staxmanade.blogspot.com/2009/02/fluent-specification-extensions.html">Fluent Specification Extensions</a> in a past blog.

Recently I wanted to execute a PowerShell script to do some automated <a href="http://en.wikipedia.org/wiki/Functional_testing">functional testing</a>. I wanted to execute an application and apply some assertions on the output of the software(basically running a console app, parse the xml output and assert on values in the output).
<blockquote>FYI: I’m very new to PowerShell, so any suggestions on how I implemented the below are welcome…</blockquote>
I’ve seen a couple examples of writing test assertions in PowerShell out there. One example is <a href="http://www.psunit.org/">PSUnit</a>; however, this seemed a little heavy for my needs and not quite the syntactic sugar I was looking for.

Besides the syntax flavor I was desiring, another thing I wanted to do was leverage the power of NUnit.Framework’s assertion capabilities. I like the error messages generated when strings and other objects fail the assertion.
<h5>Examples of end result ShouldLookLike()…</h5>
$true.ShouldBeTrue()
$false.ShouldBeFalse()
"a".ShouldEqual("a")
"a".ShouldNotEqual("b")
<h5><strong>Step 1</strong>: Figure out how to write a C# style <a href="http://msdn.microsoft.com/en-us/library/bb383977.aspx">extension method</a> in PowerShell.</h5>
<blockquote>I found a great blog post describing how to extend any PowerShell object to add extension methods.

<a href="http://bartdesmet.net/blogs/bart/archive/2007/09/06/extension-methods-in-windows-powershell.aspx">Extension Methods in Windows PowerShell</a></blockquote>
In short, to extend types in PowerShell leveraging the <a href="http://msdn.microsoft.com/en-us/library/ms714419(VS.85).aspx">Extended Type System</a>, you need to define them in an xml file and import the method definitions into the PowerShell runtime instance.

Below is PowerShell XML definition for my NUnit Specification Extensions.
<pre class="brush: xml;">&lt;?xml version="1.0" encoding="utf-16"?&gt;
&lt;Types&gt;
    &lt;Type&gt;
        &lt;Name&gt;System.Object&lt;/Name&gt;
        &lt;Members&gt;
            &lt;ScriptMethod&gt;
                &lt;Name&gt;ShouldBeFalse&lt;/Name&gt;
                &lt;Script&gt;
                    [NUnit.Framework.Assert]::IsFalse($this)
                &lt;/Script&gt;
            &lt;/ScriptMethod&gt;
            &lt;ScriptMethod&gt;
                &lt;Name&gt;ShouldBeTrue&lt;/Name&gt;
                &lt;Script&gt;
                    [NUnit.Framework.Assert]::IsTrue($this)
                &lt;/Script&gt;
            &lt;/ScriptMethod&gt;
            &lt;ScriptMethod&gt;
                &lt;Name&gt;ShouldEqual&lt;/Name&gt;
                &lt;Script&gt;
                    [NUnit.Framework.Assert]::AreEqual($args[0], $this)
                &lt;/Script&gt;
            &lt;/ScriptMethod&gt;
            &lt;ScriptMethod&gt;
                &lt;Name&gt;ShouldNotEqual&lt;/Name&gt;
                &lt;Script&gt;
                    [NUnit.Framework.Assert]::AreNotEqual($args[0], $this)
                &lt;/Script&gt;
            &lt;/ScriptMethod&gt;
        &lt;/Members&gt;
    &lt;/Type&gt;
&lt;/Types&gt;</pre>
<h4></h4>
Take the above XML and save it to a file…
<blockquote>NOTE: the file HAS to be saved with the extension <strong>.ps1xml</strong>

Ex: NunitSpecificationPowerShellExtensions<strong>.ps1xml</strong></blockquote>
<h4></h4>
<h5>Step 2: Load the extended type definition into the PowerShell runtime.</h5>
Once you’ve saved the XML extended types to a file, you need to load it into the PowerShell runtime by executing the command below.
<blockquote>
Update-TypeData -PrependPath NunitSpecificationPowerShellExtensions.ps1xml</blockquote>
Before executing the above statement…Let’s quickly look at a System.String’s members and properties – just to show you what the extension methods look like when applied inside of the runtime.<a href="http://elegantcode.com/wp-content/uploads/2009/10/image3.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" src="http://elegantcode.com/wp-content/uploads/2009/10/image_thumb2.png" border="0" alt="image" width="586" height="479" /></a>

After executing the Update-TypeData command you’ll notice there are a number of “ScriptMethod” MemberTypes added to the object.

<a href="http://elegantcode.com/wp-content/uploads/2009/10/image4.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" src="http://elegantcode.com/wp-content/uploads/2009/10/image_thumb3.png" border="0" alt="image" width="600" height="580" /></a>

Now if you try to execute one of those newly added extension methods, you may get the following error…

PS C:\&gt; $testVar.<strong>ShouldEqual</strong>("hello world")

Exception calling "ShouldEqual" with "1" argument(s): "<strong>Unable to find type [NUnit.Framework.Assert]: make sure that the

assembly containing this type is loaded.</strong>"

At line:1 char:21

+ $testVar.ShouldEqual &lt;&lt;&lt;&lt; ("hello world")

+ CategoryInfo          : NotSpecified: (:) [], MethodInvocationException

+ FullyQualifiedErrorId : ScriptMethodRuntimeException

This is because we need to load the NUnit.Framework assembly into the runtime before we can leverage the extension methods.
<blockquote>[System.Reflection.Assembly]::LoadFrom("C:\Program Files\NUnit 2.5.2\bin\net-2.0\framework\nunit.framework.dll") | Out-Null</blockquote>
Now that the extension methods have been defined and loaded into the runtime, NUnit.Framework is loaded, we can now use the methods on any object that inherits from System.Object (which, as far as I know, is everything in PowerShell).

And now, everything you need in one script (if you have the xml extended type file saved somewhere…)
<pre>#
# Update-TypeData -prependPath C:\Code\NunitSpecificationPowerShellExtensions.ps1xml
#

[System.Reflection.Assembly]::LoadFrom("C:\Program Files\NUnit 2.5.2\bin\net-2.0\framework\nunit.framework.dll") | Out-Null

$true.ShouldBeTrue()

$false.ShouldBeFalse()

"a".ShouldEqual("a")

"a".ShouldNotEqual("b")</pre>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/10/25/integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Visual Studio Team System for Small Teams</title>
	<atom:link href="http://elegantcode.com/category/unit-testing/feed/" rel="self" type="application/rss+xml" />
	<link>http://elegantcode.com</link>
	<description></description>
	<lastBuildDate>Tue, 15 May 2012 10:00:00 +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>Elegant Code &#187; Unit Testing</title>
	<atom:link href="http://elegantcode.com/category/unit-testing/feed/" rel="self" type="application/rss+xml" />
	<link>http://elegantcode.com</link>
	<description></description>
	<lastBuildDate>Tue, 15 May 2012 10:00:00 +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>AutoTest.NET</title>
		<link>http://elegantcode.com/2010/11/30/autotest-net/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=autotest-net</link>
		<comments>http://elegantcode.com/2010/11/30/autotest-net/#comments</comments>
		<pubDate>Tue, 30 Nov 2010 11:00:00 +0000</pubDate>
		<dc:creator>Jan Van Ryswyck</dc:creator>
				<category><![CDATA[TDD]]></category>
		<category><![CDATA[Tools and Utilities]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/11/30/autotest-net/</guid>
		<description><![CDATA[I just want to quickly point out a tool that I’ve been playing with for a couple of days now, named AutoTest.NET. Its an open-source tool that originates from a popular tool in the Ruby community called ZenTest, which basically runs all your valuable unit tests when you save your source files or when you [...]]]></description>
			<content:encoded><![CDATA[<p>I just want to quickly point out a tool that I’ve been playing with for a couple of days now, named <a href="https://github.com/acken/AutoTest.Net" target="_blank">AutoTest.NET</a>. Its an open-source tool that originates from a popular tool in the Ruby community called <a href="http://www.zenspider.com/ZSS/Products/ZenTest/" target="_blank">ZenTest</a>, which basically runs all your valuable unit tests when you save your source files or when you build your code. It enables you to get feedback about your changes as soon as possible.</p>  <p>The project started out a couple of years ago on <a href="http://code.google.com/p/autotestnet/" target="_blank">Google code</a> and was first initiated by <a href="http://averyblog.com/" target="_blank">James Avery</a>. Contribution stopped at some point until recently where <a href="http://ackenpacken.blogspot.com/" target="_blank">Svein Arne Ackenhausen</a> forked the source code and <a href="https://github.com/acken/AutoTest.Net" target="_blank">put it on GitHub</a>. Now it runs both for .NET as well as Mono, with NUnit, MSTest and xUnit as the currently supported unit test frameworks. </p>  <p>Here’s a screenshot from the feedback window when all tests pass:</p>  <p><a href="http://elegantcode.com/wp-content/uploads/2010/11/Success.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="Success" border="0" alt="Success" src="http://elegantcode.com/wp-content/uploads/2010/11/Success_thumb.png" width="540" height="189" /></a> </p>  <p>And here you can see the same window after I broke one of my unit tests:</p>  <p><a href="http://elegantcode.com/wp-content/uploads/2010/11/Failure.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="Failure" border="0" alt="Failure" src="http://elegantcode.com/wp-content/uploads/2010/11/Failure_thumb.png" width="538" height="319" /></a> </p>  <p>Here you can see which particular unit test has been broken and by clicking the specified link you end up at the right source file in Visual Studio. </p>  <p>I encourage you to pick up this small tool and learn how it can facilitate your TDD flow. Take a look at <a href="https://github.com/acken/AutoTest.Net/wiki/Get-started!" target="_blank">this page</a> in order to get up-and-running in no time. Also don’t forget to provide the owner(s) of this project with some feedback that you might have. Svein has been very helpful over the last week answering all my stupid questions and remarks (and the Nobel price for this year’s most patient person goes to … ;-) ). </p>  <p>I would definitely like to see this tool becoming more popular, so go check it out.&#160;&#160; </p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/11/30/autotest-net/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>If Self-Documenting Code is the What, Unit Tests are the Why</title>
		<link>http://elegantcode.com/2010/04/25/if-self-documenting-code-is-the-what-unit-tests-are-the-why/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=if-self-documenting-code-is-the-what-unit-tests-are-the-why</link>
		<comments>http://elegantcode.com/2010/04/25/if-self-documenting-code-is-the-what-unit-tests-are-the-why/#comments</comments>
		<pubDate>Sun, 25 Apr 2010 19:09:04 +0000</pubDate>
		<dc:creator>John Sonmez</dc:creator>
				<category><![CDATA[Agile]]></category>
		<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Craftsmanship]]></category>
		<category><![CDATA[Documentation]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/04/25/if-self-documenting-code-is-the-what-unit-tests-are-the-why/</guid>
		<description><![CDATA[It is not enough to just write code that is clean and self-documenting.  Eliminating comments and replacing them with clear variable and method names, will tell the reader of your code clearly what it is doing, but it will not properly express why it is doing it. If you recall from my original post on [...]]]></description>
			<content:encoded><![CDATA[It is not enough to just write code that is clean and self-documenting.  <a href="http://elegantcode.com/2010/04/18/eliminating-comments-the-road-to-clarity/">Eliminating comments</a> and replacing them with clear variable and method names, will tell the reader of your code clearly what it is doing, but it will not properly express why it is doing it.

If you recall from my <a href="http://elegantcode.com/2010/04/09/what-does-elegant-code-mean-to-me/">original post</a> on Elegant code, I stated that elegant code is:
<blockquote>Something that is simple yet effective, delivered with grace.</blockquote>
By writing self-documenting code we are hopefully able to achieve some of the aspects of simplicity and grace, but it tells us nothing about the effectiveness of the code.
<h2>Bringing the dead to life</h2>
<a href="http://elegantcode.com/wp-content/uploads/2010/04/zombies.jpg"><img style="border-right-width: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto" title="zombies" src="http://elegantcode.com/wp-content/uploads/2010/04/zombies_thumb.jpg" border="0" alt="zombies" width="441" height="295" /></a>

Throwing out comments is a debatable topic.  <a href="http://www.reddit.com/r/programming/comments/bsutx/">It raises quite a bit of controversy</a>, as you can see from some of the comments on my post about the subject.  The reason, perhaps, that so many people are so staunchly opposed to the idea, is because they are worried, and rightly so, that throwing out comments will reduce the documentation of what the code is doing.

Think about that for a second.  Is documentation of what the code is doing important?  It better be.  What we are trying to accomplish by writing self-documenting code instead of comments, is to take the vessel, which is the code itself, and make that same vessel be the documentation of what the code does.  It is by doing this that we creating a living representation of the functionality of the code.  Comments are akin to a dead representation of the functionality of the code because they do not change automatically with the code.

I diverge to talk about comments so that I can draw a parallel to another form of documentation which is valuable and should be considered necessary.  That other set of documentation is requirements.  Have you ever written requirements documents?  Have you ever captured requirements from the customer and put them into UML diagrams, or perhaps plopped them into some templated Word document, which is never updated again, and no one reads, because no one trusts it is correct?  Wouldn’t it be great if we would replace that dead document or set of documents, with a living one?

The good news is we can, and some of us have.  And I fully expect this recommendation will be just as controversial, because <strong>I am suggesting that we don’t have to write low level specifications of the system at all, instead we can write good unit tests. </strong>When we do this, we are taking a dead form of document and bringing it to life.
<h2>Unit tests tell us why and how our code is effective</h2>
If
<pre class="csharpcode">i = 5;  // Widget count defaults to five.</pre>
is replaced with
<pre class="csharpcode">widgetCount = DEFAULT_WIDGET_COUNT;</pre>
<!--.csharpcode, .csharpcode pre { 	font-size: small; 	color: black; 	font-family: consolas, "Courier New", courier, monospace; 	background-color: #ffffff; 	/*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt  { 	background-color: #f4f4f4; 	width: 100%; 	margin: 0em; } .csharpcode .lnum { color: #606060; } -->

then
<blockquote><span style="background-color: #ffffff;">1.1.5 When a new widget is created, the widget count should be increased by one.</span></blockquote>
is replaced with
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">void</span> When_NewWidgetIsCreated_Then_WidgetCountIsIncreasedByOne()
{
     WidgetFactory.Count = 3;
     WidgetFactory.CreateNew();
     assertEquals(4, WidgetFactory.Count);
}</pre>
The unit test is replacing the low level requirement, which is somewhat open to interpretation and untied to the code, with an absolute and completely tied-to-the-code, specific requirement.

The unit test is telling us why our code is built the way it is.  It is telling us what requirement that particular structure of code is trying to address.  <strong>It is telling us what end result that code is trying to accomplish and what the expectations are on the results of a given condition.</strong>

The unit test is telling us how the code is to be used in order to achieve its result.  It is serving as a living reference to the syntax and use of the code we built.  <strong>Instead of providing instructions on how to use our API, we are providing a living example, and proof that it will indeed work.</strong> Examples are often much more effective than instructions anyway.
<h2>What exactly are we replacing?</h2>
At this point we are not trying to replace all the documentation of the system (at this point).

With self-documenting code, we sought to eliminate comments, and replace them with good variable and method names.

With unit tests, we seek to eliminate technical documentation and requirements of the system, that is targeted at a developer or technical audience.

We are NOT trying to eliminate high level specifications of the system, or use cases. <strong>Unit tests DO NOT replace that kind of documentation! </strong>We will talk about replacing that kind of documentation when we talk about automated functional or system tests.

Simply put, any kind of documentation that you would give to a developer so they understand how the system works and how to use the code or APIs, can be easily replaced by writing good unit tests.

Our simple goal is to replace the “dead” documentation (meaning that it does not update automatically with the thing it is documenting), with “living” documentation in the form of unit tests.

One last point.  I want to be clear that I am not saying that having unit tests automatically results in the ability to replace technical documentation.  Just like having long-named methods and variables doesn’t automatically replace the need for comments.  It is a matter of the quality of the unit tests that are written, just as it is a matter of the quality of the self-documenting code.
<h5>As always, you can subscribe to this <a href="http://feeds2.feedburner.com/ElegantCode">RSS feed</a> to follow my posts on elegant code.  Feel free to check out my main personal blog at <a href="http://simpleprogrammer.com">http://simpleprogrammer.com</a>, which has a wider range of posts, updated 2-3 times a week.  Also, you can follow me on twitter <a href="http://twitter.com/jsonmez">here</a>.</h5>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/04/25/if-self-documenting-code-is-the-what-unit-tests-are-the-why/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Behaviors with MSpec</title>
		<link>http://elegantcode.com/2010/02/26/behaviors-with-mspec/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=behaviors-with-mspec</link>
		<comments>http://elegantcode.com/2010/02/26/behaviors-with-mspec/#comments</comments>
		<pubDate>Fri, 26 Feb 2010 23:33:28 +0000</pubDate>
		<dc:creator>Jan Van Ryswyck</dc:creator>
				<category><![CDATA[BDD]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/02/26/behaviors-with-mspec/</guid>
		<description><![CDATA[In my previous posts, I showed the syntax for context/specifications using Machine.Specifications (or MSpec for short) and how to use an auto mocking container in conjunction with this excellent Behavior-Driven Development (BDD) framework. For this post, I want to show you one of the nice features of MSpec called behaviors. Suppose we have to create [...]]]></description>
			<content:encoded><![CDATA[<p>In my previous posts, I showed the <a href="http://elegantcode.com/2010/02/19/getting-started-with-machine-specifications-mspec/">syntax for context/specifications</a> using <a href="http://github.com/machine/machine.specifications">Machine.Specifications</a> (or MSpec for short) and <a href="http://elegantcode.com/2010/02/23/mspec-and-auto-mocking">how to use an auto mocking container</a> in conjunction with this excellent Behavior-Driven Development (BDD) framework. For this post, I want to show you one of the nice features of MSpec called <em>behaviors</em>.</p>  <p>Suppose we have to create some sort of specification that validates the format of an e-mail address. We typically use some regular expression in order to ensure that a specified e-mail address is properly formatted.</p>  <pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">class</span> EmailSpecification
{
    <span class="kwrd">private</span> <span class="kwrd">const</span> String EmailRegexPattern = <span class="str">@&quot;.. SOME_REGEX_PATTERN ...&quot;</span>;

    <span class="kwrd">public</span> Boolean IsSatisfiedBy(String candidate)
    {
        var regex = <span class="kwrd">new</span> Regex(EmailRegexPattern);
        <span class="kwrd">return</span> regex.IsMatch(candidate);
    }
}</pre>
<style type="text/css">

.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>I guess this is pretty common and straightforward. One way to provide some unit tests for this particular piece of code is to check a whole number of e-mail addresses that either pass or fail the specification. The following example shows only a couple of scenarios:</p>

<pre class="csharpcode">[TestFixture]
<span class="kwrd">public</span> <span class="kwrd">class</span> When_validating_an_email
    : ContextSpecification&lt;EmailSpecification&gt;
{
    <span class="kwrd">protected</span> <span class="kwrd">override</span> EmailSpecification Create_subject_under_test()
    {
        <span class="kwrd">return</span> <span class="kwrd">new</span> EmailSpecification();
    }

    [Test]
    <span class="kwrd">public</span> <span class="kwrd">void</span> ShouldBeSatisfied()
    {
        Assert.That(SUT.IsSatisfiedBy(<span class="str">&quot;one2@three.com&quot;</span>));
        Assert.That(SUT.IsSatisfiedBy(<span class="str">&quot;one@two3.com&quot;</span>));
    }

    [Test]
    <span class="kwrd">public</span> <span class="kwrd">void</span> ShouldNotBeSatisfied()
    {
        Assert.That(SUT.IsSatisfiedBy(<span class="str">&quot;one_two.com&quot;</span>), Is.False);
        Assert.That(SUT.IsSatisfiedBy(<span class="str">&quot;one_two@&quot;</span>), Is.False);
    }
}</pre>
<style type="text/css">

.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>A slightly more concise approach for these kind of unit tests can be accomplished by utilizing a feature of any decent unit test framework called <em>row tests. </em>With this approach we can, at the very least, reduce the number of asserts we have to write for each unit test.<em>&#160;</em></p>

<pre class="csharpcode">[TestFixture]
<span class="kwrd">public</span> <span class="kwrd">class</span> When_validating_an_email__approach_2
    : ContextSpecification&lt;EmailSpecification&gt;
{
    <span class="kwrd">protected</span> <span class="kwrd">override</span> EmailSpecification Create_subject_under_test()
    {
        <span class="kwrd">return</span> <span class="kwrd">new</span> EmailSpecification();
    }

    [RowTest]
    [Row(<span class="str">&quot;one2@three.com&quot;</span>)]
    [Row(<span class="str">&quot;one@two3.com&quot;</span>)]
    <span class="kwrd">public</span> <span class="kwrd">void</span> ShouldBeSatisfied(String email)
    {
        Assert.That(SUT.IsSatisfiedBy(email));
    }

    [RowTest]
    [Row(<span class="str">&quot;one_two.com&quot;</span>)]
    [Row(<span class="str">&quot;one_two@&quot;</span>)]
    <span class="kwrd">public</span> <span class="kwrd">void</span> ShouldNotBeSatisfied(String email)
    {
        Assert.That(SUT.IsSatisfiedBy(email), Is.False);
    }
}</pre>
<style type="text/css">

.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>Notice that I explicitly called both of these approaches <em>unit tests</em> as they don’t have much to do with BDD in my opinion. I’m not saying that using regular unit tests is a bad thing, but with&#160; behavior-driven development context is king. So these unit tests are perfect examples of ‘<a href="http://elegantcode.com/2008/12/30/dont-sell-out-on-the-context-dude/">context betrayal</a>’ when following the BDD approach. </p>

<p>Lets see what MSpec can bring to the table for these kind of scenarios:</p>

<pre class="csharpcode">[Subject(<span class="kwrd">typeof</span>(EmailSpecification), <span class="str">&quot;is satisfied&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_validating_an_email_address_with_a_number_in_the_local_part
    : email_specification_specs
{
    Establish context = () =&gt;
        EmailAddress = <span class="str">&quot;one2@three.com&quot;</span>;

    Behaves_like&lt;SatisfiedSpecificationBehavior&gt; a_satisfied_specification;
}

[Subject(<span class="kwrd">typeof</span>(EmailSpecification), <span class="str">&quot;is satisfied&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_validating_an_email_address_with_a_number_in_the_domain_name
    : email_specification_specs
{
    Establish context = () =&gt;
        EmailAddress = <span class="str">&quot;one@two3.com&quot;</span>;

    Behaves_like&lt;SatisfiedSpecificationBehavior&gt; a_satisfied_specification;
}

[Subject(<span class="kwrd">typeof</span>(EmailSpecification), <span class="str">&quot;is satisfied&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_validating_an_email_address_without_an_At_sign
    : email_specification_specs
{
    Establish context = () =&gt;
        EmailAddress = <span class="str">&quot;one_two.com&quot;</span>;

    Behaves_like&lt;UnsatisfiedSpecificationBehavior&gt; an_unsatisfied_specification;
}

[Subject(<span class="kwrd">typeof</span>(EmailSpecification), <span class="str">&quot;is satisfied&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_validating_an_email_address_without_a_domain
    : email_specification_specs
{
    Establish context = () =&gt;
        EmailAddress = <span class="str">&quot;one_two@&quot;</span>;

    Behaves_like&lt;UnsatisfiedSpecificationBehavior&gt; an_unsatisfied_specification;
}</pre>
<style type="text/css">

.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>In order to escape ‘context betrayal’, we’ve split up every context into a separate context/specification. In order to reduce the amount of effort caused by duplicate code, we stripped the context setup to the bare minimum (just a particular e-mail address in this case). The observations are isolated into MSpec behaviors which provides a very readable description of their outcome. Lets take a look at what is needed in order to get these <em>behaviors</em> to work.</p>

<p>But first lets take at look at the abstract base class that we’ve used for the context/specifications we’ve just shown.</p>

<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">abstract</span> <span class="kwrd">class</span> email_specification_specs
{
    Establish context = () =&gt;
    {
        SUT = <span class="kwrd">new</span> EmailSpecification();
    };

    Because of = () =&gt;
        Result = SUT.IsSatisfiedBy(EmailAddress);

    <span class="kwrd">protected</span> <span class="kwrd">static</span> Boolean Result;
    <span class="kwrd">protected</span> <span class="kwrd">static</span> String EmailAddress { get; set; }
    <span class="kwrd">protected</span> <span class="kwrd">static</span> EmailSpecification SUT { get; set; }
}</pre>

<p><style type="text/css">

.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style></p>

<p>&#160;</p>

<p>We abstracted as much as possible into this base class in order to remove duplication in the context/specifications. The creation of the subject-under-test and the calling of its <em>IsSatisfiedBy</em> method, but the important one is the declaration of the <em>Result</em> field. This field contains the outcome of the <em>IsSatisfiedBy</em> method. Finally, lets have a look at the behaviors themselves:</p>

<pre class="csharpcode">[Behaviors]
<span class="kwrd">public</span> <span class="kwrd">class</span> SatisfiedSpecificationBehavior
{
    <span class="kwrd">protected</span> <span class="kwrd">static</span> Boolean Result;
    
    It should_satisfy_the_specification = () =&gt;
        Result.ShouldBeTrue();
}

[Behaviors]
<span class="kwrd">public</span> <span class="kwrd">class</span> UnsatisfiedSpecificationBehavior
{
    <span class="kwrd">protected</span> <span class="kwrd">static</span> Boolean Result;

    It should_not_satisfy_the_specification = () =&gt;
        Result.ShouldBeFalse();
}</pre>
<style type="text/css">

.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>In order to create an MSpec behavior, we just have to create a separate class that we decorate with the <em>Behaviors</em> attribute. Also notice that we have the same declaration of the <em>Result</em> field. MSpec ensures that this field gets initialized with the value of the other <em>Result</em> field that is set in the base class of the context/specifications. Note that you don’t necessarily need to put this field in a base class. You can have that field in every context/specification if you’d like (not sure why) as long as the names match with the fields used in the defined behaviors.</p>

<p>I personally like the way how the MSpec contributors tried to solve testing the same logic with different input patterns and the syntax they provided to back this up.&#160;&#160; </p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/02/26/behaviors-with-mspec/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>MSpec and Auto Mocking</title>
		<link>http://elegantcode.com/2010/02/23/mspec-and-auto-mocking/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=mspec-and-auto-mocking</link>
		<comments>http://elegantcode.com/2010/02/23/mspec-and-auto-mocking/#comments</comments>
		<pubDate>Tue, 23 Feb 2010 20:38:54 +0000</pubDate>
		<dc:creator>Jan Van Ryswyck</dc:creator>
				<category><![CDATA[BDD]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/02/23/mspec-and-auto-mocking/</guid>
		<description><![CDATA[In my previous post, I explained how to get started with Machine.Specifications (or MSpec for short) and showed you how the syntax for context/specifications looks like when using this BDD framework. For this post, I want to show you how to use an auto mocking container (we’ll be using the one provided by StructureMap off [...]]]></description>
			<content:encoded><![CDATA[<p>In my <a href="http://elegantcode.com/2010/02/19/getting-started-with-machine-specifications-mspec/">previous post</a>, I explained how to get started with <a href="http://github.com/machine/machine.specifications">Machine.Specifications</a> (or MSpec for short) and showed you how the syntax for context/specifications looks like when using this BDD framework. For this post, I want to show you how to use an <a href="http://vanryswyckjan.blogspot.com/2008/01/automocking-container.html">auto mocking container</a> (we’ll be using the one provided by StructureMap off course).</p>  <p>We’ll use the same example as the one used in the previous post, but now we’ll deal with the message handler that makes a particular customer preferred.</p> <style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>  <pre class="csharpcode"><span class="rem">//</span>
<span class="rem">// Subject under test</span>
<span class="rem">//</span>
<span class="kwrd">public</span> <span class="kwrd">class</span> MakeCustomerPreferredMessageHandler
{
    <span class="kwrd">private</span> <span class="kwrd">readonly</span> ICustomerRepository&lt;ICanMakeCustomerPreferred&gt; _repository;

    <span class="kwrd">public</span> MakeCustomerPreferredMessageHandler(
        ICustomerRepository&lt;ICanMakeCustomerPreferred&gt; repository)
    {
        _repository = repository;
    }

    <span class="kwrd">public</span> <span class="kwrd">void</span> Handle(MakeCustomerPreferredMessage message)
    {
        var customer = _repository.Get(message.CustomerId);
        <span class="kwrd">if</span>(<span class="kwrd">null</span> == customer)
            <span class="kwrd">throw</span> <span class="kwrd">new</span> InvalidOperationException(
                <span class="str">&quot;No customer for specified identifier&quot;</span>);
        
        customer.MakePreferred();
        _repository.Save(customer);
    }
}</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>The <em>Customer</em> class implements a ‘<a href="http://martinfowler.com/bliki/RoleInterface.html">role interface’</a> called <em>ICanMakeCustomerPreferred</em>. We retrieve a customer from the repository and make it preferred. We throw an exception in case the customer cannot be found in the data store.</p>

<p>Here are the context/specifications for this easy example:</p>

<pre class="csharpcode">[Subject(<span class="str">&quot;Making a customer preferred&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_making_a_customer_preferred
    : context_specification&lt;MakeCustomerPreferredMessageHandler&gt;
{
    Establish context = () =&gt;
    {
        _message = <span class="kwrd">new</span> MakeCustomerPreferredMessage { CustomerId = 6412 };

        Repository.Stub(repository =&gt; repository.Get(_message.CustomerId))
            .Return(Customer);
    };

    Because of = () =&gt; 
        SUT.Handle(_message);
    
    It should_mark_the_customer_as_preferred = () =&gt;
        Customer.AssertWasCalled(customer =&gt; customer.MakePreferred());

    It should_save_the_customer_in_the_repository = () =&gt;
        Repository.AssertWasCalled(repository =&gt; repository.Save(Customer));

    <span class="kwrd">private</span> <span class="kwrd">static</span> ICanMakeCustomerPreferred Customer
    {
        get { <span class="kwrd">return</span> Dependency&lt;ICanMakeCustomerPreferred&gt;(); }
    }

    <span class="kwrd">private</span> <span class="kwrd">static</span> ICustomerRepository&lt;ICanMakeCustomerPreferred&gt; Repository
    {
        get { <span class="kwrd">return</span> Dependency&lt;ICustomerRepository&lt;ICanMakeCustomerPreferred&gt;&gt;(); }
    }

    <span class="kwrd">private</span> <span class="kwrd">static</span> MakeCustomerPreferredMessage _message;
}

[Subject(<span class="str">&quot;Making a customer preferred&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_making_an_unexisting_customer_preferred
    : context_specification&lt;MakeCustomerPreferredMessageHandler&gt;
{
    Establish context = () =&gt;   
    {
        _message = <span class="kwrd">new</span> MakeCustomerPreferredMessage() { CustomerId = 61544 };

        Dependency&lt;ICustomerRepository&lt;ICanMakeCustomerPreferred&gt;&gt;()
            .Stub(repository =&gt; repository.Get(_message.CustomerId))
            .Return(<span class="kwrd">null</span>);
    };

    Because of = () =&gt;
        _resultingException = Catch.Exception(() =&gt; SUT.Handle(_message));

    It should_result_in_an_error = () =&gt;
        _resultingException.ShouldBeOfType&lt;InvalidOperationException&gt;();

    <span class="kwrd">private</span> <span class="kwrd">static</span> MakeCustomerPreferredMessage _message;
    <span class="kwrd">private</span> <span class="kwrd">static</span> Exception _resultingException;
}</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>I want to point out that all fields and properties are made static. This is needed so that the anonymous methods can access them. I’m also using a base class for these specifications which I’ll show next. This base class uses an auto mocking container for providing the requested mocks and stubs through the <em>Dependency</em> and <em>Stub</em> methods. </p>

<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">abstract</span> <span class="kwrd">class</span> context_specification&lt;TSubjectUnderTest&gt;
    <span class="kwrd">where</span> TSubjectUnderTest : <span class="kwrd">class</span>
{
    <span class="kwrd">private</span> <span class="kwrd">static</span> IAutoMockingContainer&lt;TSubjectUnderTest&gt; _autoMockingContainer;
    <span class="kwrd">protected</span> <span class="kwrd">static</span> TSubjectUnderTest SUT { get; set; }

    Establish context = () =&gt;
    {
        _autoMockingContainer = <span class="kwrd">new</span> StructureMapAMC&lt;TSubjectUnderTest&gt;();
        SUT = _autoMockingContainer.Create();     
    };
    
    Cleanup stuff = () =&gt; 
    {
        SUT = <span class="kwrd">null</span>;
        _autoMockingContainer = <span class="kwrd">null</span>;
    };

    <span class="kwrd">protected</span> <span class="kwrd">static</span> TDependency Dependency&lt;TDependency&gt;()
        <span class="kwrd">where</span> TDependency : <span class="kwrd">class</span>
    {
        <span class="kwrd">return</span> _autoMockingContainer.GetMock&lt;TDependency&gt;();
    }

    <span class="kwrd">protected</span> <span class="kwrd">static</span> TStub Stub&lt;TStub&gt;()
        <span class="kwrd">where</span> TStub : <span class="kwrd">class</span>
    {
        <span class="kwrd">return</span> _autoMockingContainer.GetStub&lt;TStub&gt;();
    }
}

<span class="kwrd">public</span> <span class="kwrd">interface</span> IAutoMockingContainer&lt;TSubject&gt;
    <span class="kwrd">where</span> TSubject : <span class="kwrd">class</span>
{
    TSubject Create();
    TMock GetMock&lt;TMock&gt;() <span class="kwrd">where</span> TMock : <span class="kwrd">class</span>;
    TStub GetStub&lt;TStub&gt;() <span class="kwrd">where</span> TStub : <span class="kwrd">class</span>;
}

<span class="kwrd">public</span> <span class="kwrd">class</span> StructureMapAMC&lt;TSubject&gt; 
    : IAutoMockingContainer&lt;TSubject&gt;
    <span class="kwrd">where</span> TSubject : <span class="kwrd">class</span>
{
    <span class="kwrd">private</span> <span class="kwrd">readonly</span> RhinoAutoMocker&lt;TSubject&gt; _rhinoAutoMocker;

    <span class="kwrd">public</span> StructureMapAMC()
    {
        _rhinoAutoMocker = 
            <span class="kwrd">new</span> RhinoAutoMocker&lt;TSubject&gt;(MockMode.AAA);
    }

    <span class="kwrd">public</span> TSubject Create()
    {
        <span class="kwrd">return</span> _rhinoAutoMocker.ClassUnderTest;
    }

    <span class="kwrd">public</span> TMock GetMock&lt;TMock&gt;() 
        <span class="kwrd">where</span> TMock : <span class="kwrd">class</span>
    {
        <span class="kwrd">return</span> GetDependency&lt;TMock&gt;();
    }

    <span class="kwrd">public</span> TStub GetStub&lt;TStub&gt;() 
        <span class="kwrd">where</span> TStub : <span class="kwrd">class</span>
    {
        <span class="kwrd">return</span> GetDependency&lt;TStub&gt;();
    }

    <span class="kwrd">private</span> TDependency GetDependency&lt;TDependency&gt;() 
        <span class="kwrd">where</span> TDependency : <span class="kwrd">class</span>
    {
        <span class="kwrd">return</span> _rhinoAutoMocker.Get&lt;TDependency&gt;();
    }
}</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>Notice that I’m using the <em>Establish</em> and <em>Cleanup</em> delegates in the <em>context_specification</em> base class. This doesn’t prevent that these can be used again in derived context/specifications. MSpec ensures that the anonymous methods are called in the right order. This means that the <em>Establish</em> method of the base class is called before the <em>Establish</em> method of the derived context/specifications.&#160;&#160;&#160;&#160; </p>

<p>Absolutely no rocket science here, but I figured it might come in handy when you need it. For the next post I’ll try to demonstrate how to deal with reusable behaviors.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/02/23/mspec-and-auto-mocking/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Getting Started With Machine.Specifications (MSpec)</title>
		<link>http://elegantcode.com/2010/02/19/getting-started-with-machine-specifications-mspec/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=getting-started-with-machine-specifications-mspec</link>
		<comments>http://elegantcode.com/2010/02/19/getting-started-with-machine-specifications-mspec/#comments</comments>
		<pubDate>Fri, 19 Feb 2010 21:34:17 +0000</pubDate>
		<dc:creator>Jan Van Ryswyck</dc:creator>
				<category><![CDATA[BDD]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/02/19/getting-started-with-machine-specifications-mspec/</guid>
		<description><![CDATA[Its been a while since I evaluated and evolved my approach to BDD. The way I’ve been doing BDD up until now is described in this blog post which goes way back to 2008. Everyone has kind of their own style nowadays. Below you can find the code of two context/specifications for a method named [...]]]></description>
			<content:encoded><![CDATA[<p>Its been a while since I evaluated and evolved my approach to BDD. The way I’ve been doing BDD up until now is described in <a href="http://elegantcode.com/2008/10/25/refining-contextspecification-bdd-using-rhino-mocks-35/">this blog post</a> which goes way back to 2008. Everyone has kind of their own style nowadays. Below you can find the code of two context/specifications for a method named <em>MakePreferred</em> on a <em>Customer </em>class. This simple example clarifies the style that I’ve been following up until now.</p> <style type="text/css">


.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style><style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>  <pre class="csharpcode">[TestFixture]
<span class="kwrd">public</span> <span class="kwrd">class</span> When_making_a_regular_customer_preferred
    : ContextSpecification&lt;Customer&gt;
{
    <span class="kwrd">protected</span> <span class="kwrd">override</span> Customer Create_subject_under_test()
    {
        <span class="kwrd">return</span> <span class="kwrd">new</span> Customer(<span class="kwrd">new</span>[] { _order });
    }

    <span class="kwrd">protected</span> <span class="kwrd">override</span> <span class="kwrd">void</span> Establish_context()
    {
        _order = <span class="kwrd">new</span> Order(<span class="kwrd">new</span>[] { <span class="kwrd">new</span> OrderItem(12), 
                                   <span class="kwrd">new</span> OrderItem(16) });
                                   
        _totalAmountWithoutDiscount = _order.TotalAmount;
    }

    <span class="kwrd">protected</span> <span class="kwrd">override</span> <span class="kwrd">void</span> Because()
    {
        SUT.MakePreferred();
    }

    [Test]
    <span class="kwrd">public</span> <span class="kwrd">void</span> Then_the_customer_should_be_marked_as_preferred()
    {
        SUT.IsPreferred.ShouldBeTrue();
    }

    [Test]
    <span class="kwrd">public</span> <span class="kwrd">void</span> Then_a_ten_percent_discount_should_be_applied_to_all_outstanding_orders()
    {
        _order.TotalAmount.ShouldBeEqualTo(
            _totalAmountWithoutDiscount * 0.9);
    }

    <span class="kwrd">private</span> Order _order;
    <span class="kwrd">private</span> Double _totalAmountWithoutDiscount;
}

[TestFixture]
<span class="kwrd">public</span> <span class="kwrd">class</span> When_making_a_preferred_customer_preferred
    : ContextSpecification&lt;Customer&gt;
{
    <span class="kwrd">protected</span> <span class="kwrd">override</span> Customer Create_subject_under_test()
    {
        var customer = <span class="kwrd">new</span> Customer(<span class="kwrd">new</span>[] { _order });
        customer.MakePreferred();
        <span class="kwrd">return</span> customer;
    }

    <span class="kwrd">protected</span> <span class="kwrd">override</span> <span class="kwrd">void</span> Establish_context()
    {
        _order = <span class="kwrd">new</span> Order(<span class="kwrd">new</span>[] { <span class="kwrd">new</span> OrderItem(12), 
                                   <span class="kwrd">new</span> OrderItem(16) });
        _totalAmountWithoutDiscount = _order.TotalAmount;
    }

    <span class="kwrd">protected</span> <span class="kwrd">override</span> <span class="kwrd">void</span> Because()
    {
        SUT.MakePreferred();
    }

    [Test]
    <span class="kwrd">public</span> <span class="kwrd">void</span> Then_no_additional_discount_should_be_applied_to_the_outstanding_orders()
    {
        _order.TotalAmount.ShouldNotBeEqualTo(
            _totalAmountWithoutDiscount * 0.81);
    }

    <span class="kwrd">private</span> Order _order;
    <span class="kwrd">private</span> Double _totalAmountWithoutDiscount;
}

<span class="rem">//</span>
<span class="rem">// Subject under test</span>
<span class="rem">//</span>
<span class="kwrd">public</span> <span class="kwrd">class</span> Customer
{
    <span class="kwrd">private</span> <span class="kwrd">readonly</span> List&lt;Order&gt; _orders;
    <span class="kwrd">public</span> Boolean IsPreferred { get; <span class="kwrd">private</span> set; }

    <span class="kwrd">public</span> Customer(IEnumerable&lt;Order&gt; orders)
    {
        _orders = <span class="kwrd">new</span> List&lt;Order&gt;(orders);
    }

    <span class="kwrd">public</span> <span class="kwrd">void</span> MakePreferred()
    {
        <span class="kwrd">if</span>(IsPreferred)    
            <span class="kwrd">return</span>;
    
        IsPreferred = <span class="kwrd">true</span>;
        _orders.ForEach(order =&gt; order.ApplyDiscount(10));
    }
}</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>The bottom line of this example is that preferred customers get a 10 percent discount. Customers that are already preferred do not get an additional discount or otherwise we’re out of business ;-). </p>

<p>I’ve been pretty happy with this approach so far, although sometimes there were some quirks associated with this. So it was time for me to look beyond the horizon again, trying to look for ways to improve. </p>

<p><a href="http://github.com/machine/machine.specifications">Machine.Specifications</a> or MSpec for short is something that has been on my ‘cool-things-to-learn-list’ for quite some time now. As you will see later in this post, the syntax is a bit different as one would come to expect from a context/specification framework that targets the C# programming language. Its seems to be heavily inspired by Scott Bellware’s <a href="http://code.google.com/p/specunit-net/">SpecUnit framework</a> and <a href="http://rspec.info/">RSpec</a>.</p>

<p>Lets see how to set things up first. </p>

<p>The most obvious starting point is downloading the bits and bytes. You can grab the <a href="http://github.com/machine/machine.specifications">source code</a> from GitHub and build it or you can wuss out like I did and get the latest build from the <a href="http://teamcity.codebetter.com/login.html">TeamCity.CodeBetter.com</a> builder server (you can log on as a guest and search the artifacts for a latest build).&#160; </p>

<p>When you’re heavily addicted to <a href="http://www.testdriven.net/">TestDriven.NET</a> like I am, then its possible to keep using this wonderful Visual Studio add-in for running MSpec context/specifications. Just create a directory named <em>Machine.Specifications</em> in {$Program_Files}\TestDriven.NET 2.0 and copy the following files:</p>

<ul>
  <li>Machine.Specifications.dll</li>

  <li>Machine.Specifications.TDNetRunner.dll</li>

  <li>InstallTDNetRunner.bat</li>
</ul>

<ul>Run the InstallTDNetRunner.bat file and you’re able to run all MSpec context/specifications using TestDriven.NET.</ul>

<p>I also strongly encourage you to install the plugin for the Resharper test runner (if only to prevent some Resharper warnings later on). First step is to add a directory named <em>Plugins</em> to the <em>Bin</em> directory of Resharper ({$Program_Files}\JetBrains\ReSharper\v4.5\Bin\). Then create a directory named <em>Machine.Specifications</em> in the <em>Plugins</em> directory you just created and copy the following files:</p>

<ul>
  <li>Machine.Specifications.dll</li>

  <li>Machine.Specifications.ReSharperRunner.4.5.dll</li>

  <li>InstallResharperRunner.4.5.bat</li>
</ul>

<p>Run the InstallResharperRunner.4.5.bat file and you’re also able to run MSpec context/specifications using the Resharper test runner.</p>

<p>I’m not going to put this off any longer. Lets look at the code of the context/specifications shown earlier but completely revamped using the MSpec syntax:</p>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<pre class="csharpcode">[Subject(<span class="str">&quot;Making a customer preferred&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_a_regular_customer_is_made_preferred 
{
    Establish context = () =&gt;
    {
        _order = <span class="kwrd">new</span> Order(<span class="kwrd">new</span>[] { <span class="kwrd">new</span> OrderItem(12), 
                                   <span class="kwrd">new</span> OrderItem(16) });
        _totalAmountWithoutDiscount = _order.TotalAmount;

        SUT = <span class="kwrd">new</span> Customer(<span class="kwrd">new</span>[] { _order });
    };

    Because of = () =&gt; 
        SUT.MakePreferred();

    It should_mark_the_customer_as_preferred = () =&gt;
        SUT.IsPreferred.ShouldBeTrue();
        
    It should_apply_a_ten_percent_discount_to_all_outstanding_orders = () =&gt;
        _order.TotalAmount.ShouldEqual(_totalAmountWithoutDiscount * 0.9);      

    <span class="kwrd">private</span> <span class="kwrd">static</span> Customer SUT;
    
    <span class="kwrd">private</span> <span class="kwrd">static</span> Order _order;
    <span class="kwrd">private</span> <span class="kwrd">static</span> Double _totalAmountWithoutDiscount;
}

[Subject(<span class="str">&quot;Making a customer preferred&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_a_preferred_customer_is_made_preferred
{
    Establish context = () =&gt;
    {
        _order = <span class="kwrd">new</span> Order(<span class="kwrd">new</span>[] { <span class="kwrd">new</span> OrderItem(12), 
                                   <span class="kwrd">new</span> OrderItem(16) });
        _totalAmountWithoutDiscount = _order.TotalAmount;

        SUT = <span class="kwrd">new</span> Customer(<span class="kwrd">new</span>[] { _order });
        SUT.MakePreferred();
    };

    Because of = () =&gt;
        SUT.MakePreferred();

    It should_apply_no_additional_discount_to_the_outstanding_orders = () =&gt; 
        _order.TotalAmount.ShouldNotEqual(_totalAmountWithoutDiscount * 0.81);

    <span class="kwrd">private</span> <span class="kwrd">static</span> Customer SUT;

    <span class="kwrd">private</span> <span class="kwrd">static</span> Order _order;
    <span class="kwrd">private</span> <span class="kwrd">static</span> Double _totalAmountWithoutDiscount;
}</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>I warned you about the syntax, didn’t I :-). It only took me a couple of seconds to get used to this syntax but now I’m completely hooked. Instead of using methods and attributes, MSpec utilizes delegates and anonymous methods. But there’s more. </p>

<p>When using <a href="http://www.nunit.com/index.php">NUnit</a> for writing context/ specifications, the <em>Establish_context</em> and <em>Because</em> methods of the example shown earlier is executed before every observation (test). With MSpec, the <em>Establish</em> and <em>Because</em> anonymous methods are executed only once for every context no matter how many observations a particular context class contains. Big difference? Well, at first glance not but on second hand it does make <a href="http://elegantcode.com/2008/12/30/dont-sell-out-on-the-context-dude/">selling out on the context</a> a bit more difficult as it will probably blow up in your face sooner than later. You can force MSpec to execute the <em>Establish</em> and <em>Because</em> anonymous methods before every observation by applying the <em>SetupForEachSpecification</em> attribute to the context class, but I strongly encourage you to stay away from that unless absolutely needed.</p>

<p>Also notice that the fields in the contexts are now all static. This is needed so that the anonymous methods can access those.&#160;&#160;&#160;&#160;&#160; </p>

<p>Running these context/specifications using TestDriven.NET yields the following output in the output window of Visual Studio:</p>

<blockquote>
  <p><font face="Arial">Making a customer preferred, when a regular customer is made preferred
      <br />» should mark the customer as preferred

      <br />» should apply a ten percent discount to all outstanding orders</font></p>

  <p><font face="Arial">Making a customer preferred, when a preferred customer is made preferred
      <br />» should apply no additional discount to the outstanding orders</font></p>
</blockquote>

<p>What’s not to like? Well, the only downside so far is that Resharper was giving me some warnings about classes and fields not being used etc. … . Many of those warnings disappeared by registering the MSpec plugin for the Resharper test runner as I explained earlier.</p>

<p>So far, so good. I’ve got two more posts coming up on MSpec, so stay tuned.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/02/19/getting-started-with-machine-specifications-mspec/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Unity/Moq &#8211; AutoMocker or AutoMockingContainer</title>
		<link>http://elegantcode.com/2010/01/03/unitymoq-automocker-or-automockingcontainer/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=unitymoq-automocker-or-automockingcontainer</link>
		<comments>http://elegantcode.com/2010/01/03/unitymoq-automocker-or-automockingcontainer/#comments</comments>
		<pubDate>Sun, 03 Jan 2010 16:52:33 +0000</pubDate>
		<dc:creator>Jason Jarrett</dc:creator>
				<category><![CDATA[TDD]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Tools and Utilities]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/01/03/unitymoq-automocker-or-automockingcontainer/</guid>
		<description><![CDATA[What is an Auto Mocking Container? This post started to get a little long, so I won’t re-explain the concept. Joshua Flanagan wrote a nice overview at his Los Techies blog: Auto mocking Explained. My post is mainly here to describe the Unity version of an automocking container I threw together. In Jan 2009 I [...]]]></description>
			<content:encoded><![CDATA[<h4>What is an Auto Mocking Container?</h4>  <p>This post started to get a little long, so I won’t re-explain the concept.</p>  <p><a href="http://www.lostechies.com/blogs/joshuaflanagan/default.aspx">Joshua Flanagan</a> wrote a nice overview at his <a href="http://www.lostechies.com/">Los Techies</a> blog: <a href="http://www.lostechies.com/blogs/joshuaflanagan/archive/2009/02/03/auto-mocking-explained.aspx"><strong>Auto mocking Explained</strong></a>.</p>  <p>My post is mainly here to describe the Unity version of an automocking container I threw together.</p>  <h4>In Jan 2009 I blogged about my initial version of the Unity AutoMocker - Why am I blogging about it again?</h4>  <p>I originally wrote the AutoMocker for the Unity container a year ago (Jan 2009, in Silverlight), and finally got around to placing the code up in the <a href="http://code.google.com/p/moq-contrib/">moq-contrib</a> project in June of 2009.</p>  <p>I’m writing another post today in hopes to:</p>  <ol>   <li>Get some feedback on how this little snippet of code should continue. </li>    <li>Give a little more how-to/example code </li>    <li>Describe some updates I made since I originally created it.&#160; </li> </ol>  <h4>Where can I get it?</h4>  <p><strong>This is one part where I’d appreciate some feedback.</strong></p>  <p>I have two slightly different versions out there (currently).</p>  <p>I have one version at the <a href="http://code.google.com/p/elegantcode/source/browse/#svn/trunk/Coders/JasonJarrett/UnityAutoMocker">ElegantCode</a> repository where I was working on it, and the other I threw up at <a href="http://code.google.com/p/moq-contrib/">moq-contrib</a>.</p>  <p>The core of the UnityAutoMockContainer is the same in both places, it’s how the tests are separated out that differ.</p>  <p>In the <a href="http://code.google.com/p/elegantcode/source/browse/#svn/trunk/Coders/JasonJarrett/UnityAutoMocker">ElegantCode repository</a> it’s an all in one self contained single file (that you can copy into your own test project(s)). You can then setup a single test in your own testing framework that runs all internal automocker tests (in case you need to modify it yourself, and don’t want to break any existing functionality). EX: test</p>  <pre class="brush: csharp;">[Test]
public void Should_run_all_UnityAutoMockContainer_internal_tests()
{
    Moq.AutoMocking.SelfTesting.UnityAutoMockContainerFixture
        .RunAllTests(Console.WriteLine);
}</pre>

<p>I kind of like this format as it makes it easy to port between test libraries. Can’t say I like having the tests in the same file as the core, but it certainly is not a large chunk of code (so far) so it’s relatively small to maintain and definitely easier to manage as a single .cs file than another assembly (which would have to be version dependent on both Unity and Moq).</p>

<p>The <a href="http://code.google.com/p/moq-contrib/">moq-contrib</a> is definitely where I think this helper should end up (and it is there). I just happened to break the tests out into the Silverlight test project and the core is alone in a file. </p>

<p>It’s current state isn’t as easy to copy to a test library (Silverlight/Desktop/Unity 1.2/Unity 2.0) as the one at <a href="http://elegantcode.com/">ElegantCode</a>. <strong>What does anyone think?</strong> Should I put them all together in one file?</p>

<p>However it ends up (1. all in one file or two (1 test) (1 core)) it will continue to be maintained on the <a href="http://code.google.com/p/moq-contrib/">moq-contrib</a> project.</p>

<h4>What is the high level API of the container?</h4>

<p>It’s pretty simple, (currently) there are four methods on the container.</p>

<p><strong>Two for registering items with the container</strong>. Say you want to register an already created instance, or say you want to map an interface to a concrete class and _not_ have the container generate mocks automatically for special cases. </p>

<p>And <strong>two for pulling items out of the container</strong>. Whether you want a instance of T or a Mock&lt;T&gt;, it gives you ways to retrieve both.</p>

<blockquote>
  <p><a href="http://elegantcode.com/wp-content/uploads/2010/01/image.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://elegantcode.com/wp-content/uploads/2010/01/image_thumb.png" width="396" height="106" /></a> </p>
</blockquote>

<h4>How can I setup my own registrations with the container? </h4>

<p>Say I don’t want to have the container generate mocks for specific items and I want to supply specific configuration to the UnityContainer.</p>

<blockquote>
  <p>public UnityAutoMockContainer RegisterInstance&lt;TService&gt;(TService instance)</p>

  <p>public UnityAutoMockContainer Register&lt;TService, TImplementation&gt;() 
    <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; where TImplementation : TService</p>
</blockquote>

<p><strong>Note</strong>: both of these registration methods return the container itself so you can fluently stack registration. <strong>EX:</strong></p>

<pre class="brush: csharp;">AutoMockContainer
    .Register&lt;IServiceA, ServiceA&gt;()
    .Register&lt;IServiceB, ServiceB&gt;();</pre>

<p><strong>Let me know</strong>: I haven’t tested or played around with how this automocking container deals with any container specific xml configuration… So although I don’t think you should probably have that in a test assembly (stuff happens). Let me know if there are any issues.</p>

<h4>How do I get items out of the container?</h4>

<p>First is the Resolve&lt;T&gt;(). It will pull an item T out of the container. (Creating it if not already existing)</p>

<blockquote>
  <p>public T Resolve&lt;T&gt;()</p>
</blockquote>

<p>When T is an interface Resolve&lt;T&gt; (unless you setup registration specifically with the container) should return basically “(new Mock&lt;T&gt;()).Object”</p>

<p>When T is a concrete Class, the container should return an instance of T and any of it’s dependencies will be satisfied by mocks. (Note that T will not be any sort of mocked instance of T, unless you used the GetMock&lt;T&gt; as described below first)</p>

<blockquote>
  <p>public Mock&lt;T&gt; GetMock&lt;T&gt;() where T : class</p>
</blockquote>

<p>When T is an interface GetMock&lt;T&gt; should return basically “(new Mock&lt;T&gt;())” </p>

<p>When T is a concrete Class, the container should return a new Mock&lt;T&gt;() and any of it’s dependencies will be satisfied by mocks.</p>

<h4>How do I use the UnityAutoMockContainer?</h4>

<p>It’s pretty basic, you first create an instance of the UnityAutoMockContainer, and from there you can ask it for mocks of an (Interface, Class, or Abstract Class).</p>

<p>If you request an instance of a concrete class, or abstract class, the UnityAutoMockContainer will stuff mocks in for any constructor dependencies of your concrete class (if it can). You can then request from the container those same dependencies one at a time and either apply mocking setups or verifications.</p>

<blockquote>
  <p><strong>NOTE:</strong> Anything the container creates will live as a singleton instance in the container. So any other requests from the container will always return the originally created instance. Therefore, each distinct scenario in a test suite should have their own instances of the container.</p>
</blockquote>

<p>Below his an example of how you can leverage the container in some tests. Given this base fixture class…</p>

<pre class="brush: csharp;">public class FixtureBase
{
    private readonly UnityAutoMockContainer _autoMockContainer = new UnityAutoMockContainer();

    protected UnityAutoMockContainer AutoMockContainer
    {
        get { return _autoMockContainer; }
    }

    [TestFixtureSetUp]
    public void SetupContext_ALL()
    {
        Before_all_tests();
        Because();
    }

    [TestFixtureTearDown]
    public void TearDownContext_ALL()
    {
        After_all_tests();
    }

    protected virtual void Before_all_tests()
    {
    }

    protected virtual void Because()
    {
    }

    protected virtual void After_all_tests()
    {
    }
}</pre>

<p>If I were given the following system to test.</p>

<pre class="brush: csharp;">public interface IServiceA { void RunA(); }
public interface IServiceB { void RunB(); }

public class TestComponent
{
    public TestComponent(IServiceA serviceA, IServiceB serviceB)
    {
        ServiceA = serviceA;
        ServiceB = serviceB;
    }

    public IServiceA ServiceA { get; private set; }
    public IServiceB ServiceB { get; private set; }

    public void RunAll()
    {
        if (!HowDidItGo())
            return;
        ServiceA.RunA();
        ServiceB.RunB();
    }

    public virtual bool HowDidItGo()
    {
        // some really nasty untestable code
        return true;
    }
}</pre>

<p>The below example demonstrates simply verifying some behavior on the mocked dependencies of the system under test.</p>

<pre class="brush: csharp;">[TestFixture]
public class Example__how_to_pull_items_from_the_UnityAutoMockContainer_when_verifying_behavior_after_an_action_was_taken 
    : FixtureBase
{
    private TestComponent _testComponent;

    protected override void Before_all_tests()
    {
        base.Before_all_tests();
        _testComponent = AutoMockContainer.Resolve&lt;TestComponent&gt;();
    }

    protected override void Because()
    {
        _testComponent.RunAll();
    }

    [Test]
    public void Should_run_ServiceA_RunA()
    {
        AutoMockContainer
            .GetMock&lt;IServiceA&gt;()
            .Verify(v =&gt; v.RunA(), Times.Once());
    }

    [Test]
    public void Should_run_ServiceB_RunB()
    {
        AutoMockContainer
            .GetMock&lt;IServiceB&gt;()
            .Verify(v =&gt; v.RunB(), Times.Once());
    }
}</pre>

<p>Next, you may have noticed that the system under test had a complicated internal method (that may not necessarily be testable). You can use the AutoMocker to create the system under test as a Mock itself, so we can override some of the behavior. Here’s how you could quickly do that. </p>

<blockquote>
  <p><strong>Aside</strong>: I’m not saying this is a good practice or aids in good component design, just saying it’s possible</p>
</blockquote>

<pre class="brush: csharp;">[TestFixture]
public class Example__how_to_use_the_UnityAutoMockContainer_to_override_a_method_on_the_SystemUnderTest_to_test_a_certain_behavior
    : FixtureBase
{

    private TestComponent _testComponent;

    protected override void Before_all_tests()
    {
        base.Before_all_tests();
        var mockTestComponent = AutoMockContainer.GetMock&lt;TestComponent&gt;();

        mockTestComponent
            .Setup(s =&gt; s.HowDidItGo())
            .Returns(false);

        _testComponent = mockTestComponent.Object;
    }

    protected override void Because()
    {
        _testComponent.RunAll();
    }

    [Test]
    public void Should_run_ServiceA_RunA()
    {
        AutoMockContainer
            .GetMock&lt;IServiceA&gt;()
            .Verify(v =&gt; v.RunA(), Times.Never());
    }

    [Test]
    public void Should_run_ServiceB_RunB()
    {
        AutoMockContainer
            .GetMock&lt;IServiceB&gt;()
            .Verify(v =&gt; v.RunB(), Times.Never());
    }
}</pre>

<p>&#160;</p>

<p>It’s amazing how much redundant test setup code this little helper has saved me in my tests. I hope others can find some use with this as well.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/01/03/unitymoq-automocker-or-automockingcontainer/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>StatLight &#8211; Goes Open Source</title>
		<link>http://elegantcode.com/2009/12/10/statlight-goes-open-source/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=statlight-goes-open-source</link>
		<comments>http://elegantcode.com/2009/12/10/statlight-goes-open-source/#comments</comments>
		<pubDate>Fri, 11 Dec 2009 03:26:55 +0000</pubDate>
		<dc:creator>Jason Jarrett</dc:creator>
				<category><![CDATA[Esoterica]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[TDD]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Tools and Utilities]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/12/10/statlight-goes-open-source/</guid>
		<description><![CDATA[Although I made a very minor attempt at making StatLight a “for-sale” product, I knew when I started that open-source was most likely going to be my long term path for StatLight. What is it? (Silverlight Testing Automation Tool) StatLight is a tool developed for automating the setup, running, and gathering results of Silverlight unit [...]]]></description>
			<content:encoded><![CDATA[Although I made a very minor attempt at making <a href="http://statlight.net" target="_blank">StatLight</a> a “for-sale” product, I knew when I started that open-source was most likely going to be my long term path for <a href="http://statlight.net" target="_blank">StatLight</a>.
<h5>What is it? (Silverlight Testing Automation Tool)</h5>
StatLight is a tool developed for automating the setup, running, and gathering results of Silverlight unit tests. StatLight helps to speed up the feedback cycles while practicing<a href="http://en.wikipedia.org/wiki/Test-driven_development"> TDD</a>/<a href="http://en.wikipedia.org/wiki/Behavior_Driven_Development">BDD</a>/(insert your test style here) during Silverlight development.
<h5>Where can I get StatLight?</h5>
<a href="http://StatLight.CodePlex.com">http://StatLight.CodePlex.com</a>
<h4>Happy Coding !!!</h4>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/12/10/statlight-goes-open-source/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Wrapping up the StructureMap Automocking Container</title>
		<link>http://elegantcode.com/2009/11/30/wrapping-up-the-structuremap-automocking-container/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=wrapping-up-the-structuremap-automocking-container</link>
		<comments>http://elegantcode.com/2009/11/30/wrapping-up-the-structuremap-automocking-container/#comments</comments>
		<pubDate>Mon, 30 Nov 2009 07:21:43 +0000</pubDate>
		<dc:creator>Richard Cirerol</dc:creator>
				<category><![CDATA[TDD]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Unit Testing]]></category>
		<category><![CDATA[StructureMap; Automocking; MSpec;]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/11/30/wrapping-up-the-structuremap-automocking-container/</guid>
		<description><![CDATA[<p><font color="#804040"><strong>UPDATE</strong>: I apologize…the original wrapper did not allow injected dependencies.&#160; I have fixed this bug and updated the sample.</font></p> I have been using StructureMap.AutoMocking with MSpec (Machine.Specifications) and Rhino.Mocks for a few months now.  Although I am very comfortable with the patterns that emerge from using the frameworks together, introducing StructureMap.Automocking to other developers is sometimes challenging. I decided to wrap the details of the container to make the intention clearer and explanation easier.  I have started using this wrapper in my projects, and have found it makes building up specifications more efficient in my daily coding.]]></description>
			<content:encoded><![CDATA[<span style="color: #804040;"><strong>UPDATE</strong>: I apologize…the original wrapper did not allow injected dependencies.  I have fixed this bug and updated the sample.</span>

I have been using StructureMap.AutoMocking with MSpec (Machine.Specifications) and Rhino.Mocks for a few months now.  Although I am very comfortable with the patterns that emerge from using the frameworks together, introducing StructureMap.Automocking to other developers is sometimes challenging.

When viewing a specification or test set up with the Rhino.Mocks or Moq automocking container, what is being tested is not readily apparent.  Once the concept is explained and demonstrated, these same developers seem to have no issue with maintaining the specifications/tests.

I decided to wrap the details of the container to make the intention clearer and explanation easier.  I have started using this wrapper in my projects, and have found it makes building up specifications more efficient in my daily coding.

Let me know whether this is useful to you, or how it could be made more useful.
<h4>The Examples</h4>
Let’s contrive an example.  We’ll say we have a coffee machine that grinds its own beans before brewing. However, the hopper has to have beans before starting the grind.  Here is the basic specification:
<table border="1" cellspacing="0" cellpadding="2" width="533">
<tbody>
<tr>
<td width="117" valign="top">Action/Behavior</td>
<td width="414" valign="top">Prepare coffee grounds for 12 cups of coffee</td>
</tr>
<tr>
<td rowspan="2" width="117" valign="top">Expectations</td>
<td width="414" valign="top">Should check that hopper has beans (mock returns true)</td>
</tr>
<tr>
<td width="414" valign="top">Because hopper has beans, should ask grinder to grind enough beans for 12 cups of coffee</td>
</tr>
</tbody></table>
We could start without a container, using Rhino.Mocks to build up the CoffeeMachine dependencies manually:
<pre class="brush: csharp;">[Subject(typeof(CoffeeMachine),"using vanilla Rhino.Mocks")]
public class Example01_when_preparing_coffee_grounds
{
    Establish context = () =&gt;
        {
            Grinder = MockRepository.GenerateMock&lt;IGrinder&gt;();
            Hopper = MockRepository.GenerateMock&lt;IHopper&gt;();
            Hopper.Expect(x =&gt; x.HasBeans()).Return(true);
            CoffeeMachine = new CoffeeMachine(Grinder, Hopper);
        };

    Because of = () =&gt; _coffeeMachine.PrepareCoffeeGrounds(12);

    It should_check_if_hopper_has_beans = () =&gt; Hopper.VerifyAllExpectations();
    It should_grind_coffee = () =&gt; Grinder.AssertWasCalled(x =&gt; x.Grind(12));

    static IGrinder Grinder;
    static IHopper Hopper;
    static CoffeeMachine CoffeeMachine;
}</pre>
For those of you not familiar with the MSpec style, please refer to the following posts:
<ul>
	<li><a href="http://blog.wekeroad.com/blog/make-bdd-your-bff-2/" target="_blank">Make BDD Your BFF</a></li>
	<li><a href="http://www.lostechies.com/blogs/seanbiefeld/archive/2009/08/25/step-by-step-to-using-machine-specifications-with-resharper.aspx" target="_blank">Step by Step to Using MSpec (Machine.Specifications) with ReSharper</a></li>
	<li><a href="http://elegantcode.com/2009/07/05/mspec-take-2/" target="_blank">MSpec - Take 2</a></li>
	<li><a href="http://marcinobel.com/index.php/mspec-bdd-installer/" target="_blank">MSpec BDD framework installer</a></li>
	<li><strong>Updated! </strong>From the <a href="http://blog.cwa.me.uk/2009/11/30/the-morning-brew-487/" target="_blank">Morning Brew #487</a>: BDD with MSpec and Rhino Auto Mocks, parts  <a href="http://telldontask.wordpress.com/2009/11/10/bdd-with-mspec-and-rhino-auto-mocks/" target="_blank">1</a>, <a href="http://telldontask.wordpress.com/2009/11/19/bdd-with-mspec-and-rhino-auto-mocks-part-2/" target="_blank">2</a>, and <a href="http://telldontask.wordpress.com/2009/11/29/bdd-with-mspec-and-rhino-auto-mocks-part-3/" target="_blank">3</a>
Here is the same specification using the RhinoAutoMocker&lt;T&gt; class provided by StructureMap.AutoMocking:</li>
</ul>
<pre class="brush: csharp;">[Subject(typeof(CoffeeMachine),"using RhinoAutoMocker&lt;CoffeeMachine&gt;")]
public class Example02_when_preparing_coffee_grounds
{
    Establish context = () =&gt;
        {
            CoffeeMachine = new RhinoAutoMocker&lt;CoffeeMachine&gt;();
            Grinder = CoffeeMachine.Get&lt;IGrinder&gt;();
            Hopper = CoffeeMachine.Get&lt;IHopper&gt;();
            Hopper.Expect(x =&gt; x.HasBeans()).Return(true);
        };

    Because of = () =&gt; v.ClassUnderTest.PrepareCoffeeGrounds(12);

    It should_check_if_hopper_has_beans = () =&gt; Hopper.VerifyAllExpectations();
    It should_grind_coffee = () =&gt; Grinder.AssertWasCalled(x =&gt; x.Grind(12));

    static IGrinder Grinder;
    static IHopper Hopper;
    static RhinoAutoMocker&lt;CoffeeMachine&gt; CoffeeMachine;
}</pre>
Although I think this looks cleaner, the initialization of CoffeeMachine causes some confusion. Unfortunately, a common question would be, “Is RhinoAutoMocker&lt;CoffeeMachine&gt; creating a mocked version of CoffeeMachine?” Well, not exactly.

RhinoAutoMocker is an implementation of the AutoMocker base class which uses StructureMap to fill dependencies.  The RhinoAutoMocker implementation of the container uses Rhino.Mocks to generate all of dependencies of the target class, whereas the MoqAutoMocker implementation uses Moq.  (Optionally, the target class can be partially mocked in order to further isolate behavior.)  We then retrieve the class under test (in this case, CoffeeMachine) and its dependencies (IGrinder and IHopper) from the container for use.

If you do not need to setup any expectations in the specification, there is no need to retrieve the dependency from the container.  However, in this specification, we need both dependencies.

<em>(Incidentally, I do not like the ClassUnderTest name.  I may end up changing this to Instance, ClassInstance, TargetClass, or something similar.  Suggestions?)</em>

By moving the initialization of the RhinoAutoMocker to a base class, some of the chattiness of the context can be hidden.
<ul>
<pre class="brush: csharp;">[Subject(typeof(CoffeeMachine),"using RhinoAutoMocker base")]
public class Example03_when_preparing_coffee_grounds : with_rhinoautomocker
{
    Establish context = () =&gt; Hopper.Expect(x =&gt; x.HasBeans()).Return(true);

    Because of = () =&gt; CoffeeMachine.ClassUnderTest.PrepareCoffeeGrounds(12);

    It should_check_if_hopper_has_beans = () =&gt; Hopper.VerifyAllExpectations();
    It should_grind_coffee = () =&gt; Grinder.AssertWasCalled(x =&gt; x.Grind(12));

}

[Subject("using RhinoAutoMocker&lt;T&gt;")]
public class with_rhinoautomocker
{
    protected static IGrinder Grinder;
    protected static IHopper Hopper;
    protected static RhinoAutoMocker&lt;CoffeeMachine&gt; CoffeeMachine;

    Establish context = () =&gt;
    {
        CoffeeMachine = new RhinoAutoMocker&lt;CoffeeMachine&gt;();
        Grinder = CoffeeMachine.Get&lt;IGrinder&gt;();
        Hopper = CoffeeMachine.Get&lt;IHopper&gt;();
    };
}</pre>
However, we are still initializing and accessing the class in a less than optimal manner.To make the usage of the container a little more seamless, I decided to create a wrapper and factory for the AutoMocker.  Setup of the dependencies and expectations are done through an AutoMocker wrapper object.  The instance of the class under test is accessed through a ClassUnderTest object.
<h4>The Result</h4>
The specification (and base class) now look like this:
<pre class="brush: csharp;">[Subject(typeof(CoffeeMachine),"using coffee machine base")]
public class Example05_when_preparing_coffee_grounds : with_coffee_machine
{
    Establish context = () =&gt; Hopper.Expect(x =&gt; x.HasBeans()).Return(true);

    Because of = () =&gt; ClassUnderTest.PrepareCoffeeGrounds(12);

    It should_check_if_hopper_has_beans = () =&gt; Hopper.VerifyAllExpectations();
    It should_grind_coffee = () =&gt; Grinder.AssertWasCalled(x =&gt; x.Grind(12));
}

[Subject("using SpecificationFor&lt;CoffeeMachine&gt;")]
public class with_coffee_machine : SpecificationFor&lt;CoffeeMachine&gt;
{
    protected static IGrinder Grinder;
    protected static IHopper Hopper;

    public with_coffee_machine
    {
        Grinder = AutoMocker.Get&lt;IGrinder&gt;();
        Hopper = AutoMocker.Get&lt;IHopper&gt;();
    }
}</pre>
As you can see, the base class inherits from SpecificationFor&lt;T&gt;.  The default constructor uses Rhino.Mocks(MockMode.AAA) to generate the dependencies.  It then exposes a AutoMocker object, which is just the wrapper around the AutoMocker base class.  It also exposes a ClassUnderTest object.  If I didn’t need to use the dependencies, I could make the <em>Example05_when_preparing_coffee_grounds</em> class inherit from <em>SpecificationFor&lt;CoffeeMachine&gt; </em>instead of inheriting from the base class<em>.</em>
<h4>The Code</h4>
I have included the code for the wrapper below for your review.  The code and six examples are available on my <a href="http://codeprogression.googlecode.com/svn/trunk/CodeProgression.Framework.Testing" target="_blank">Google code repository</a>. The repository also includes an example using the MoqAutoMocker.  All the examples have the same assertions, but are built up using the different techniques.
<pre class="brush: csharp;">namespace CodeProgression.Framework.Testing
{
    public abstract class SpecificationFor&lt;T&gt; where T: class
    {
        protected static ClassUnderTest&lt;T&gt; Factory;

        // UPDATE 2009-12-21:
        //   Moved initialization here
        protected static T ClassUnderTest {get {return AutoMocker.Instance;} }

        protected SpecificationFor()
        {
            AutoMocker = AutoMockFactory.CreateTarget&lt;T&gt;();

            // UPDATE 2009-12-21:
            //    Initializing here prevented injected dependencies!
            // AutoMocker.PartialMockTheClassUnderTest();
            // ClassUnderTest = AutoMocker.Instance;
        }

        protected SpecificationFor(AutoMockType type)
        {
            AutoMocker = AutoMockFactory.CreateTarget&lt;T&gt;(type);

            // UPDATE 2009-12-21:
            // Initializing here prevented injected dependencies!
            // AutoMocker.PartialMockTheClassUnderTest();
            // ClassUnderTest = AutoMocker.Instance;
        }
    }

    public static class AutoMockFactory
    {
        public static ClassUnderTest&lt;TARGETCLASS&gt; CreateTarget&lt;TARGETCLASS&gt;() where TARGETCLASS : class
        {
            return CreateTarget&lt;TARGETCLASS&gt;(AutoMockType.RhinoMocksAAA);
        }

        public static ClassUnderTest&lt;TARGETCLASS&gt; CreateTarget&lt;TARGETCLASS&gt;(AutoMockType framework) where TARGETCLASS : class
        {
            AutoMocker&lt;TARGETCLASS&gt; mocker;
            ServiceLocator serviceLocator;
            switch (framework)
            {
                case AutoMockType.RhinoMocksAAA:
                    mocker = new RhinoAutoMocker&lt;TARGETCLASS&gt;(MockMode.AAA);
                    serviceLocator = new RhinoMocksAAAServiceLocator();
                    break;
                case AutoMockType.RhinoMocksClassic:
                    mocker = new RhinoAutoMocker&lt;TARGETCLASS&gt;(MockMode.RecordAndReplay);
                    serviceLocator = new RhinoMocksClassicServiceLocator();
                    break;
                case AutoMockType.Moq:
                    mocker = new MoqAutoMocker&lt;TARGETCLASS&gt;();
                    serviceLocator = new MoqServiceLocator();
                    break;
                default:
                    throw new ArgumentOutOfRangeException("framework");
            }
            return new ClassUnderTest&lt;TARGETCLASS&gt;(mocker, serviceLocator);
        }
    }

    public enum AutoMockType
    {
        Moq,
        RhinoMocksAAA,
        RhinoMocksClassic
    }

    public class ClassUnderTest&lt;TARGETCLASS&gt; where TARGETCLASS : class
    {
        readonly IAutoMocker&lt;TARGETCLASS&gt; _mocker;
        readonly ServiceLocator _serviceLocator;

        public ClassUnderTest(IAutoMocker&lt;TARGETCLASS&gt; mocker, ServiceLocator serviceLocator)
        {
            _mocker = mocker;
            _serviceLocator = serviceLocator;
        }

        public AutoMockedContainer Container
        {
            get { return _mocker.Container; }
        }

        public TARGETCLASS Instance
        {
            get { return _mocker.ClassUnderTest; }
        }

        public void MockObjectFactory()
        {
            _mocker.MockObjectFactory();
        }

        public void PartialMockTheClassUnderTest()
        {
            _mocker.PartialMockTheClassUnderTest();
        }

        public T Get&lt;T&gt;() where T : class
        {
            return _mocker.Get&lt;T&gt;();
        }

        public void Inject(Type pluginType, object stub)
        {
            _mocker.Inject(pluginType, stub);
        }

        public void Inject&lt;T&gt;(T target)
        {
            _mocker.Inject(target);
        }

        public T AddAdditionalMockFor&lt;T&gt;() where T : class
        {
            return _mocker.AddAdditionalMockFor&lt;T&gt;();
        }

        public void UseConcreteClassFor&lt;T&gt;()
        {
            _mocker.UseConcreteClassFor&lt;T&gt;();
        }

        public T[] CreateMockArrayFor&lt;T&gt;(int count) where T : class
        {
            return _mocker.CreateMockArrayFor&lt;T&gt;(count);
        }

        public void InjectArray&lt;T&gt;(T[] stubs)
        {
            _mocker.InjectArray(stubs);
        }

        public T Mock&lt;T&gt;() where T : class
        {
            return _serviceLocator.Service&lt;T&gt;();
        }
        public object Mock(Type serviceType)
        {
            return _serviceLocator.Service(serviceType);
        }
        public T PartialMock&lt;T&gt;() where T : class
        {
            return _serviceLocator.PartialMock&lt;T&gt;();
        }
    }
}</pre>
</ul>
<script type="text/javascript">// <![CDATA[
 var cirerolGaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."); document.write(unescape("%3Cscript src='" + cirerolGaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
// ]]&gt;</script>

<script type="text/javascript">// <![CDATA[
 var cirerolPageTracker = _gat._getTracker('UA-8257866-3'); cirerolPageTracker._initData(); cirerolPageTracker._trackPageview();
// ]]&gt;</script>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/11/30/wrapping-up-the-structuremap-automocking-container/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Integration Test Brought to you by Powershell &amp; NUnit &#8211; with a Little Specification Syntax for Flavoring</title>
		<link>http://elegantcode.com/2009/10/25/integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring</link>
		<comments>http://elegantcode.com/2009/10/25/integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring/#comments</comments>
		<pubDate>Mon, 26 Oct 2009 05:00:40 +0000</pubDate>
		<dc:creator>Jason Jarrett</dc:creator>
				<category><![CDATA[Esoterica]]></category>
		<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/10/25/integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring/</guid>
		<description><![CDATA[One of the tools I’ve used the last half of a year and really enjoyed is the C# specification extension methods when writing unit test assertions. If you’re looking for a little more background on the topic, I wrote about Fluent Specification Extensions in a past blog. Recently I wanted to execute a PowerShell script [...]]]></description>
			<content:encoded><![CDATA[One of the tools I’ve used the last half of a year and really enjoyed is the C# specification extension methods when writing unit test assertions. If you’re looking for a little more background on the topic, I wrote about <a href="http://staxmanade.blogspot.com/2009/02/fluent-specification-extensions.html">Fluent Specification Extensions</a> in a past blog.

Recently I wanted to execute a PowerShell script to do some automated <a href="http://en.wikipedia.org/wiki/Functional_testing">functional testing</a>. I wanted to execute an application and apply some assertions on the output of the software(basically running a console app, parse the xml output and assert on values in the output).
<blockquote>FYI: I’m very new to PowerShell, so any suggestions on how I implemented the below are welcome…</blockquote>
I’ve seen a couple examples of writing test assertions in PowerShell out there. One example is <a href="http://www.psunit.org/">PSUnit</a>; however, this seemed a little heavy for my needs and not quite the syntactic sugar I was looking for.

Besides the syntax flavor I was desiring, another thing I wanted to do was leverage the power of NUnit.Framework’s assertion capabilities. I like the error messages generated when strings and other objects fail the assertion.
<h5>Examples of end result ShouldLookLike()…</h5>
$true.ShouldBeTrue()
$false.ShouldBeFalse()
"a".ShouldEqual("a")
"a".ShouldNotEqual("b")
<h5><strong>Step 1</strong>: Figure out how to write a C# style <a href="http://msdn.microsoft.com/en-us/library/bb383977.aspx">extension method</a> in PowerShell.</h5>
<blockquote>I found a great blog post describing how to extend any PowerShell object to add extension methods.

<a href="http://bartdesmet.net/blogs/bart/archive/2007/09/06/extension-methods-in-windows-powershell.aspx">Extension Methods in Windows PowerShell</a></blockquote>
In short, to extend types in PowerShell leveraging the <a href="http://msdn.microsoft.com/en-us/library/ms714419(VS.85).aspx">Extended Type System</a>, you need to define them in an xml file and import the method definitions into the PowerShell runtime instance.

Below is PowerShell XML definition for my NUnit Specification Extensions.
<pre class="brush: xml;">&lt;?xml version="1.0" encoding="utf-16"?&gt;
&lt;Types&gt;
    &lt;Type&gt;
        &lt;Name&gt;System.Object&lt;/Name&gt;
        &lt;Members&gt;
            &lt;ScriptMethod&gt;
                &lt;Name&gt;ShouldBeFalse&lt;/Name&gt;
                &lt;Script&gt;
                    [NUnit.Framework.Assert]::IsFalse($this)
                &lt;/Script&gt;
            &lt;/ScriptMethod&gt;
            &lt;ScriptMethod&gt;
                &lt;Name&gt;ShouldBeTrue&lt;/Name&gt;
                &lt;Script&gt;
                    [NUnit.Framework.Assert]::IsTrue($this)
                &lt;/Script&gt;
            &lt;/ScriptMethod&gt;
            &lt;ScriptMethod&gt;
                &lt;Name&gt;ShouldEqual&lt;/Name&gt;
                &lt;Script&gt;
                    [NUnit.Framework.Assert]::AreEqual($args[0], $this)
                &lt;/Script&gt;
            &lt;/ScriptMethod&gt;
            &lt;ScriptMethod&gt;
                &lt;Name&gt;ShouldNotEqual&lt;/Name&gt;
                &lt;Script&gt;
                    [NUnit.Framework.Assert]::AreNotEqual($args[0], $this)
                &lt;/Script&gt;
            &lt;/ScriptMethod&gt;
        &lt;/Members&gt;
    &lt;/Type&gt;
&lt;/Types&gt;</pre>
<h4></h4>
Take the above XML and save it to a file…
<blockquote>NOTE: the file HAS to be saved with the extension <strong>.ps1xml</strong>

Ex: NunitSpecificationPowerShellExtensions<strong>.ps1xml</strong></blockquote>
<h4></h4>
<h5>Step 2: Load the extended type definition into the PowerShell runtime.</h5>
Once you’ve saved the XML extended types to a file, you need to load it into the PowerShell runtime by executing the command below.
<blockquote>
Update-TypeData -PrependPath NunitSpecificationPowerShellExtensions.ps1xml</blockquote>
Before executing the above statement…Let’s quickly look at a System.String’s members and properties – just to show you what the extension methods look like when applied inside of the runtime.<a href="http://elegantcode.com/wp-content/uploads/2009/10/image3.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" src="http://elegantcode.com/wp-content/uploads/2009/10/image_thumb2.png" border="0" alt="image" width="586" height="479" /></a>

After executing the Update-TypeData command you’ll notice there are a number of “ScriptMethod” MemberTypes added to the object.

<a href="http://elegantcode.com/wp-content/uploads/2009/10/image4.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" src="http://elegantcode.com/wp-content/uploads/2009/10/image_thumb3.png" border="0" alt="image" width="600" height="580" /></a>

Now if you try to execute one of those newly added extension methods, you may get the following error…

PS C:\&gt; $testVar.<strong>ShouldEqual</strong>("hello world")

Exception calling "ShouldEqual" with "1" argument(s): "<strong>Unable to find type [NUnit.Framework.Assert]: make sure that the

assembly containing this type is loaded.</strong>"

At line:1 char:21

+ $testVar.ShouldEqual &lt;&lt;&lt;&lt; ("hello world")

+ CategoryInfo          : NotSpecified: (:) [], MethodInvocationException

+ FullyQualifiedErrorId : ScriptMethodRuntimeException

This is because we need to load the NUnit.Framework assembly into the runtime before we can leverage the extension methods.
<blockquote>[System.Reflection.Assembly]::LoadFrom("C:\Program Files\NUnit 2.5.2\bin\net-2.0\framework\nunit.framework.dll") | Out-Null</blockquote>
Now that the extension methods have been defined and loaded into the runtime, NUnit.Framework is loaded, we can now use the methods on any object that inherits from System.Object (which, as far as I know, is everything in PowerShell).

And now, everything you need in one script (if you have the xml extended type file saved somewhere…)
<pre>#
# Update-TypeData -prependPath C:\Code\NunitSpecificationPowerShellExtensions.ps1xml
#

[System.Reflection.Assembly]::LoadFrom("C:\Program Files\NUnit 2.5.2\bin\net-2.0\framework\nunit.framework.dll") | Out-Null

$true.ShouldBeTrue()

$false.ShouldBeFalse()

"a".ShouldEqual("a")

"a".ShouldNotEqual("b")</pre>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/10/25/integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Visual Studio Team System for Small Teams</title>
		<link>http://elegantcode.com/2010/11/30/autotest-net/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=autotest-net</link>
		<comments>http://elegantcode.com/2010/11/30/autotest-net/#comments</comments>
		<pubDate>Tue, 30 Nov 2010 11:00:00 +0000</pubDate>
		<dc:creator>Jan Van Ryswyck</dc:creator>
				<category><![CDATA[TDD]]></category>
		<category><![CDATA[Tools and Utilities]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/11/30/autotest-net/</guid>
		<description><![CDATA[I just want to quickly point out a tool that I’ve been playing with for a couple of days now, named AutoTest.NET. Its an open-source tool that originates from a popular tool in the Ruby community called ZenTest, which basically runs all your valuable unit tests when you save your source files or when you [...]]]></description>
			<content:encoded><![CDATA[<p>I just want to quickly point out a tool that I’ve been playing with for a couple of days now, named <a href="https://github.com/acken/AutoTest.Net" target="_blank">AutoTest.NET</a>. Its an open-source tool that originates from a popular tool in the Ruby community called <a href="http://www.zenspider.com/ZSS/Products/ZenTest/" target="_blank">ZenTest</a>, which basically runs all your valuable unit tests when you save your source files or when you build your code. It enables you to get feedback about your changes as soon as possible.</p>  <p>The project started out a couple of years ago on <a href="http://code.google.com/p/autotestnet/" target="_blank">Google code</a> and was first initiated by <a href="http://averyblog.com/" target="_blank">James Avery</a>. Contribution stopped at some point until recently where <a href="http://ackenpacken.blogspot.com/" target="_blank">Svein Arne Ackenhausen</a> forked the source code and <a href="https://github.com/acken/AutoTest.Net" target="_blank">put it on GitHub</a>. Now it runs both for .NET as well as Mono, with NUnit, MSTest and xUnit as the currently supported unit test frameworks. </p>  <p>Here’s a screenshot from the feedback window when all tests pass:</p>  <p><a href="http://elegantcode.com/wp-content/uploads/2010/11/Success.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="Success" border="0" alt="Success" src="http://elegantcode.com/wp-content/uploads/2010/11/Success_thumb.png" width="540" height="189" /></a> </p>  <p>And here you can see the same window after I broke one of my unit tests:</p>  <p><a href="http://elegantcode.com/wp-content/uploads/2010/11/Failure.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="Failure" border="0" alt="Failure" src="http://elegantcode.com/wp-content/uploads/2010/11/Failure_thumb.png" width="538" height="319" /></a> </p>  <p>Here you can see which particular unit test has been broken and by clicking the specified link you end up at the right source file in Visual Studio. </p>  <p>I encourage you to pick up this small tool and learn how it can facilitate your TDD flow. Take a look at <a href="https://github.com/acken/AutoTest.Net/wiki/Get-started!" target="_blank">this page</a> in order to get up-and-running in no time. Also don’t forget to provide the owner(s) of this project with some feedback that you might have. Svein has been very helpful over the last week answering all my stupid questions and remarks (and the Nobel price for this year’s most patient person goes to … ;-) ). </p>  <p>I would definitely like to see this tool becoming more popular, so go check it out.&#160;&#160; </p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/11/30/autotest-net/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Elegant Code &#187; Unit Testing</title>
	<atom:link href="http://elegantcode.com/category/unit-testing/feed/" rel="self" type="application/rss+xml" />
	<link>http://elegantcode.com</link>
	<description></description>
	<lastBuildDate>Tue, 15 May 2012 10:00:00 +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>AutoTest.NET</title>
		<link>http://elegantcode.com/2010/11/30/autotest-net/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=autotest-net</link>
		<comments>http://elegantcode.com/2010/11/30/autotest-net/#comments</comments>
		<pubDate>Tue, 30 Nov 2010 11:00:00 +0000</pubDate>
		<dc:creator>Jan Van Ryswyck</dc:creator>
				<category><![CDATA[TDD]]></category>
		<category><![CDATA[Tools and Utilities]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/11/30/autotest-net/</guid>
		<description><![CDATA[I just want to quickly point out a tool that I’ve been playing with for a couple of days now, named AutoTest.NET. Its an open-source tool that originates from a popular tool in the Ruby community called ZenTest, which basically runs all your valuable unit tests when you save your source files or when you [...]]]></description>
			<content:encoded><![CDATA[<p>I just want to quickly point out a tool that I’ve been playing with for a couple of days now, named <a href="https://github.com/acken/AutoTest.Net" target="_blank">AutoTest.NET</a>. Its an open-source tool that originates from a popular tool in the Ruby community called <a href="http://www.zenspider.com/ZSS/Products/ZenTest/" target="_blank">ZenTest</a>, which basically runs all your valuable unit tests when you save your source files or when you build your code. It enables you to get feedback about your changes as soon as possible.</p>  <p>The project started out a couple of years ago on <a href="http://code.google.com/p/autotestnet/" target="_blank">Google code</a> and was first initiated by <a href="http://averyblog.com/" target="_blank">James Avery</a>. Contribution stopped at some point until recently where <a href="http://ackenpacken.blogspot.com/" target="_blank">Svein Arne Ackenhausen</a> forked the source code and <a href="https://github.com/acken/AutoTest.Net" target="_blank">put it on GitHub</a>. Now it runs both for .NET as well as Mono, with NUnit, MSTest and xUnit as the currently supported unit test frameworks. </p>  <p>Here’s a screenshot from the feedback window when all tests pass:</p>  <p><a href="http://elegantcode.com/wp-content/uploads/2010/11/Success.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="Success" border="0" alt="Success" src="http://elegantcode.com/wp-content/uploads/2010/11/Success_thumb.png" width="540" height="189" /></a> </p>  <p>And here you can see the same window after I broke one of my unit tests:</p>  <p><a href="http://elegantcode.com/wp-content/uploads/2010/11/Failure.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="Failure" border="0" alt="Failure" src="http://elegantcode.com/wp-content/uploads/2010/11/Failure_thumb.png" width="538" height="319" /></a> </p>  <p>Here you can see which particular unit test has been broken and by clicking the specified link you end up at the right source file in Visual Studio. </p>  <p>I encourage you to pick up this small tool and learn how it can facilitate your TDD flow. Take a look at <a href="https://github.com/acken/AutoTest.Net/wiki/Get-started!" target="_blank">this page</a> in order to get up-and-running in no time. Also don’t forget to provide the owner(s) of this project with some feedback that you might have. Svein has been very helpful over the last week answering all my stupid questions and remarks (and the Nobel price for this year’s most patient person goes to … ;-) ). </p>  <p>I would definitely like to see this tool becoming more popular, so go check it out.&#160;&#160; </p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/11/30/autotest-net/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>If Self-Documenting Code is the What, Unit Tests are the Why</title>
		<link>http://elegantcode.com/2010/04/25/if-self-documenting-code-is-the-what-unit-tests-are-the-why/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=if-self-documenting-code-is-the-what-unit-tests-are-the-why</link>
		<comments>http://elegantcode.com/2010/04/25/if-self-documenting-code-is-the-what-unit-tests-are-the-why/#comments</comments>
		<pubDate>Sun, 25 Apr 2010 19:09:04 +0000</pubDate>
		<dc:creator>John Sonmez</dc:creator>
				<category><![CDATA[Agile]]></category>
		<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Craftsmanship]]></category>
		<category><![CDATA[Documentation]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/04/25/if-self-documenting-code-is-the-what-unit-tests-are-the-why/</guid>
		<description><![CDATA[It is not enough to just write code that is clean and self-documenting.  Eliminating comments and replacing them with clear variable and method names, will tell the reader of your code clearly what it is doing, but it will not properly express why it is doing it. If you recall from my original post on [...]]]></description>
			<content:encoded><![CDATA[It is not enough to just write code that is clean and self-documenting.  <a href="http://elegantcode.com/2010/04/18/eliminating-comments-the-road-to-clarity/">Eliminating comments</a> and replacing them with clear variable and method names, will tell the reader of your code clearly what it is doing, but it will not properly express why it is doing it.

If you recall from my <a href="http://elegantcode.com/2010/04/09/what-does-elegant-code-mean-to-me/">original post</a> on Elegant code, I stated that elegant code is:
<blockquote>Something that is simple yet effective, delivered with grace.</blockquote>
By writing self-documenting code we are hopefully able to achieve some of the aspects of simplicity and grace, but it tells us nothing about the effectiveness of the code.
<h2>Bringing the dead to life</h2>
<a href="http://elegantcode.com/wp-content/uploads/2010/04/zombies.jpg"><img style="border-right-width: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto" title="zombies" src="http://elegantcode.com/wp-content/uploads/2010/04/zombies_thumb.jpg" border="0" alt="zombies" width="441" height="295" /></a>

Throwing out comments is a debatable topic.  <a href="http://www.reddit.com/r/programming/comments/bsutx/">It raises quite a bit of controversy</a>, as you can see from some of the comments on my post about the subject.  The reason, perhaps, that so many people are so staunchly opposed to the idea, is because they are worried, and rightly so, that throwing out comments will reduce the documentation of what the code is doing.

Think about that for a second.  Is documentation of what the code is doing important?  It better be.  What we are trying to accomplish by writing self-documenting code instead of comments, is to take the vessel, which is the code itself, and make that same vessel be the documentation of what the code does.  It is by doing this that we creating a living representation of the functionality of the code.  Comments are akin to a dead representation of the functionality of the code because they do not change automatically with the code.

I diverge to talk about comments so that I can draw a parallel to another form of documentation which is valuable and should be considered necessary.  That other set of documentation is requirements.  Have you ever written requirements documents?  Have you ever captured requirements from the customer and put them into UML diagrams, or perhaps plopped them into some templated Word document, which is never updated again, and no one reads, because no one trusts it is correct?  Wouldn’t it be great if we would replace that dead document or set of documents, with a living one?

The good news is we can, and some of us have.  And I fully expect this recommendation will be just as controversial, because <strong>I am suggesting that we don’t have to write low level specifications of the system at all, instead we can write good unit tests. </strong>When we do this, we are taking a dead form of document and bringing it to life.
<h2>Unit tests tell us why and how our code is effective</h2>
If
<pre class="csharpcode">i = 5;  // Widget count defaults to five.</pre>
is replaced with
<pre class="csharpcode">widgetCount = DEFAULT_WIDGET_COUNT;</pre>
<!--.csharpcode, .csharpcode pre { 	font-size: small; 	color: black; 	font-family: consolas, "Courier New", courier, monospace; 	background-color: #ffffff; 	/*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt  { 	background-color: #f4f4f4; 	width: 100%; 	margin: 0em; } .csharpcode .lnum { color: #606060; } -->

then
<blockquote><span style="background-color: #ffffff;">1.1.5 When a new widget is created, the widget count should be increased by one.</span></blockquote>
is replaced with
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">void</span> When_NewWidgetIsCreated_Then_WidgetCountIsIncreasedByOne()
{
     WidgetFactory.Count = 3;
     WidgetFactory.CreateNew();
     assertEquals(4, WidgetFactory.Count);
}</pre>
The unit test is replacing the low level requirement, which is somewhat open to interpretation and untied to the code, with an absolute and completely tied-to-the-code, specific requirement.

The unit test is telling us why our code is built the way it is.  It is telling us what requirement that particular structure of code is trying to address.  <strong>It is telling us what end result that code is trying to accomplish and what the expectations are on the results of a given condition.</strong>

The unit test is telling us how the code is to be used in order to achieve its result.  It is serving as a living reference to the syntax and use of the code we built.  <strong>Instead of providing instructions on how to use our API, we are providing a living example, and proof that it will indeed work.</strong> Examples are often much more effective than instructions anyway.
<h2>What exactly are we replacing?</h2>
At this point we are not trying to replace all the documentation of the system (at this point).

With self-documenting code, we sought to eliminate comments, and replace them with good variable and method names.

With unit tests, we seek to eliminate technical documentation and requirements of the system, that is targeted at a developer or technical audience.

We are NOT trying to eliminate high level specifications of the system, or use cases. <strong>Unit tests DO NOT replace that kind of documentation! </strong>We will talk about replacing that kind of documentation when we talk about automated functional or system tests.

Simply put, any kind of documentation that you would give to a developer so they understand how the system works and how to use the code or APIs, can be easily replaced by writing good unit tests.

Our simple goal is to replace the “dead” documentation (meaning that it does not update automatically with the thing it is documenting), with “living” documentation in the form of unit tests.

One last point.  I want to be clear that I am not saying that having unit tests automatically results in the ability to replace technical documentation.  Just like having long-named methods and variables doesn’t automatically replace the need for comments.  It is a matter of the quality of the unit tests that are written, just as it is a matter of the quality of the self-documenting code.
<h5>As always, you can subscribe to this <a href="http://feeds2.feedburner.com/ElegantCode">RSS feed</a> to follow my posts on elegant code.  Feel free to check out my main personal blog at <a href="http://simpleprogrammer.com">http://simpleprogrammer.com</a>, which has a wider range of posts, updated 2-3 times a week.  Also, you can follow me on twitter <a href="http://twitter.com/jsonmez">here</a>.</h5>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/04/25/if-self-documenting-code-is-the-what-unit-tests-are-the-why/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Behaviors with MSpec</title>
		<link>http://elegantcode.com/2010/02/26/behaviors-with-mspec/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=behaviors-with-mspec</link>
		<comments>http://elegantcode.com/2010/02/26/behaviors-with-mspec/#comments</comments>
		<pubDate>Fri, 26 Feb 2010 23:33:28 +0000</pubDate>
		<dc:creator>Jan Van Ryswyck</dc:creator>
				<category><![CDATA[BDD]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/02/26/behaviors-with-mspec/</guid>
		<description><![CDATA[In my previous posts, I showed the syntax for context/specifications using Machine.Specifications (or MSpec for short) and how to use an auto mocking container in conjunction with this excellent Behavior-Driven Development (BDD) framework. For this post, I want to show you one of the nice features of MSpec called behaviors. Suppose we have to create [...]]]></description>
			<content:encoded><![CDATA[<p>In my previous posts, I showed the <a href="http://elegantcode.com/2010/02/19/getting-started-with-machine-specifications-mspec/">syntax for context/specifications</a> using <a href="http://github.com/machine/machine.specifications">Machine.Specifications</a> (or MSpec for short) and <a href="http://elegantcode.com/2010/02/23/mspec-and-auto-mocking">how to use an auto mocking container</a> in conjunction with this excellent Behavior-Driven Development (BDD) framework. For this post, I want to show you one of the nice features of MSpec called <em>behaviors</em>.</p>  <p>Suppose we have to create some sort of specification that validates the format of an e-mail address. We typically use some regular expression in order to ensure that a specified e-mail address is properly formatted.</p>  <pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">class</span> EmailSpecification
{
    <span class="kwrd">private</span> <span class="kwrd">const</span> String EmailRegexPattern = <span class="str">@&quot;.. SOME_REGEX_PATTERN ...&quot;</span>;

    <span class="kwrd">public</span> Boolean IsSatisfiedBy(String candidate)
    {
        var regex = <span class="kwrd">new</span> Regex(EmailRegexPattern);
        <span class="kwrd">return</span> regex.IsMatch(candidate);
    }
}</pre>
<style type="text/css">

.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>I guess this is pretty common and straightforward. One way to provide some unit tests for this particular piece of code is to check a whole number of e-mail addresses that either pass or fail the specification. The following example shows only a couple of scenarios:</p>

<pre class="csharpcode">[TestFixture]
<span class="kwrd">public</span> <span class="kwrd">class</span> When_validating_an_email
    : ContextSpecification&lt;EmailSpecification&gt;
{
    <span class="kwrd">protected</span> <span class="kwrd">override</span> EmailSpecification Create_subject_under_test()
    {
        <span class="kwrd">return</span> <span class="kwrd">new</span> EmailSpecification();
    }

    [Test]
    <span class="kwrd">public</span> <span class="kwrd">void</span> ShouldBeSatisfied()
    {
        Assert.That(SUT.IsSatisfiedBy(<span class="str">&quot;one2@three.com&quot;</span>));
        Assert.That(SUT.IsSatisfiedBy(<span class="str">&quot;one@two3.com&quot;</span>));
    }

    [Test]
    <span class="kwrd">public</span> <span class="kwrd">void</span> ShouldNotBeSatisfied()
    {
        Assert.That(SUT.IsSatisfiedBy(<span class="str">&quot;one_two.com&quot;</span>), Is.False);
        Assert.That(SUT.IsSatisfiedBy(<span class="str">&quot;one_two@&quot;</span>), Is.False);
    }
}</pre>
<style type="text/css">

.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>A slightly more concise approach for these kind of unit tests can be accomplished by utilizing a feature of any decent unit test framework called <em>row tests. </em>With this approach we can, at the very least, reduce the number of asserts we have to write for each unit test.<em>&#160;</em></p>

<pre class="csharpcode">[TestFixture]
<span class="kwrd">public</span> <span class="kwrd">class</span> When_validating_an_email__approach_2
    : ContextSpecification&lt;EmailSpecification&gt;
{
    <span class="kwrd">protected</span> <span class="kwrd">override</span> EmailSpecification Create_subject_under_test()
    {
        <span class="kwrd">return</span> <span class="kwrd">new</span> EmailSpecification();
    }

    [RowTest]
    [Row(<span class="str">&quot;one2@three.com&quot;</span>)]
    [Row(<span class="str">&quot;one@two3.com&quot;</span>)]
    <span class="kwrd">public</span> <span class="kwrd">void</span> ShouldBeSatisfied(String email)
    {
        Assert.That(SUT.IsSatisfiedBy(email));
    }

    [RowTest]
    [Row(<span class="str">&quot;one_two.com&quot;</span>)]
    [Row(<span class="str">&quot;one_two@&quot;</span>)]
    <span class="kwrd">public</span> <span class="kwrd">void</span> ShouldNotBeSatisfied(String email)
    {
        Assert.That(SUT.IsSatisfiedBy(email), Is.False);
    }
}</pre>
<style type="text/css">

.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>Notice that I explicitly called both of these approaches <em>unit tests</em> as they don’t have much to do with BDD in my opinion. I’m not saying that using regular unit tests is a bad thing, but with&#160; behavior-driven development context is king. So these unit tests are perfect examples of ‘<a href="http://elegantcode.com/2008/12/30/dont-sell-out-on-the-context-dude/">context betrayal</a>’ when following the BDD approach. </p>

<p>Lets see what MSpec can bring to the table for these kind of scenarios:</p>

<pre class="csharpcode">[Subject(<span class="kwrd">typeof</span>(EmailSpecification), <span class="str">&quot;is satisfied&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_validating_an_email_address_with_a_number_in_the_local_part
    : email_specification_specs
{
    Establish context = () =&gt;
        EmailAddress = <span class="str">&quot;one2@three.com&quot;</span>;

    Behaves_like&lt;SatisfiedSpecificationBehavior&gt; a_satisfied_specification;
}

[Subject(<span class="kwrd">typeof</span>(EmailSpecification), <span class="str">&quot;is satisfied&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_validating_an_email_address_with_a_number_in_the_domain_name
    : email_specification_specs
{
    Establish context = () =&gt;
        EmailAddress = <span class="str">&quot;one@two3.com&quot;</span>;

    Behaves_like&lt;SatisfiedSpecificationBehavior&gt; a_satisfied_specification;
}

[Subject(<span class="kwrd">typeof</span>(EmailSpecification), <span class="str">&quot;is satisfied&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_validating_an_email_address_without_an_At_sign
    : email_specification_specs
{
    Establish context = () =&gt;
        EmailAddress = <span class="str">&quot;one_two.com&quot;</span>;

    Behaves_like&lt;UnsatisfiedSpecificationBehavior&gt; an_unsatisfied_specification;
}

[Subject(<span class="kwrd">typeof</span>(EmailSpecification), <span class="str">&quot;is satisfied&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_validating_an_email_address_without_a_domain
    : email_specification_specs
{
    Establish context = () =&gt;
        EmailAddress = <span class="str">&quot;one_two@&quot;</span>;

    Behaves_like&lt;UnsatisfiedSpecificationBehavior&gt; an_unsatisfied_specification;
}</pre>
<style type="text/css">

.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>In order to escape ‘context betrayal’, we’ve split up every context into a separate context/specification. In order to reduce the amount of effort caused by duplicate code, we stripped the context setup to the bare minimum (just a particular e-mail address in this case). The observations are isolated into MSpec behaviors which provides a very readable description of their outcome. Lets take a look at what is needed in order to get these <em>behaviors</em> to work.</p>

<p>But first lets take at look at the abstract base class that we’ve used for the context/specifications we’ve just shown.</p>

<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">abstract</span> <span class="kwrd">class</span> email_specification_specs
{
    Establish context = () =&gt;
    {
        SUT = <span class="kwrd">new</span> EmailSpecification();
    };

    Because of = () =&gt;
        Result = SUT.IsSatisfiedBy(EmailAddress);

    <span class="kwrd">protected</span> <span class="kwrd">static</span> Boolean Result;
    <span class="kwrd">protected</span> <span class="kwrd">static</span> String EmailAddress { get; set; }
    <span class="kwrd">protected</span> <span class="kwrd">static</span> EmailSpecification SUT { get; set; }
}</pre>

<p><style type="text/css">

.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style></p>

<p>&#160;</p>

<p>We abstracted as much as possible into this base class in order to remove duplication in the context/specifications. The creation of the subject-under-test and the calling of its <em>IsSatisfiedBy</em> method, but the important one is the declaration of the <em>Result</em> field. This field contains the outcome of the <em>IsSatisfiedBy</em> method. Finally, lets have a look at the behaviors themselves:</p>

<pre class="csharpcode">[Behaviors]
<span class="kwrd">public</span> <span class="kwrd">class</span> SatisfiedSpecificationBehavior
{
    <span class="kwrd">protected</span> <span class="kwrd">static</span> Boolean Result;
    
    It should_satisfy_the_specification = () =&gt;
        Result.ShouldBeTrue();
}

[Behaviors]
<span class="kwrd">public</span> <span class="kwrd">class</span> UnsatisfiedSpecificationBehavior
{
    <span class="kwrd">protected</span> <span class="kwrd">static</span> Boolean Result;

    It should_not_satisfy_the_specification = () =&gt;
        Result.ShouldBeFalse();
}</pre>
<style type="text/css">

.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>In order to create an MSpec behavior, we just have to create a separate class that we decorate with the <em>Behaviors</em> attribute. Also notice that we have the same declaration of the <em>Result</em> field. MSpec ensures that this field gets initialized with the value of the other <em>Result</em> field that is set in the base class of the context/specifications. Note that you don’t necessarily need to put this field in a base class. You can have that field in every context/specification if you’d like (not sure why) as long as the names match with the fields used in the defined behaviors.</p>

<p>I personally like the way how the MSpec contributors tried to solve testing the same logic with different input patterns and the syntax they provided to back this up.&#160;&#160; </p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/02/26/behaviors-with-mspec/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>MSpec and Auto Mocking</title>
		<link>http://elegantcode.com/2010/02/23/mspec-and-auto-mocking/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=mspec-and-auto-mocking</link>
		<comments>http://elegantcode.com/2010/02/23/mspec-and-auto-mocking/#comments</comments>
		<pubDate>Tue, 23 Feb 2010 20:38:54 +0000</pubDate>
		<dc:creator>Jan Van Ryswyck</dc:creator>
				<category><![CDATA[BDD]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/02/23/mspec-and-auto-mocking/</guid>
		<description><![CDATA[In my previous post, I explained how to get started with Machine.Specifications (or MSpec for short) and showed you how the syntax for context/specifications looks like when using this BDD framework. For this post, I want to show you how to use an auto mocking container (we’ll be using the one provided by StructureMap off [...]]]></description>
			<content:encoded><![CDATA[<p>In my <a href="http://elegantcode.com/2010/02/19/getting-started-with-machine-specifications-mspec/">previous post</a>, I explained how to get started with <a href="http://github.com/machine/machine.specifications">Machine.Specifications</a> (or MSpec for short) and showed you how the syntax for context/specifications looks like when using this BDD framework. For this post, I want to show you how to use an <a href="http://vanryswyckjan.blogspot.com/2008/01/automocking-container.html">auto mocking container</a> (we’ll be using the one provided by StructureMap off course).</p>  <p>We’ll use the same example as the one used in the previous post, but now we’ll deal with the message handler that makes a particular customer preferred.</p> <style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>  <pre class="csharpcode"><span class="rem">//</span>
<span class="rem">// Subject under test</span>
<span class="rem">//</span>
<span class="kwrd">public</span> <span class="kwrd">class</span> MakeCustomerPreferredMessageHandler
{
    <span class="kwrd">private</span> <span class="kwrd">readonly</span> ICustomerRepository&lt;ICanMakeCustomerPreferred&gt; _repository;

    <span class="kwrd">public</span> MakeCustomerPreferredMessageHandler(
        ICustomerRepository&lt;ICanMakeCustomerPreferred&gt; repository)
    {
        _repository = repository;
    }

    <span class="kwrd">public</span> <span class="kwrd">void</span> Handle(MakeCustomerPreferredMessage message)
    {
        var customer = _repository.Get(message.CustomerId);
        <span class="kwrd">if</span>(<span class="kwrd">null</span> == customer)
            <span class="kwrd">throw</span> <span class="kwrd">new</span> InvalidOperationException(
                <span class="str">&quot;No customer for specified identifier&quot;</span>);
        
        customer.MakePreferred();
        _repository.Save(customer);
    }
}</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>The <em>Customer</em> class implements a ‘<a href="http://martinfowler.com/bliki/RoleInterface.html">role interface’</a> called <em>ICanMakeCustomerPreferred</em>. We retrieve a customer from the repository and make it preferred. We throw an exception in case the customer cannot be found in the data store.</p>

<p>Here are the context/specifications for this easy example:</p>

<pre class="csharpcode">[Subject(<span class="str">&quot;Making a customer preferred&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_making_a_customer_preferred
    : context_specification&lt;MakeCustomerPreferredMessageHandler&gt;
{
    Establish context = () =&gt;
    {
        _message = <span class="kwrd">new</span> MakeCustomerPreferredMessage { CustomerId = 6412 };

        Repository.Stub(repository =&gt; repository.Get(_message.CustomerId))
            .Return(Customer);
    };

    Because of = () =&gt; 
        SUT.Handle(_message);
    
    It should_mark_the_customer_as_preferred = () =&gt;
        Customer.AssertWasCalled(customer =&gt; customer.MakePreferred());

    It should_save_the_customer_in_the_repository = () =&gt;
        Repository.AssertWasCalled(repository =&gt; repository.Save(Customer));

    <span class="kwrd">private</span> <span class="kwrd">static</span> ICanMakeCustomerPreferred Customer
    {
        get { <span class="kwrd">return</span> Dependency&lt;ICanMakeCustomerPreferred&gt;(); }
    }

    <span class="kwrd">private</span> <span class="kwrd">static</span> ICustomerRepository&lt;ICanMakeCustomerPreferred&gt; Repository
    {
        get { <span class="kwrd">return</span> Dependency&lt;ICustomerRepository&lt;ICanMakeCustomerPreferred&gt;&gt;(); }
    }

    <span class="kwrd">private</span> <span class="kwrd">static</span> MakeCustomerPreferredMessage _message;
}

[Subject(<span class="str">&quot;Making a customer preferred&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_making_an_unexisting_customer_preferred
    : context_specification&lt;MakeCustomerPreferredMessageHandler&gt;
{
    Establish context = () =&gt;   
    {
        _message = <span class="kwrd">new</span> MakeCustomerPreferredMessage() { CustomerId = 61544 };

        Dependency&lt;ICustomerRepository&lt;ICanMakeCustomerPreferred&gt;&gt;()
            .Stub(repository =&gt; repository.Get(_message.CustomerId))
            .Return(<span class="kwrd">null</span>);
    };

    Because of = () =&gt;
        _resultingException = Catch.Exception(() =&gt; SUT.Handle(_message));

    It should_result_in_an_error = () =&gt;
        _resultingException.ShouldBeOfType&lt;InvalidOperationException&gt;();

    <span class="kwrd">private</span> <span class="kwrd">static</span> MakeCustomerPreferredMessage _message;
    <span class="kwrd">private</span> <span class="kwrd">static</span> Exception _resultingException;
}</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>I want to point out that all fields and properties are made static. This is needed so that the anonymous methods can access them. I’m also using a base class for these specifications which I’ll show next. This base class uses an auto mocking container for providing the requested mocks and stubs through the <em>Dependency</em> and <em>Stub</em> methods. </p>

<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">abstract</span> <span class="kwrd">class</span> context_specification&lt;TSubjectUnderTest&gt;
    <span class="kwrd">where</span> TSubjectUnderTest : <span class="kwrd">class</span>
{
    <span class="kwrd">private</span> <span class="kwrd">static</span> IAutoMockingContainer&lt;TSubjectUnderTest&gt; _autoMockingContainer;
    <span class="kwrd">protected</span> <span class="kwrd">static</span> TSubjectUnderTest SUT { get; set; }

    Establish context = () =&gt;
    {
        _autoMockingContainer = <span class="kwrd">new</span> StructureMapAMC&lt;TSubjectUnderTest&gt;();
        SUT = _autoMockingContainer.Create();     
    };
    
    Cleanup stuff = () =&gt; 
    {
        SUT = <span class="kwrd">null</span>;
        _autoMockingContainer = <span class="kwrd">null</span>;
    };

    <span class="kwrd">protected</span> <span class="kwrd">static</span> TDependency Dependency&lt;TDependency&gt;()
        <span class="kwrd">where</span> TDependency : <span class="kwrd">class</span>
    {
        <span class="kwrd">return</span> _autoMockingContainer.GetMock&lt;TDependency&gt;();
    }

    <span class="kwrd">protected</span> <span class="kwrd">static</span> TStub Stub&lt;TStub&gt;()
        <span class="kwrd">where</span> TStub : <span class="kwrd">class</span>
    {
        <span class="kwrd">return</span> _autoMockingContainer.GetStub&lt;TStub&gt;();
    }
}

<span class="kwrd">public</span> <span class="kwrd">interface</span> IAutoMockingContainer&lt;TSubject&gt;
    <span class="kwrd">where</span> TSubject : <span class="kwrd">class</span>
{
    TSubject Create();
    TMock GetMock&lt;TMock&gt;() <span class="kwrd">where</span> TMock : <span class="kwrd">class</span>;
    TStub GetStub&lt;TStub&gt;() <span class="kwrd">where</span> TStub : <span class="kwrd">class</span>;
}

<span class="kwrd">public</span> <span class="kwrd">class</span> StructureMapAMC&lt;TSubject&gt; 
    : IAutoMockingContainer&lt;TSubject&gt;
    <span class="kwrd">where</span> TSubject : <span class="kwrd">class</span>
{
    <span class="kwrd">private</span> <span class="kwrd">readonly</span> RhinoAutoMocker&lt;TSubject&gt; _rhinoAutoMocker;

    <span class="kwrd">public</span> StructureMapAMC()
    {
        _rhinoAutoMocker = 
            <span class="kwrd">new</span> RhinoAutoMocker&lt;TSubject&gt;(MockMode.AAA);
    }

    <span class="kwrd">public</span> TSubject Create()
    {
        <span class="kwrd">return</span> _rhinoAutoMocker.ClassUnderTest;
    }

    <span class="kwrd">public</span> TMock GetMock&lt;TMock&gt;() 
        <span class="kwrd">where</span> TMock : <span class="kwrd">class</span>
    {
        <span class="kwrd">return</span> GetDependency&lt;TMock&gt;();
    }

    <span class="kwrd">public</span> TStub GetStub&lt;TStub&gt;() 
        <span class="kwrd">where</span> TStub : <span class="kwrd">class</span>
    {
        <span class="kwrd">return</span> GetDependency&lt;TStub&gt;();
    }

    <span class="kwrd">private</span> TDependency GetDependency&lt;TDependency&gt;() 
        <span class="kwrd">where</span> TDependency : <span class="kwrd">class</span>
    {
        <span class="kwrd">return</span> _rhinoAutoMocker.Get&lt;TDependency&gt;();
    }
}</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>Notice that I’m using the <em>Establish</em> and <em>Cleanup</em> delegates in the <em>context_specification</em> base class. This doesn’t prevent that these can be used again in derived context/specifications. MSpec ensures that the anonymous methods are called in the right order. This means that the <em>Establish</em> method of the base class is called before the <em>Establish</em> method of the derived context/specifications.&#160;&#160;&#160;&#160; </p>

<p>Absolutely no rocket science here, but I figured it might come in handy when you need it. For the next post I’ll try to demonstrate how to deal with reusable behaviors.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/02/23/mspec-and-auto-mocking/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Getting Started With Machine.Specifications (MSpec)</title>
		<link>http://elegantcode.com/2010/02/19/getting-started-with-machine-specifications-mspec/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=getting-started-with-machine-specifications-mspec</link>
		<comments>http://elegantcode.com/2010/02/19/getting-started-with-machine-specifications-mspec/#comments</comments>
		<pubDate>Fri, 19 Feb 2010 21:34:17 +0000</pubDate>
		<dc:creator>Jan Van Ryswyck</dc:creator>
				<category><![CDATA[BDD]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/02/19/getting-started-with-machine-specifications-mspec/</guid>
		<description><![CDATA[Its been a while since I evaluated and evolved my approach to BDD. The way I’ve been doing BDD up until now is described in this blog post which goes way back to 2008. Everyone has kind of their own style nowadays. Below you can find the code of two context/specifications for a method named [...]]]></description>
			<content:encoded><![CDATA[<p>Its been a while since I evaluated and evolved my approach to BDD. The way I’ve been doing BDD up until now is described in <a href="http://elegantcode.com/2008/10/25/refining-contextspecification-bdd-using-rhino-mocks-35/">this blog post</a> which goes way back to 2008. Everyone has kind of their own style nowadays. Below you can find the code of two context/specifications for a method named <em>MakePreferred</em> on a <em>Customer </em>class. This simple example clarifies the style that I’ve been following up until now.</p> <style type="text/css">


.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style><style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>  <pre class="csharpcode">[TestFixture]
<span class="kwrd">public</span> <span class="kwrd">class</span> When_making_a_regular_customer_preferred
    : ContextSpecification&lt;Customer&gt;
{
    <span class="kwrd">protected</span> <span class="kwrd">override</span> Customer Create_subject_under_test()
    {
        <span class="kwrd">return</span> <span class="kwrd">new</span> Customer(<span class="kwrd">new</span>[] { _order });
    }

    <span class="kwrd">protected</span> <span class="kwrd">override</span> <span class="kwrd">void</span> Establish_context()
    {
        _order = <span class="kwrd">new</span> Order(<span class="kwrd">new</span>[] { <span class="kwrd">new</span> OrderItem(12), 
                                   <span class="kwrd">new</span> OrderItem(16) });
                                   
        _totalAmountWithoutDiscount = _order.TotalAmount;
    }

    <span class="kwrd">protected</span> <span class="kwrd">override</span> <span class="kwrd">void</span> Because()
    {
        SUT.MakePreferred();
    }

    [Test]
    <span class="kwrd">public</span> <span class="kwrd">void</span> Then_the_customer_should_be_marked_as_preferred()
    {
        SUT.IsPreferred.ShouldBeTrue();
    }

    [Test]
    <span class="kwrd">public</span> <span class="kwrd">void</span> Then_a_ten_percent_discount_should_be_applied_to_all_outstanding_orders()
    {
        _order.TotalAmount.ShouldBeEqualTo(
            _totalAmountWithoutDiscount * 0.9);
    }

    <span class="kwrd">private</span> Order _order;
    <span class="kwrd">private</span> Double _totalAmountWithoutDiscount;
}

[TestFixture]
<span class="kwrd">public</span> <span class="kwrd">class</span> When_making_a_preferred_customer_preferred
    : ContextSpecification&lt;Customer&gt;
{
    <span class="kwrd">protected</span> <span class="kwrd">override</span> Customer Create_subject_under_test()
    {
        var customer = <span class="kwrd">new</span> Customer(<span class="kwrd">new</span>[] { _order });
        customer.MakePreferred();
        <span class="kwrd">return</span> customer;
    }

    <span class="kwrd">protected</span> <span class="kwrd">override</span> <span class="kwrd">void</span> Establish_context()
    {
        _order = <span class="kwrd">new</span> Order(<span class="kwrd">new</span>[] { <span class="kwrd">new</span> OrderItem(12), 
                                   <span class="kwrd">new</span> OrderItem(16) });
        _totalAmountWithoutDiscount = _order.TotalAmount;
    }

    <span class="kwrd">protected</span> <span class="kwrd">override</span> <span class="kwrd">void</span> Because()
    {
        SUT.MakePreferred();
    }

    [Test]
    <span class="kwrd">public</span> <span class="kwrd">void</span> Then_no_additional_discount_should_be_applied_to_the_outstanding_orders()
    {
        _order.TotalAmount.ShouldNotBeEqualTo(
            _totalAmountWithoutDiscount * 0.81);
    }

    <span class="kwrd">private</span> Order _order;
    <span class="kwrd">private</span> Double _totalAmountWithoutDiscount;
}

<span class="rem">//</span>
<span class="rem">// Subject under test</span>
<span class="rem">//</span>
<span class="kwrd">public</span> <span class="kwrd">class</span> Customer
{
    <span class="kwrd">private</span> <span class="kwrd">readonly</span> List&lt;Order&gt; _orders;
    <span class="kwrd">public</span> Boolean IsPreferred { get; <span class="kwrd">private</span> set; }

    <span class="kwrd">public</span> Customer(IEnumerable&lt;Order&gt; orders)
    {
        _orders = <span class="kwrd">new</span> List&lt;Order&gt;(orders);
    }

    <span class="kwrd">public</span> <span class="kwrd">void</span> MakePreferred()
    {
        <span class="kwrd">if</span>(IsPreferred)    
            <span class="kwrd">return</span>;
    
        IsPreferred = <span class="kwrd">true</span>;
        _orders.ForEach(order =&gt; order.ApplyDiscount(10));
    }
}</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>The bottom line of this example is that preferred customers get a 10 percent discount. Customers that are already preferred do not get an additional discount or otherwise we’re out of business ;-). </p>

<p>I’ve been pretty happy with this approach so far, although sometimes there were some quirks associated with this. So it was time for me to look beyond the horizon again, trying to look for ways to improve. </p>

<p><a href="http://github.com/machine/machine.specifications">Machine.Specifications</a> or MSpec for short is something that has been on my ‘cool-things-to-learn-list’ for quite some time now. As you will see later in this post, the syntax is a bit different as one would come to expect from a context/specification framework that targets the C# programming language. Its seems to be heavily inspired by Scott Bellware’s <a href="http://code.google.com/p/specunit-net/">SpecUnit framework</a> and <a href="http://rspec.info/">RSpec</a>.</p>

<p>Lets see how to set things up first. </p>

<p>The most obvious starting point is downloading the bits and bytes. You can grab the <a href="http://github.com/machine/machine.specifications">source code</a> from GitHub and build it or you can wuss out like I did and get the latest build from the <a href="http://teamcity.codebetter.com/login.html">TeamCity.CodeBetter.com</a> builder server (you can log on as a guest and search the artifacts for a latest build).&#160; </p>

<p>When you’re heavily addicted to <a href="http://www.testdriven.net/">TestDriven.NET</a> like I am, then its possible to keep using this wonderful Visual Studio add-in for running MSpec context/specifications. Just create a directory named <em>Machine.Specifications</em> in {$Program_Files}\TestDriven.NET 2.0 and copy the following files:</p>

<ul>
  <li>Machine.Specifications.dll</li>

  <li>Machine.Specifications.TDNetRunner.dll</li>

  <li>InstallTDNetRunner.bat</li>
</ul>

<ul>Run the InstallTDNetRunner.bat file and you’re able to run all MSpec context/specifications using TestDriven.NET.</ul>

<p>I also strongly encourage you to install the plugin for the Resharper test runner (if only to prevent some Resharper warnings later on). First step is to add a directory named <em>Plugins</em> to the <em>Bin</em> directory of Resharper ({$Program_Files}\JetBrains\ReSharper\v4.5\Bin\). Then create a directory named <em>Machine.Specifications</em> in the <em>Plugins</em> directory you just created and copy the following files:</p>

<ul>
  <li>Machine.Specifications.dll</li>

  <li>Machine.Specifications.ReSharperRunner.4.5.dll</li>

  <li>InstallResharperRunner.4.5.bat</li>
</ul>

<p>Run the InstallResharperRunner.4.5.bat file and you’re also able to run MSpec context/specifications using the Resharper test runner.</p>

<p>I’m not going to put this off any longer. Lets look at the code of the context/specifications shown earlier but completely revamped using the MSpec syntax:</p>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<pre class="csharpcode">[Subject(<span class="str">&quot;Making a customer preferred&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_a_regular_customer_is_made_preferred 
{
    Establish context = () =&gt;
    {
        _order = <span class="kwrd">new</span> Order(<span class="kwrd">new</span>[] { <span class="kwrd">new</span> OrderItem(12), 
                                   <span class="kwrd">new</span> OrderItem(16) });
        _totalAmountWithoutDiscount = _order.TotalAmount;

        SUT = <span class="kwrd">new</span> Customer(<span class="kwrd">new</span>[] { _order });
    };

    Because of = () =&gt; 
        SUT.MakePreferred();

    It should_mark_the_customer_as_preferred = () =&gt;
        SUT.IsPreferred.ShouldBeTrue();
        
    It should_apply_a_ten_percent_discount_to_all_outstanding_orders = () =&gt;
        _order.TotalAmount.ShouldEqual(_totalAmountWithoutDiscount * 0.9);      

    <span class="kwrd">private</span> <span class="kwrd">static</span> Customer SUT;
    
    <span class="kwrd">private</span> <span class="kwrd">static</span> Order _order;
    <span class="kwrd">private</span> <span class="kwrd">static</span> Double _totalAmountWithoutDiscount;
}

[Subject(<span class="str">&quot;Making a customer preferred&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_a_preferred_customer_is_made_preferred
{
    Establish context = () =&gt;
    {
        _order = <span class="kwrd">new</span> Order(<span class="kwrd">new</span>[] { <span class="kwrd">new</span> OrderItem(12), 
                                   <span class="kwrd">new</span> OrderItem(16) });
        _totalAmountWithoutDiscount = _order.TotalAmount;

        SUT = <span class="kwrd">new</span> Customer(<span class="kwrd">new</span>[] { _order });
        SUT.MakePreferred();
    };

    Because of = () =&gt;
        SUT.MakePreferred();

    It should_apply_no_additional_discount_to_the_outstanding_orders = () =&gt; 
        _order.TotalAmount.ShouldNotEqual(_totalAmountWithoutDiscount * 0.81);

    <span class="kwrd">private</span> <span class="kwrd">static</span> Customer SUT;

    <span class="kwrd">private</span> <span class="kwrd">static</span> Order _order;
    <span class="kwrd">private</span> <span class="kwrd">static</span> Double _totalAmountWithoutDiscount;
}</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>I warned you about the syntax, didn’t I :-). It only took me a couple of seconds to get used to this syntax but now I’m completely hooked. Instead of using methods and attributes, MSpec utilizes delegates and anonymous methods. But there’s more. </p>

<p>When using <a href="http://www.nunit.com/index.php">NUnit</a> for writing context/ specifications, the <em>Establish_context</em> and <em>Because</em> methods of the example shown earlier is executed before every observation (test). With MSpec, the <em>Establish</em> and <em>Because</em> anonymous methods are executed only once for every context no matter how many observations a particular context class contains. Big difference? Well, at first glance not but on second hand it does make <a href="http://elegantcode.com/2008/12/30/dont-sell-out-on-the-context-dude/">selling out on the context</a> a bit more difficult as it will probably blow up in your face sooner than later. You can force MSpec to execute the <em>Establish</em> and <em>Because</em> anonymous methods before every observation by applying the <em>SetupForEachSpecification</em> attribute to the context class, but I strongly encourage you to stay away from that unless absolutely needed.</p>

<p>Also notice that the fields in the contexts are now all static. This is needed so that the anonymous methods can access those.&#160;&#160;&#160;&#160;&#160; </p>

<p>Running these context/specifications using TestDriven.NET yields the following output in the output window of Visual Studio:</p>

<blockquote>
  <p><font face="Arial">Making a customer preferred, when a regular customer is made preferred
      <br />» should mark the customer as preferred

      <br />» should apply a ten percent discount to all outstanding orders</font></p>

  <p><font face="Arial">Making a customer preferred, when a preferred customer is made preferred
      <br />» should apply no additional discount to the outstanding orders</font></p>
</blockquote>

<p>What’s not to like? Well, the only downside so far is that Resharper was giving me some warnings about classes and fields not being used etc. … . Many of those warnings disappeared by registering the MSpec plugin for the Resharper test runner as I explained earlier.</p>

<p>So far, so good. I’ve got two more posts coming up on MSpec, so stay tuned.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/02/19/getting-started-with-machine-specifications-mspec/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Unity/Moq &#8211; AutoMocker or AutoMockingContainer</title>
		<link>http://elegantcode.com/2010/01/03/unitymoq-automocker-or-automockingcontainer/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=unitymoq-automocker-or-automockingcontainer</link>
		<comments>http://elegantcode.com/2010/01/03/unitymoq-automocker-or-automockingcontainer/#comments</comments>
		<pubDate>Sun, 03 Jan 2010 16:52:33 +0000</pubDate>
		<dc:creator>Jason Jarrett</dc:creator>
				<category><![CDATA[TDD]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Tools and Utilities]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/01/03/unitymoq-automocker-or-automockingcontainer/</guid>
		<description><![CDATA[What is an Auto Mocking Container? This post started to get a little long, so I won’t re-explain the concept. Joshua Flanagan wrote a nice overview at his Los Techies blog: Auto mocking Explained. My post is mainly here to describe the Unity version of an automocking container I threw together. In Jan 2009 I [...]]]></description>
			<content:encoded><![CDATA[<h4>What is an Auto Mocking Container?</h4>  <p>This post started to get a little long, so I won’t re-explain the concept.</p>  <p><a href="http://www.lostechies.com/blogs/joshuaflanagan/default.aspx">Joshua Flanagan</a> wrote a nice overview at his <a href="http://www.lostechies.com/">Los Techies</a> blog: <a href="http://www.lostechies.com/blogs/joshuaflanagan/archive/2009/02/03/auto-mocking-explained.aspx"><strong>Auto mocking Explained</strong></a>.</p>  <p>My post is mainly here to describe the Unity version of an automocking container I threw together.</p>  <h4>In Jan 2009 I blogged about my initial version of the Unity AutoMocker - Why am I blogging about it again?</h4>  <p>I originally wrote the AutoMocker for the Unity container a year ago (Jan 2009, in Silverlight), and finally got around to placing the code up in the <a href="http://code.google.com/p/moq-contrib/">moq-contrib</a> project in June of 2009.</p>  <p>I’m writing another post today in hopes to:</p>  <ol>   <li>Get some feedback on how this little snippet of code should continue. </li>    <li>Give a little more how-to/example code </li>    <li>Describe some updates I made since I originally created it.&#160; </li> </ol>  <h4>Where can I get it?</h4>  <p><strong>This is one part where I’d appreciate some feedback.</strong></p>  <p>I have two slightly different versions out there (currently).</p>  <p>I have one version at the <a href="http://code.google.com/p/elegantcode/source/browse/#svn/trunk/Coders/JasonJarrett/UnityAutoMocker">ElegantCode</a> repository where I was working on it, and the other I threw up at <a href="http://code.google.com/p/moq-contrib/">moq-contrib</a>.</p>  <p>The core of the UnityAutoMockContainer is the same in both places, it’s how the tests are separated out that differ.</p>  <p>In the <a href="http://code.google.com/p/elegantcode/source/browse/#svn/trunk/Coders/JasonJarrett/UnityAutoMocker">ElegantCode repository</a> it’s an all in one self contained single file (that you can copy into your own test project(s)). You can then setup a single test in your own testing framework that runs all internal automocker tests (in case you need to modify it yourself, and don’t want to break any existing functionality). EX: test</p>  <pre class="brush: csharp;">[Test]
public void Should_run_all_UnityAutoMockContainer_internal_tests()
{
    Moq.AutoMocking.SelfTesting.UnityAutoMockContainerFixture
        .RunAllTests(Console.WriteLine);
}</pre>

<p>I kind of like this format as it makes it easy to port between test libraries. Can’t say I like having the tests in the same file as the core, but it certainly is not a large chunk of code (so far) so it’s relatively small to maintain and definitely easier to manage as a single .cs file than another assembly (which would have to be version dependent on both Unity and Moq).</p>

<p>The <a href="http://code.google.com/p/moq-contrib/">moq-contrib</a> is definitely where I think this helper should end up (and it is there). I just happened to break the tests out into the Silverlight test project and the core is alone in a file. </p>

<p>It’s current state isn’t as easy to copy to a test library (Silverlight/Desktop/Unity 1.2/Unity 2.0) as the one at <a href="http://elegantcode.com/">ElegantCode</a>. <strong>What does anyone think?</strong> Should I put them all together in one file?</p>

<p>However it ends up (1. all in one file or two (1 test) (1 core)) it will continue to be maintained on the <a href="http://code.google.com/p/moq-contrib/">moq-contrib</a> project.</p>

<h4>What is the high level API of the container?</h4>

<p>It’s pretty simple, (currently) there are four methods on the container.</p>

<p><strong>Two for registering items with the container</strong>. Say you want to register an already created instance, or say you want to map an interface to a concrete class and _not_ have the container generate mocks automatically for special cases. </p>

<p>And <strong>two for pulling items out of the container</strong>. Whether you want a instance of T or a Mock&lt;T&gt;, it gives you ways to retrieve both.</p>

<blockquote>
  <p><a href="http://elegantcode.com/wp-content/uploads/2010/01/image.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://elegantcode.com/wp-content/uploads/2010/01/image_thumb.png" width="396" height="106" /></a> </p>
</blockquote>

<h4>How can I setup my own registrations with the container? </h4>

<p>Say I don’t want to have the container generate mocks for specific items and I want to supply specific configuration to the UnityContainer.</p>

<blockquote>
  <p>public UnityAutoMockContainer RegisterInstance&lt;TService&gt;(TService instance)</p>

  <p>public UnityAutoMockContainer Register&lt;TService, TImplementation&gt;() 
    <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; where TImplementation : TService</p>
</blockquote>

<p><strong>Note</strong>: both of these registration methods return the container itself so you can fluently stack registration. <strong>EX:</strong></p>

<pre class="brush: csharp;">AutoMockContainer
    .Register&lt;IServiceA, ServiceA&gt;()
    .Register&lt;IServiceB, ServiceB&gt;();</pre>

<p><strong>Let me know</strong>: I haven’t tested or played around with how this automocking container deals with any container specific xml configuration… So although I don’t think you should probably have that in a test assembly (stuff happens). Let me know if there are any issues.</p>

<h4>How do I get items out of the container?</h4>

<p>First is the Resolve&lt;T&gt;(). It will pull an item T out of the container. (Creating it if not already existing)</p>

<blockquote>
  <p>public T Resolve&lt;T&gt;()</p>
</blockquote>

<p>When T is an interface Resolve&lt;T&gt; (unless you setup registration specifically with the container) should return basically “(new Mock&lt;T&gt;()).Object”</p>

<p>When T is a concrete Class, the container should return an instance of T and any of it’s dependencies will be satisfied by mocks. (Note that T will not be any sort of mocked instance of T, unless you used the GetMock&lt;T&gt; as described below first)</p>

<blockquote>
  <p>public Mock&lt;T&gt; GetMock&lt;T&gt;() where T : class</p>
</blockquote>

<p>When T is an interface GetMock&lt;T&gt; should return basically “(new Mock&lt;T&gt;())” </p>

<p>When T is a concrete Class, the container should return a new Mock&lt;T&gt;() and any of it’s dependencies will be satisfied by mocks.</p>

<h4>How do I use the UnityAutoMockContainer?</h4>

<p>It’s pretty basic, you first create an instance of the UnityAutoMockContainer, and from there you can ask it for mocks of an (Interface, Class, or Abstract Class).</p>

<p>If you request an instance of a concrete class, or abstract class, the UnityAutoMockContainer will stuff mocks in for any constructor dependencies of your concrete class (if it can). You can then request from the container those same dependencies one at a time and either apply mocking setups or verifications.</p>

<blockquote>
  <p><strong>NOTE:</strong> Anything the container creates will live as a singleton instance in the container. So any other requests from the container will always return the originally created instance. Therefore, each distinct scenario in a test suite should have their own instances of the container.</p>
</blockquote>

<p>Below his an example of how you can leverage the container in some tests. Given this base fixture class…</p>

<pre class="brush: csharp;">public class FixtureBase
{
    private readonly UnityAutoMockContainer _autoMockContainer = new UnityAutoMockContainer();

    protected UnityAutoMockContainer AutoMockContainer
    {
        get { return _autoMockContainer; }
    }

    [TestFixtureSetUp]
    public void SetupContext_ALL()
    {
        Before_all_tests();
        Because();
    }

    [TestFixtureTearDown]
    public void TearDownContext_ALL()
    {
        After_all_tests();
    }

    protected virtual void Before_all_tests()
    {
    }

    protected virtual void Because()
    {
    }

    protected virtual void After_all_tests()
    {
    }
}</pre>

<p>If I were given the following system to test.</p>

<pre class="brush: csharp;">public interface IServiceA { void RunA(); }
public interface IServiceB { void RunB(); }

public class TestComponent
{
    public TestComponent(IServiceA serviceA, IServiceB serviceB)
    {
        ServiceA = serviceA;
        ServiceB = serviceB;
    }

    public IServiceA ServiceA { get; private set; }
    public IServiceB ServiceB { get; private set; }

    public void RunAll()
    {
        if (!HowDidItGo())
            return;
        ServiceA.RunA();
        ServiceB.RunB();
    }

    public virtual bool HowDidItGo()
    {
        // some really nasty untestable code
        return true;
    }
}</pre>

<p>The below example demonstrates simply verifying some behavior on the mocked dependencies of the system under test.</p>

<pre class="brush: csharp;">[TestFixture]
public class Example__how_to_pull_items_from_the_UnityAutoMockContainer_when_verifying_behavior_after_an_action_was_taken 
    : FixtureBase
{
    private TestComponent _testComponent;

    protected override void Before_all_tests()
    {
        base.Before_all_tests();
        _testComponent = AutoMockContainer.Resolve&lt;TestComponent&gt;();
    }

    protected override void Because()
    {
        _testComponent.RunAll();
    }

    [Test]
    public void Should_run_ServiceA_RunA()
    {
        AutoMockContainer
            .GetMock&lt;IServiceA&gt;()
            .Verify(v =&gt; v.RunA(), Times.Once());
    }

    [Test]
    public void Should_run_ServiceB_RunB()
    {
        AutoMockContainer
            .GetMock&lt;IServiceB&gt;()
            .Verify(v =&gt; v.RunB(), Times.Once());
    }
}</pre>

<p>Next, you may have noticed that the system under test had a complicated internal method (that may not necessarily be testable). You can use the AutoMocker to create the system under test as a Mock itself, so we can override some of the behavior. Here’s how you could quickly do that. </p>

<blockquote>
  <p><strong>Aside</strong>: I’m not saying this is a good practice or aids in good component design, just saying it’s possible</p>
</blockquote>

<pre class="brush: csharp;">[TestFixture]
public class Example__how_to_use_the_UnityAutoMockContainer_to_override_a_method_on_the_SystemUnderTest_to_test_a_certain_behavior
    : FixtureBase
{

    private TestComponent _testComponent;

    protected override void Before_all_tests()
    {
        base.Before_all_tests();
        var mockTestComponent = AutoMockContainer.GetMock&lt;TestComponent&gt;();

        mockTestComponent
            .Setup(s =&gt; s.HowDidItGo())
            .Returns(false);

        _testComponent = mockTestComponent.Object;
    }

    protected override void Because()
    {
        _testComponent.RunAll();
    }

    [Test]
    public void Should_run_ServiceA_RunA()
    {
        AutoMockContainer
            .GetMock&lt;IServiceA&gt;()
            .Verify(v =&gt; v.RunA(), Times.Never());
    }

    [Test]
    public void Should_run_ServiceB_RunB()
    {
        AutoMockContainer
            .GetMock&lt;IServiceB&gt;()
            .Verify(v =&gt; v.RunB(), Times.Never());
    }
}</pre>

<p>&#160;</p>

<p>It’s amazing how much redundant test setup code this little helper has saved me in my tests. I hope others can find some use with this as well.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/01/03/unitymoq-automocker-or-automockingcontainer/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>StatLight &#8211; Goes Open Source</title>
		<link>http://elegantcode.com/2009/12/10/statlight-goes-open-source/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=statlight-goes-open-source</link>
		<comments>http://elegantcode.com/2009/12/10/statlight-goes-open-source/#comments</comments>
		<pubDate>Fri, 11 Dec 2009 03:26:55 +0000</pubDate>
		<dc:creator>Jason Jarrett</dc:creator>
				<category><![CDATA[Esoterica]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[TDD]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Tools and Utilities]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/12/10/statlight-goes-open-source/</guid>
		<description><![CDATA[Although I made a very minor attempt at making StatLight a “for-sale” product, I knew when I started that open-source was most likely going to be my long term path for StatLight. What is it? (Silverlight Testing Automation Tool) StatLight is a tool developed for automating the setup, running, and gathering results of Silverlight unit [...]]]></description>
			<content:encoded><![CDATA[Although I made a very minor attempt at making <a href="http://statlight.net" target="_blank">StatLight</a> a “for-sale” product, I knew when I started that open-source was most likely going to be my long term path for <a href="http://statlight.net" target="_blank">StatLight</a>.
<h5>What is it? (Silverlight Testing Automation Tool)</h5>
StatLight is a tool developed for automating the setup, running, and gathering results of Silverlight unit tests. StatLight helps to speed up the feedback cycles while practicing<a href="http://en.wikipedia.org/wiki/Test-driven_development"> TDD</a>/<a href="http://en.wikipedia.org/wiki/Behavior_Driven_Development">BDD</a>/(insert your test style here) during Silverlight development.
<h5>Where can I get StatLight?</h5>
<a href="http://StatLight.CodePlex.com">http://StatLight.CodePlex.com</a>
<h4>Happy Coding !!!</h4>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/12/10/statlight-goes-open-source/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Wrapping up the StructureMap Automocking Container</title>
		<link>http://elegantcode.com/2009/11/30/wrapping-up-the-structuremap-automocking-container/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=wrapping-up-the-structuremap-automocking-container</link>
		<comments>http://elegantcode.com/2009/11/30/wrapping-up-the-structuremap-automocking-container/#comments</comments>
		<pubDate>Mon, 30 Nov 2009 07:21:43 +0000</pubDate>
		<dc:creator>Richard Cirerol</dc:creator>
				<category><![CDATA[TDD]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Unit Testing]]></category>
		<category><![CDATA[StructureMap; Automocking; MSpec;]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/11/30/wrapping-up-the-structuremap-automocking-container/</guid>
		<description><![CDATA[<p><font color="#804040"><strong>UPDATE</strong>: I apologize…the original wrapper did not allow injected dependencies.&#160; I have fixed this bug and updated the sample.</font></p> I have been using StructureMap.AutoMocking with MSpec (Machine.Specifications) and Rhino.Mocks for a few months now.  Although I am very comfortable with the patterns that emerge from using the frameworks together, introducing StructureMap.Automocking to other developers is sometimes challenging. I decided to wrap the details of the container to make the intention clearer and explanation easier.  I have started using this wrapper in my projects, and have found it makes building up specifications more efficient in my daily coding.]]></description>
			<content:encoded><![CDATA[<span style="color: #804040;"><strong>UPDATE</strong>: I apologize…the original wrapper did not allow injected dependencies.  I have fixed this bug and updated the sample.</span>

I have been using StructureMap.AutoMocking with MSpec (Machine.Specifications) and Rhino.Mocks for a few months now.  Although I am very comfortable with the patterns that emerge from using the frameworks together, introducing StructureMap.Automocking to other developers is sometimes challenging.

When viewing a specification or test set up with the Rhino.Mocks or Moq automocking container, what is being tested is not readily apparent.  Once the concept is explained and demonstrated, these same developers seem to have no issue with maintaining the specifications/tests.

I decided to wrap the details of the container to make the intention clearer and explanation easier.  I have started using this wrapper in my projects, and have found it makes building up specifications more efficient in my daily coding.

Let me know whether this is useful to you, or how it could be made more useful.
<h4>The Examples</h4>
Let’s contrive an example.  We’ll say we have a coffee machine that grinds its own beans before brewing. However, the hopper has to have beans before starting the grind.  Here is the basic specification:
<table border="1" cellspacing="0" cellpadding="2" width="533">
<tbody>
<tr>
<td width="117" valign="top">Action/Behavior</td>
<td width="414" valign="top">Prepare coffee grounds for 12 cups of coffee</td>
</tr>
<tr>
<td rowspan="2" width="117" valign="top">Expectations</td>
<td width="414" valign="top">Should check that hopper has beans (mock returns true)</td>
</tr>
<tr>
<td width="414" valign="top">Because hopper has beans, should ask grinder to grind enough beans for 12 cups of coffee</td>
</tr>
</tbody></table>
We could start without a container, using Rhino.Mocks to build up the CoffeeMachine dependencies manually:
<pre class="brush: csharp;">[Subject(typeof(CoffeeMachine),"using vanilla Rhino.Mocks")]
public class Example01_when_preparing_coffee_grounds
{
    Establish context = () =&gt;
        {
            Grinder = MockRepository.GenerateMock&lt;IGrinder&gt;();
            Hopper = MockRepository.GenerateMock&lt;IHopper&gt;();
            Hopper.Expect(x =&gt; x.HasBeans()).Return(true);
            CoffeeMachine = new CoffeeMachine(Grinder, Hopper);
        };

    Because of = () =&gt; _coffeeMachine.PrepareCoffeeGrounds(12);

    It should_check_if_hopper_has_beans = () =&gt; Hopper.VerifyAllExpectations();
    It should_grind_coffee = () =&gt; Grinder.AssertWasCalled(x =&gt; x.Grind(12));

    static IGrinder Grinder;
    static IHopper Hopper;
    static CoffeeMachine CoffeeMachine;
}</pre>
For those of you not familiar with the MSpec style, please refer to the following posts:
<ul>
	<li><a href="http://blog.wekeroad.com/blog/make-bdd-your-bff-2/" target="_blank">Make BDD Your BFF</a></li>
	<li><a href="http://www.lostechies.com/blogs/seanbiefeld/archive/2009/08/25/step-by-step-to-using-machine-specifications-with-resharper.aspx" target="_blank">Step by Step to Using MSpec (Machine.Specifications) with ReSharper</a></li>
	<li><a href="http://elegantcode.com/2009/07/05/mspec-take-2/" target="_blank">MSpec - Take 2</a></li>
	<li><a href="http://marcinobel.com/index.php/mspec-bdd-installer/" target="_blank">MSpec BDD framework installer</a></li>
	<li><strong>Updated! </strong>From the <a href="http://blog.cwa.me.uk/2009/11/30/the-morning-brew-487/" target="_blank">Morning Brew #487</a>: BDD with MSpec and Rhino Auto Mocks, parts  <a href="http://telldontask.wordpress.com/2009/11/10/bdd-with-mspec-and-rhino-auto-mocks/" target="_blank">1</a>, <a href="http://telldontask.wordpress.com/2009/11/19/bdd-with-mspec-and-rhino-auto-mocks-part-2/" target="_blank">2</a>, and <a href="http://telldontask.wordpress.com/2009/11/29/bdd-with-mspec-and-rhino-auto-mocks-part-3/" target="_blank">3</a>
Here is the same specification using the RhinoAutoMocker&lt;T&gt; class provided by StructureMap.AutoMocking:</li>
</ul>
<pre class="brush: csharp;">[Subject(typeof(CoffeeMachine),"using RhinoAutoMocker&lt;CoffeeMachine&gt;")]
public class Example02_when_preparing_coffee_grounds
{
    Establish context = () =&gt;
        {
            CoffeeMachine = new RhinoAutoMocker&lt;CoffeeMachine&gt;();
            Grinder = CoffeeMachine.Get&lt;IGrinder&gt;();
            Hopper = CoffeeMachine.Get&lt;IHopper&gt;();
            Hopper.Expect(x =&gt; x.HasBeans()).Return(true);
        };

    Because of = () =&gt; v.ClassUnderTest.PrepareCoffeeGrounds(12);

    It should_check_if_hopper_has_beans = () =&gt; Hopper.VerifyAllExpectations();
    It should_grind_coffee = () =&gt; Grinder.AssertWasCalled(x =&gt; x.Grind(12));

    static IGrinder Grinder;
    static IHopper Hopper;
    static RhinoAutoMocker&lt;CoffeeMachine&gt; CoffeeMachine;
}</pre>
Although I think this looks cleaner, the initialization of CoffeeMachine causes some confusion. Unfortunately, a common question would be, “Is RhinoAutoMocker&lt;CoffeeMachine&gt; creating a mocked version of CoffeeMachine?” Well, not exactly.

RhinoAutoMocker is an implementation of the AutoMocker base class which uses StructureMap to fill dependencies.  The RhinoAutoMocker implementation of the container uses Rhino.Mocks to generate all of dependencies of the target class, whereas the MoqAutoMocker implementation uses Moq.  (Optionally, the target class can be partially mocked in order to further isolate behavior.)  We then retrieve the class under test (in this case, CoffeeMachine) and its dependencies (IGrinder and IHopper) from the container for use.

If you do not need to setup any expectations in the specification, there is no need to retrieve the dependency from the container.  However, in this specification, we need both dependencies.

<em>(Incidentally, I do not like the ClassUnderTest name.  I may end up changing this to Instance, ClassInstance, TargetClass, or something similar.  Suggestions?)</em>

By moving the initialization of the RhinoAutoMocker to a base class, some of the chattiness of the context can be hidden.
<ul>
<pre class="brush: csharp;">[Subject(typeof(CoffeeMachine),"using RhinoAutoMocker base")]
public class Example03_when_preparing_coffee_grounds : with_rhinoautomocker
{
    Establish context = () =&gt; Hopper.Expect(x =&gt; x.HasBeans()).Return(true);

    Because of = () =&gt; CoffeeMachine.ClassUnderTest.PrepareCoffeeGrounds(12);

    It should_check_if_hopper_has_beans = () =&gt; Hopper.VerifyAllExpectations();
    It should_grind_coffee = () =&gt; Grinder.AssertWasCalled(x =&gt; x.Grind(12));

}

[Subject("using RhinoAutoMocker&lt;T&gt;")]
public class with_rhinoautomocker
{
    protected static IGrinder Grinder;
    protected static IHopper Hopper;
    protected static RhinoAutoMocker&lt;CoffeeMachine&gt; CoffeeMachine;

    Establish context = () =&gt;
    {
        CoffeeMachine = new RhinoAutoMocker&lt;CoffeeMachine&gt;();
        Grinder = CoffeeMachine.Get&lt;IGrinder&gt;();
        Hopper = CoffeeMachine.Get&lt;IHopper&gt;();
    };
}</pre>
However, we are still initializing and accessing the class in a less than optimal manner.To make the usage of the container a little more seamless, I decided to create a wrapper and factory for the AutoMocker.  Setup of the dependencies and expectations are done through an AutoMocker wrapper object.  The instance of the class under test is accessed through a ClassUnderTest object.
<h4>The Result</h4>
The specification (and base class) now look like this:
<pre class="brush: csharp;">[Subject(typeof(CoffeeMachine),"using coffee machine base")]
public class Example05_when_preparing_coffee_grounds : with_coffee_machine
{
    Establish context = () =&gt; Hopper.Expect(x =&gt; x.HasBeans()).Return(true);

    Because of = () =&gt; ClassUnderTest.PrepareCoffeeGrounds(12);

    It should_check_if_hopper_has_beans = () =&gt; Hopper.VerifyAllExpectations();
    It should_grind_coffee = () =&gt; Grinder.AssertWasCalled(x =&gt; x.Grind(12));
}

[Subject("using SpecificationFor&lt;CoffeeMachine&gt;")]
public class with_coffee_machine : SpecificationFor&lt;CoffeeMachine&gt;
{
    protected static IGrinder Grinder;
    protected static IHopper Hopper;

    public with_coffee_machine
    {
        Grinder = AutoMocker.Get&lt;IGrinder&gt;();
        Hopper = AutoMocker.Get&lt;IHopper&gt;();
    }
}</pre>
As you can see, the base class inherits from SpecificationFor&lt;T&gt;.  The default constructor uses Rhino.Mocks(MockMode.AAA) to generate the dependencies.  It then exposes a AutoMocker object, which is just the wrapper around the AutoMocker base class.  It also exposes a ClassUnderTest object.  If I didn’t need to use the dependencies, I could make the <em>Example05_when_preparing_coffee_grounds</em> class inherit from <em>SpecificationFor&lt;CoffeeMachine&gt; </em>instead of inheriting from the base class<em>.</em>
<h4>The Code</h4>
I have included the code for the wrapper below for your review.  The code and six examples are available on my <a href="http://codeprogression.googlecode.com/svn/trunk/CodeProgression.Framework.Testing" target="_blank">Google code repository</a>. The repository also includes an example using the MoqAutoMocker.  All the examples have the same assertions, but are built up using the different techniques.
<pre class="brush: csharp;">namespace CodeProgression.Framework.Testing
{
    public abstract class SpecificationFor&lt;T&gt; where T: class
    {
        protected static ClassUnderTest&lt;T&gt; Factory;

        // UPDATE 2009-12-21:
        //   Moved initialization here
        protected static T ClassUnderTest {get {return AutoMocker.Instance;} }

        protected SpecificationFor()
        {
            AutoMocker = AutoMockFactory.CreateTarget&lt;T&gt;();

            // UPDATE 2009-12-21:
            //    Initializing here prevented injected dependencies!
            // AutoMocker.PartialMockTheClassUnderTest();
            // ClassUnderTest = AutoMocker.Instance;
        }

        protected SpecificationFor(AutoMockType type)
        {
            AutoMocker = AutoMockFactory.CreateTarget&lt;T&gt;(type);

            // UPDATE 2009-12-21:
            // Initializing here prevented injected dependencies!
            // AutoMocker.PartialMockTheClassUnderTest();
            // ClassUnderTest = AutoMocker.Instance;
        }
    }

    public static class AutoMockFactory
    {
        public static ClassUnderTest&lt;TARGETCLASS&gt; CreateTarget&lt;TARGETCLASS&gt;() where TARGETCLASS : class
        {
            return CreateTarget&lt;TARGETCLASS&gt;(AutoMockType.RhinoMocksAAA);
        }

        public static ClassUnderTest&lt;TARGETCLASS&gt; CreateTarget&lt;TARGETCLASS&gt;(AutoMockType framework) where TARGETCLASS : class
        {
            AutoMocker&lt;TARGETCLASS&gt; mocker;
            ServiceLocator serviceLocator;
            switch (framework)
            {
                case AutoMockType.RhinoMocksAAA:
                    mocker = new RhinoAutoMocker&lt;TARGETCLASS&gt;(MockMode.AAA);
                    serviceLocator = new RhinoMocksAAAServiceLocator();
                    break;
                case AutoMockType.RhinoMocksClassic:
                    mocker = new RhinoAutoMocker&lt;TARGETCLASS&gt;(MockMode.RecordAndReplay);
                    serviceLocator = new RhinoMocksClassicServiceLocator();
                    break;
                case AutoMockType.Moq:
                    mocker = new MoqAutoMocker&lt;TARGETCLASS&gt;();
                    serviceLocator = new MoqServiceLocator();
                    break;
                default:
                    throw new ArgumentOutOfRangeException("framework");
            }
            return new ClassUnderTest&lt;TARGETCLASS&gt;(mocker, serviceLocator);
        }
    }

    public enum AutoMockType
    {
        Moq,
        RhinoMocksAAA,
        RhinoMocksClassic
    }

    public class ClassUnderTest&lt;TARGETCLASS&gt; where TARGETCLASS : class
    {
        readonly IAutoMocker&lt;TARGETCLASS&gt; _mocker;
        readonly ServiceLocator _serviceLocator;

        public ClassUnderTest(IAutoMocker&lt;TARGETCLASS&gt; mocker, ServiceLocator serviceLocator)
        {
            _mocker = mocker;
            _serviceLocator = serviceLocator;
        }

        public AutoMockedContainer Container
        {
            get { return _mocker.Container; }
        }

        public TARGETCLASS Instance
        {
            get { return _mocker.ClassUnderTest; }
        }

        public void MockObjectFactory()
        {
            _mocker.MockObjectFactory();
        }

        public void PartialMockTheClassUnderTest()
        {
            _mocker.PartialMockTheClassUnderTest();
        }

        public T Get&lt;T&gt;() where T : class
        {
            return _mocker.Get&lt;T&gt;();
        }

        public void Inject(Type pluginType, object stub)
        {
            _mocker.Inject(pluginType, stub);
        }

        public void Inject&lt;T&gt;(T target)
        {
            _mocker.Inject(target);
        }

        public T AddAdditionalMockFor&lt;T&gt;() where T : class
        {
            return _mocker.AddAdditionalMockFor&lt;T&gt;();
        }

        public void UseConcreteClassFor&lt;T&gt;()
        {
            _mocker.UseConcreteClassFor&lt;T&gt;();
        }

        public T[] CreateMockArrayFor&lt;T&gt;(int count) where T : class
        {
            return _mocker.CreateMockArrayFor&lt;T&gt;(count);
        }

        public void InjectArray&lt;T&gt;(T[] stubs)
        {
            _mocker.InjectArray(stubs);
        }

        public T Mock&lt;T&gt;() where T : class
        {
            return _serviceLocator.Service&lt;T&gt;();
        }
        public object Mock(Type serviceType)
        {
            return _serviceLocator.Service(serviceType);
        }
        public T PartialMock&lt;T&gt;() where T : class
        {
            return _serviceLocator.PartialMock&lt;T&gt;();
        }
    }
}</pre>
</ul>
<script type="text/javascript">// <![CDATA[
 var cirerolGaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."); document.write(unescape("%3Cscript src='" + cirerolGaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
// ]]&gt;</script>

<script type="text/javascript">// <![CDATA[
 var cirerolPageTracker = _gat._getTracker('UA-8257866-3'); cirerolPageTracker._initData(); cirerolPageTracker._trackPageview();
// ]]&gt;</script>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/11/30/wrapping-up-the-structuremap-automocking-container/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Integration Test Brought to you by Powershell &amp; NUnit &#8211; with a Little Specification Syntax for Flavoring</title>
		<link>http://elegantcode.com/2009/10/25/integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring</link>
		<comments>http://elegantcode.com/2009/10/25/integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring/#comments</comments>
		<pubDate>Mon, 26 Oct 2009 05:00:40 +0000</pubDate>
		<dc:creator>Jason Jarrett</dc:creator>
				<category><![CDATA[Esoterica]]></category>
		<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/10/25/integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring/</guid>
		<description><![CDATA[One of the tools I’ve used the last half of a year and really enjoyed is the C# specification extension methods when writing unit test assertions. If you’re looking for a little more background on the topic, I wrote about Fluent Specification Extensions in a past blog. Recently I wanted to execute a PowerShell script [...]]]></description>
			<content:encoded><![CDATA[One of the tools I’ve used the last half of a year and really enjoyed is the C# specification extension methods when writing unit test assertions. If you’re looking for a little more background on the topic, I wrote about <a href="http://staxmanade.blogspot.com/2009/02/fluent-specification-extensions.html">Fluent Specification Extensions</a> in a past blog.

Recently I wanted to execute a PowerShell script to do some automated <a href="http://en.wikipedia.org/wiki/Functional_testing">functional testing</a>. I wanted to execute an application and apply some assertions on the output of the software(basically running a console app, parse the xml output and assert on values in the output).
<blockquote>FYI: I’m very new to PowerShell, so any suggestions on how I implemented the below are welcome…</blockquote>
I’ve seen a couple examples of writing test assertions in PowerShell out there. One example is <a href="http://www.psunit.org/">PSUnit</a>; however, this seemed a little heavy for my needs and not quite the syntactic sugar I was looking for.

Besides the syntax flavor I was desiring, another thing I wanted to do was leverage the power of NUnit.Framework’s assertion capabilities. I like the error messages generated when strings and other objects fail the assertion.
<h5>Examples of end result ShouldLookLike()…</h5>
$true.ShouldBeTrue()
$false.ShouldBeFalse()
"a".ShouldEqual("a")
"a".ShouldNotEqual("b")
<h5><strong>Step 1</strong>: Figure out how to write a C# style <a href="http://msdn.microsoft.com/en-us/library/bb383977.aspx">extension method</a> in PowerShell.</h5>
<blockquote>I found a great blog post describing how to extend any PowerShell object to add extension methods.

<a href="http://bartdesmet.net/blogs/bart/archive/2007/09/06/extension-methods-in-windows-powershell.aspx">Extension Methods in Windows PowerShell</a></blockquote>
In short, to extend types in PowerShell leveraging the <a href="http://msdn.microsoft.com/en-us/library/ms714419(VS.85).aspx">Extended Type System</a>, you need to define them in an xml file and import the method definitions into the PowerShell runtime instance.

Below is PowerShell XML definition for my NUnit Specification Extensions.
<pre class="brush: xml;">&lt;?xml version="1.0" encoding="utf-16"?&gt;
&lt;Types&gt;
    &lt;Type&gt;
        &lt;Name&gt;System.Object&lt;/Name&gt;
        &lt;Members&gt;
            &lt;ScriptMethod&gt;
                &lt;Name&gt;ShouldBeFalse&lt;/Name&gt;
                &lt;Script&gt;
                    [NUnit.Framework.Assert]::IsFalse($this)
                &lt;/Script&gt;
            &lt;/ScriptMethod&gt;
            &lt;ScriptMethod&gt;
                &lt;Name&gt;ShouldBeTrue&lt;/Name&gt;
                &lt;Script&gt;
                    [NUnit.Framework.Assert]::IsTrue($this)
                &lt;/Script&gt;
            &lt;/ScriptMethod&gt;
            &lt;ScriptMethod&gt;
                &lt;Name&gt;ShouldEqual&lt;/Name&gt;
                &lt;Script&gt;
                    [NUnit.Framework.Assert]::AreEqual($args[0], $this)
                &lt;/Script&gt;
            &lt;/ScriptMethod&gt;
            &lt;ScriptMethod&gt;
                &lt;Name&gt;ShouldNotEqual&lt;/Name&gt;
                &lt;Script&gt;
                    [NUnit.Framework.Assert]::AreNotEqual($args[0], $this)
                &lt;/Script&gt;
            &lt;/ScriptMethod&gt;
        &lt;/Members&gt;
    &lt;/Type&gt;
&lt;/Types&gt;</pre>
<h4></h4>
Take the above XML and save it to a file…
<blockquote>NOTE: the file HAS to be saved with the extension <strong>.ps1xml</strong>

Ex: NunitSpecificationPowerShellExtensions<strong>.ps1xml</strong></blockquote>
<h4></h4>
<h5>Step 2: Load the extended type definition into the PowerShell runtime.</h5>
Once you’ve saved the XML extended types to a file, you need to load it into the PowerShell runtime by executing the command below.
<blockquote>
Update-TypeData -PrependPath NunitSpecificationPowerShellExtensions.ps1xml</blockquote>
Before executing the above statement…Let’s quickly look at a System.String’s members and properties – just to show you what the extension methods look like when applied inside of the runtime.<a href="http://elegantcode.com/wp-content/uploads/2009/10/image3.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" src="http://elegantcode.com/wp-content/uploads/2009/10/image_thumb2.png" border="0" alt="image" width="586" height="479" /></a>

After executing the Update-TypeData command you’ll notice there are a number of “ScriptMethod” MemberTypes added to the object.

<a href="http://elegantcode.com/wp-content/uploads/2009/10/image4.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" src="http://elegantcode.com/wp-content/uploads/2009/10/image_thumb3.png" border="0" alt="image" width="600" height="580" /></a>

Now if you try to execute one of those newly added extension methods, you may get the following error…

PS C:\&gt; $testVar.<strong>ShouldEqual</strong>("hello world")

Exception calling "ShouldEqual" with "1" argument(s): "<strong>Unable to find type [NUnit.Framework.Assert]: make sure that the

assembly containing this type is loaded.</strong>"

At line:1 char:21

+ $testVar.ShouldEqual &lt;&lt;&lt;&lt; ("hello world")

+ CategoryInfo          : NotSpecified: (:) [], MethodInvocationException

+ FullyQualifiedErrorId : ScriptMethodRuntimeException

This is because we need to load the NUnit.Framework assembly into the runtime before we can leverage the extension methods.
<blockquote>[System.Reflection.Assembly]::LoadFrom("C:\Program Files\NUnit 2.5.2\bin\net-2.0\framework\nunit.framework.dll") | Out-Null</blockquote>
Now that the extension methods have been defined and loaded into the runtime, NUnit.Framework is loaded, we can now use the methods on any object that inherits from System.Object (which, as far as I know, is everything in PowerShell).

And now, everything you need in one script (if you have the xml extended type file saved somewhere…)
<pre>#
# Update-TypeData -prependPath C:\Code\NunitSpecificationPowerShellExtensions.ps1xml
#

[System.Reflection.Assembly]::LoadFrom("C:\Program Files\NUnit 2.5.2\bin\net-2.0\framework\nunit.framework.dll") | Out-Null

$true.ShouldBeTrue()

$false.ShouldBeFalse()

"a".ShouldEqual("a")

"a".ShouldNotEqual("b")</pre>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/10/25/integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Visual Studio Team System for Small Teams</title>
		<link>http://elegantcode.com/2010/04/25/if-self-documenting-code-is-the-what-unit-tests-are-the-why/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=if-self-documenting-code-is-the-what-unit-tests-are-the-why</link>
		<comments>http://elegantcode.com/2010/04/25/if-self-documenting-code-is-the-what-unit-tests-are-the-why/#comments</comments>
		<pubDate>Sun, 25 Apr 2010 19:09:04 +0000</pubDate>
		<dc:creator>John Sonmez</dc:creator>
				<category><![CDATA[Agile]]></category>
		<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Craftsmanship]]></category>
		<category><![CDATA[Documentation]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/04/25/if-self-documenting-code-is-the-what-unit-tests-are-the-why/</guid>
		<description><![CDATA[It is not enough to just write code that is clean and self-documenting.  Eliminating comments and replacing them with clear variable and method names, will tell the reader of your code clearly what it is doing, but it will not properly express why it is doing it. If you recall from my original post on [...]]]></description>
			<content:encoded><![CDATA[It is not enough to just write code that is clean and self-documenting.  <a href="http://elegantcode.com/2010/04/18/eliminating-comments-the-road-to-clarity/">Eliminating comments</a> and replacing them with clear variable and method names, will tell the reader of your code clearly what it is doing, but it will not properly express why it is doing it.

If you recall from my <a href="http://elegantcode.com/2010/04/09/what-does-elegant-code-mean-to-me/">original post</a> on Elegant code, I stated that elegant code is:
<blockquote>Something that is simple yet effective, delivered with grace.</blockquote>
By writing self-documenting code we are hopefully able to achieve some of the aspects of simplicity and grace, but it tells us nothing about the effectiveness of the code.
<h2>Bringing the dead to life</h2>
<a href="http://elegantcode.com/wp-content/uploads/2010/04/zombies.jpg"><img style="border-right-width: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto" title="zombies" src="http://elegantcode.com/wp-content/uploads/2010/04/zombies_thumb.jpg" border="0" alt="zombies" width="441" height="295" /></a>

Throwing out comments is a debatable topic.  <a href="http://www.reddit.com/r/programming/comments/bsutx/">It raises quite a bit of controversy</a>, as you can see from some of the comments on my post about the subject.  The reason, perhaps, that so many people are so staunchly opposed to the idea, is because they are worried, and rightly so, that throwing out comments will reduce the documentation of what the code is doing.

Think about that for a second.  Is documentation of what the code is doing important?  It better be.  What we are trying to accomplish by writing self-documenting code instead of comments, is to take the vessel, which is the code itself, and make that same vessel be the documentation of what the code does.  It is by doing this that we creating a living representation of the functionality of the code.  Comments are akin to a dead representation of the functionality of the code because they do not change automatically with the code.

I diverge to talk about comments so that I can draw a parallel to another form of documentation which is valuable and should be considered necessary.  That other set of documentation is requirements.  Have you ever written requirements documents?  Have you ever captured requirements from the customer and put them into UML diagrams, or perhaps plopped them into some templated Word document, which is never updated again, and no one reads, because no one trusts it is correct?  Wouldn’t it be great if we would replace that dead document or set of documents, with a living one?

The good news is we can, and some of us have.  And I fully expect this recommendation will be just as controversial, because <strong>I am suggesting that we don’t have to write low level specifications of the system at all, instead we can write good unit tests. </strong>When we do this, we are taking a dead form of document and bringing it to life.
<h2>Unit tests tell us why and how our code is effective</h2>
If
<pre class="csharpcode">i = 5;  // Widget count defaults to five.</pre>
is replaced with
<pre class="csharpcode">widgetCount = DEFAULT_WIDGET_COUNT;</pre>
<!--.csharpcode, .csharpcode pre { 	font-size: small; 	color: black; 	font-family: consolas, "Courier New", courier, monospace; 	background-color: #ffffff; 	/*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt  { 	background-color: #f4f4f4; 	width: 100%; 	margin: 0em; } .csharpcode .lnum { color: #606060; } -->

then
<blockquote><span style="background-color: #ffffff;">1.1.5 When a new widget is created, the widget count should be increased by one.</span></blockquote>
is replaced with
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">void</span> When_NewWidgetIsCreated_Then_WidgetCountIsIncreasedByOne()
{
     WidgetFactory.Count = 3;
     WidgetFactory.CreateNew();
     assertEquals(4, WidgetFactory.Count);
}</pre>
The unit test is replacing the low level requirement, which is somewhat open to interpretation and untied to the code, with an absolute and completely tied-to-the-code, specific requirement.

The unit test is telling us why our code is built the way it is.  It is telling us what requirement that particular structure of code is trying to address.  <strong>It is telling us what end result that code is trying to accomplish and what the expectations are on the results of a given condition.</strong>

The unit test is telling us how the code is to be used in order to achieve its result.  It is serving as a living reference to the syntax and use of the code we built.  <strong>Instead of providing instructions on how to use our API, we are providing a living example, and proof that it will indeed work.</strong> Examples are often much more effective than instructions anyway.
<h2>What exactly are we replacing?</h2>
At this point we are not trying to replace all the documentation of the system (at this point).

With self-documenting code, we sought to eliminate comments, and replace them with good variable and method names.

With unit tests, we seek to eliminate technical documentation and requirements of the system, that is targeted at a developer or technical audience.

We are NOT trying to eliminate high level specifications of the system, or use cases. <strong>Unit tests DO NOT replace that kind of documentation! </strong>We will talk about replacing that kind of documentation when we talk about automated functional or system tests.

Simply put, any kind of documentation that you would give to a developer so they understand how the system works and how to use the code or APIs, can be easily replaced by writing good unit tests.

Our simple goal is to replace the “dead” documentation (meaning that it does not update automatically with the thing it is documenting), with “living” documentation in the form of unit tests.

One last point.  I want to be clear that I am not saying that having unit tests automatically results in the ability to replace technical documentation.  Just like having long-named methods and variables doesn’t automatically replace the need for comments.  It is a matter of the quality of the unit tests that are written, just as it is a matter of the quality of the self-documenting code.
<h5>As always, you can subscribe to this <a href="http://feeds2.feedburner.com/ElegantCode">RSS feed</a> to follow my posts on elegant code.  Feel free to check out my main personal blog at <a href="http://simpleprogrammer.com">http://simpleprogrammer.com</a>, which has a wider range of posts, updated 2-3 times a week.  Also, you can follow me on twitter <a href="http://twitter.com/jsonmez">here</a>.</h5>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/04/25/if-self-documenting-code-is-the-what-unit-tests-are-the-why/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Elegant Code &#187; Unit Testing</title>
	<atom:link href="http://elegantcode.com/category/unit-testing/feed/" rel="self" type="application/rss+xml" />
	<link>http://elegantcode.com</link>
	<description></description>
	<lastBuildDate>Tue, 15 May 2012 10:00:00 +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>AutoTest.NET</title>
		<link>http://elegantcode.com/2010/11/30/autotest-net/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=autotest-net</link>
		<comments>http://elegantcode.com/2010/11/30/autotest-net/#comments</comments>
		<pubDate>Tue, 30 Nov 2010 11:00:00 +0000</pubDate>
		<dc:creator>Jan Van Ryswyck</dc:creator>
				<category><![CDATA[TDD]]></category>
		<category><![CDATA[Tools and Utilities]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/11/30/autotest-net/</guid>
		<description><![CDATA[I just want to quickly point out a tool that I’ve been playing with for a couple of days now, named AutoTest.NET. Its an open-source tool that originates from a popular tool in the Ruby community called ZenTest, which basically runs all your valuable unit tests when you save your source files or when you [...]]]></description>
			<content:encoded><![CDATA[<p>I just want to quickly point out a tool that I’ve been playing with for a couple of days now, named <a href="https://github.com/acken/AutoTest.Net" target="_blank">AutoTest.NET</a>. Its an open-source tool that originates from a popular tool in the Ruby community called <a href="http://www.zenspider.com/ZSS/Products/ZenTest/" target="_blank">ZenTest</a>, which basically runs all your valuable unit tests when you save your source files or when you build your code. It enables you to get feedback about your changes as soon as possible.</p>  <p>The project started out a couple of years ago on <a href="http://code.google.com/p/autotestnet/" target="_blank">Google code</a> and was first initiated by <a href="http://averyblog.com/" target="_blank">James Avery</a>. Contribution stopped at some point until recently where <a href="http://ackenpacken.blogspot.com/" target="_blank">Svein Arne Ackenhausen</a> forked the source code and <a href="https://github.com/acken/AutoTest.Net" target="_blank">put it on GitHub</a>. Now it runs both for .NET as well as Mono, with NUnit, MSTest and xUnit as the currently supported unit test frameworks. </p>  <p>Here’s a screenshot from the feedback window when all tests pass:</p>  <p><a href="http://elegantcode.com/wp-content/uploads/2010/11/Success.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="Success" border="0" alt="Success" src="http://elegantcode.com/wp-content/uploads/2010/11/Success_thumb.png" width="540" height="189" /></a> </p>  <p>And here you can see the same window after I broke one of my unit tests:</p>  <p><a href="http://elegantcode.com/wp-content/uploads/2010/11/Failure.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="Failure" border="0" alt="Failure" src="http://elegantcode.com/wp-content/uploads/2010/11/Failure_thumb.png" width="538" height="319" /></a> </p>  <p>Here you can see which particular unit test has been broken and by clicking the specified link you end up at the right source file in Visual Studio. </p>  <p>I encourage you to pick up this small tool and learn how it can facilitate your TDD flow. Take a look at <a href="https://github.com/acken/AutoTest.Net/wiki/Get-started!" target="_blank">this page</a> in order to get up-and-running in no time. Also don’t forget to provide the owner(s) of this project with some feedback that you might have. Svein has been very helpful over the last week answering all my stupid questions and remarks (and the Nobel price for this year’s most patient person goes to … ;-) ). </p>  <p>I would definitely like to see this tool becoming more popular, so go check it out.&#160;&#160; </p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/11/30/autotest-net/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>If Self-Documenting Code is the What, Unit Tests are the Why</title>
		<link>http://elegantcode.com/2010/04/25/if-self-documenting-code-is-the-what-unit-tests-are-the-why/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=if-self-documenting-code-is-the-what-unit-tests-are-the-why</link>
		<comments>http://elegantcode.com/2010/04/25/if-self-documenting-code-is-the-what-unit-tests-are-the-why/#comments</comments>
		<pubDate>Sun, 25 Apr 2010 19:09:04 +0000</pubDate>
		<dc:creator>John Sonmez</dc:creator>
				<category><![CDATA[Agile]]></category>
		<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Craftsmanship]]></category>
		<category><![CDATA[Documentation]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/04/25/if-self-documenting-code-is-the-what-unit-tests-are-the-why/</guid>
		<description><![CDATA[It is not enough to just write code that is clean and self-documenting.  Eliminating comments and replacing them with clear variable and method names, will tell the reader of your code clearly what it is doing, but it will not properly express why it is doing it. If you recall from my original post on [...]]]></description>
			<content:encoded><![CDATA[It is not enough to just write code that is clean and self-documenting.  <a href="http://elegantcode.com/2010/04/18/eliminating-comments-the-road-to-clarity/">Eliminating comments</a> and replacing them with clear variable and method names, will tell the reader of your code clearly what it is doing, but it will not properly express why it is doing it.

If you recall from my <a href="http://elegantcode.com/2010/04/09/what-does-elegant-code-mean-to-me/">original post</a> on Elegant code, I stated that elegant code is:
<blockquote>Something that is simple yet effective, delivered with grace.</blockquote>
By writing self-documenting code we are hopefully able to achieve some of the aspects of simplicity and grace, but it tells us nothing about the effectiveness of the code.
<h2>Bringing the dead to life</h2>
<a href="http://elegantcode.com/wp-content/uploads/2010/04/zombies.jpg"><img style="border-right-width: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto" title="zombies" src="http://elegantcode.com/wp-content/uploads/2010/04/zombies_thumb.jpg" border="0" alt="zombies" width="441" height="295" /></a>

Throwing out comments is a debatable topic.  <a href="http://www.reddit.com/r/programming/comments/bsutx/">It raises quite a bit of controversy</a>, as you can see from some of the comments on my post about the subject.  The reason, perhaps, that so many people are so staunchly opposed to the idea, is because they are worried, and rightly so, that throwing out comments will reduce the documentation of what the code is doing.

Think about that for a second.  Is documentation of what the code is doing important?  It better be.  What we are trying to accomplish by writing self-documenting code instead of comments, is to take the vessel, which is the code itself, and make that same vessel be the documentation of what the code does.  It is by doing this that we creating a living representation of the functionality of the code.  Comments are akin to a dead representation of the functionality of the code because they do not change automatically with the code.

I diverge to talk about comments so that I can draw a parallel to another form of documentation which is valuable and should be considered necessary.  That other set of documentation is requirements.  Have you ever written requirements documents?  Have you ever captured requirements from the customer and put them into UML diagrams, or perhaps plopped them into some templated Word document, which is never updated again, and no one reads, because no one trusts it is correct?  Wouldn’t it be great if we would replace that dead document or set of documents, with a living one?

The good news is we can, and some of us have.  And I fully expect this recommendation will be just as controversial, because <strong>I am suggesting that we don’t have to write low level specifications of the system at all, instead we can write good unit tests. </strong>When we do this, we are taking a dead form of document and bringing it to life.
<h2>Unit tests tell us why and how our code is effective</h2>
If
<pre class="csharpcode">i = 5;  // Widget count defaults to five.</pre>
is replaced with
<pre class="csharpcode">widgetCount = DEFAULT_WIDGET_COUNT;</pre>
<!--.csharpcode, .csharpcode pre { 	font-size: small; 	color: black; 	font-family: consolas, "Courier New", courier, monospace; 	background-color: #ffffff; 	/*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt  { 	background-color: #f4f4f4; 	width: 100%; 	margin: 0em; } .csharpcode .lnum { color: #606060; } -->

then
<blockquote><span style="background-color: #ffffff;">1.1.5 When a new widget is created, the widget count should be increased by one.</span></blockquote>
is replaced with
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">void</span> When_NewWidgetIsCreated_Then_WidgetCountIsIncreasedByOne()
{
     WidgetFactory.Count = 3;
     WidgetFactory.CreateNew();
     assertEquals(4, WidgetFactory.Count);
}</pre>
The unit test is replacing the low level requirement, which is somewhat open to interpretation and untied to the code, with an absolute and completely tied-to-the-code, specific requirement.

The unit test is telling us why our code is built the way it is.  It is telling us what requirement that particular structure of code is trying to address.  <strong>It is telling us what end result that code is trying to accomplish and what the expectations are on the results of a given condition.</strong>

The unit test is telling us how the code is to be used in order to achieve its result.  It is serving as a living reference to the syntax and use of the code we built.  <strong>Instead of providing instructions on how to use our API, we are providing a living example, and proof that it will indeed work.</strong> Examples are often much more effective than instructions anyway.
<h2>What exactly are we replacing?</h2>
At this point we are not trying to replace all the documentation of the system (at this point).

With self-documenting code, we sought to eliminate comments, and replace them with good variable and method names.

With unit tests, we seek to eliminate technical documentation and requirements of the system, that is targeted at a developer or technical audience.

We are NOT trying to eliminate high level specifications of the system, or use cases. <strong>Unit tests DO NOT replace that kind of documentation! </strong>We will talk about replacing that kind of documentation when we talk about automated functional or system tests.

Simply put, any kind of documentation that you would give to a developer so they understand how the system works and how to use the code or APIs, can be easily replaced by writing good unit tests.

Our simple goal is to replace the “dead” documentation (meaning that it does not update automatically with the thing it is documenting), with “living” documentation in the form of unit tests.

One last point.  I want to be clear that I am not saying that having unit tests automatically results in the ability to replace technical documentation.  Just like having long-named methods and variables doesn’t automatically replace the need for comments.  It is a matter of the quality of the unit tests that are written, just as it is a matter of the quality of the self-documenting code.
<h5>As always, you can subscribe to this <a href="http://feeds2.feedburner.com/ElegantCode">RSS feed</a> to follow my posts on elegant code.  Feel free to check out my main personal blog at <a href="http://simpleprogrammer.com">http://simpleprogrammer.com</a>, which has a wider range of posts, updated 2-3 times a week.  Also, you can follow me on twitter <a href="http://twitter.com/jsonmez">here</a>.</h5>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/04/25/if-self-documenting-code-is-the-what-unit-tests-are-the-why/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Behaviors with MSpec</title>
		<link>http://elegantcode.com/2010/02/26/behaviors-with-mspec/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=behaviors-with-mspec</link>
		<comments>http://elegantcode.com/2010/02/26/behaviors-with-mspec/#comments</comments>
		<pubDate>Fri, 26 Feb 2010 23:33:28 +0000</pubDate>
		<dc:creator>Jan Van Ryswyck</dc:creator>
				<category><![CDATA[BDD]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/02/26/behaviors-with-mspec/</guid>
		<description><![CDATA[In my previous posts, I showed the syntax for context/specifications using Machine.Specifications (or MSpec for short) and how to use an auto mocking container in conjunction with this excellent Behavior-Driven Development (BDD) framework. For this post, I want to show you one of the nice features of MSpec called behaviors. Suppose we have to create [...]]]></description>
			<content:encoded><![CDATA[<p>In my previous posts, I showed the <a href="http://elegantcode.com/2010/02/19/getting-started-with-machine-specifications-mspec/">syntax for context/specifications</a> using <a href="http://github.com/machine/machine.specifications">Machine.Specifications</a> (or MSpec for short) and <a href="http://elegantcode.com/2010/02/23/mspec-and-auto-mocking">how to use an auto mocking container</a> in conjunction with this excellent Behavior-Driven Development (BDD) framework. For this post, I want to show you one of the nice features of MSpec called <em>behaviors</em>.</p>  <p>Suppose we have to create some sort of specification that validates the format of an e-mail address. We typically use some regular expression in order to ensure that a specified e-mail address is properly formatted.</p>  <pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">class</span> EmailSpecification
{
    <span class="kwrd">private</span> <span class="kwrd">const</span> String EmailRegexPattern = <span class="str">@&quot;.. SOME_REGEX_PATTERN ...&quot;</span>;

    <span class="kwrd">public</span> Boolean IsSatisfiedBy(String candidate)
    {
        var regex = <span class="kwrd">new</span> Regex(EmailRegexPattern);
        <span class="kwrd">return</span> regex.IsMatch(candidate);
    }
}</pre>
<style type="text/css">

.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>I guess this is pretty common and straightforward. One way to provide some unit tests for this particular piece of code is to check a whole number of e-mail addresses that either pass or fail the specification. The following example shows only a couple of scenarios:</p>

<pre class="csharpcode">[TestFixture]
<span class="kwrd">public</span> <span class="kwrd">class</span> When_validating_an_email
    : ContextSpecification&lt;EmailSpecification&gt;
{
    <span class="kwrd">protected</span> <span class="kwrd">override</span> EmailSpecification Create_subject_under_test()
    {
        <span class="kwrd">return</span> <span class="kwrd">new</span> EmailSpecification();
    }

    [Test]
    <span class="kwrd">public</span> <span class="kwrd">void</span> ShouldBeSatisfied()
    {
        Assert.That(SUT.IsSatisfiedBy(<span class="str">&quot;one2@three.com&quot;</span>));
        Assert.That(SUT.IsSatisfiedBy(<span class="str">&quot;one@two3.com&quot;</span>));
    }

    [Test]
    <span class="kwrd">public</span> <span class="kwrd">void</span> ShouldNotBeSatisfied()
    {
        Assert.That(SUT.IsSatisfiedBy(<span class="str">&quot;one_two.com&quot;</span>), Is.False);
        Assert.That(SUT.IsSatisfiedBy(<span class="str">&quot;one_two@&quot;</span>), Is.False);
    }
}</pre>
<style type="text/css">

.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>A slightly more concise approach for these kind of unit tests can be accomplished by utilizing a feature of any decent unit test framework called <em>row tests. </em>With this approach we can, at the very least, reduce the number of asserts we have to write for each unit test.<em>&#160;</em></p>

<pre class="csharpcode">[TestFixture]
<span class="kwrd">public</span> <span class="kwrd">class</span> When_validating_an_email__approach_2
    : ContextSpecification&lt;EmailSpecification&gt;
{
    <span class="kwrd">protected</span> <span class="kwrd">override</span> EmailSpecification Create_subject_under_test()
    {
        <span class="kwrd">return</span> <span class="kwrd">new</span> EmailSpecification();
    }

    [RowTest]
    [Row(<span class="str">&quot;one2@three.com&quot;</span>)]
    [Row(<span class="str">&quot;one@two3.com&quot;</span>)]
    <span class="kwrd">public</span> <span class="kwrd">void</span> ShouldBeSatisfied(String email)
    {
        Assert.That(SUT.IsSatisfiedBy(email));
    }

    [RowTest]
    [Row(<span class="str">&quot;one_two.com&quot;</span>)]
    [Row(<span class="str">&quot;one_two@&quot;</span>)]
    <span class="kwrd">public</span> <span class="kwrd">void</span> ShouldNotBeSatisfied(String email)
    {
        Assert.That(SUT.IsSatisfiedBy(email), Is.False);
    }
}</pre>
<style type="text/css">

.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>Notice that I explicitly called both of these approaches <em>unit tests</em> as they don’t have much to do with BDD in my opinion. I’m not saying that using regular unit tests is a bad thing, but with&#160; behavior-driven development context is king. So these unit tests are perfect examples of ‘<a href="http://elegantcode.com/2008/12/30/dont-sell-out-on-the-context-dude/">context betrayal</a>’ when following the BDD approach. </p>

<p>Lets see what MSpec can bring to the table for these kind of scenarios:</p>

<pre class="csharpcode">[Subject(<span class="kwrd">typeof</span>(EmailSpecification), <span class="str">&quot;is satisfied&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_validating_an_email_address_with_a_number_in_the_local_part
    : email_specification_specs
{
    Establish context = () =&gt;
        EmailAddress = <span class="str">&quot;one2@three.com&quot;</span>;

    Behaves_like&lt;SatisfiedSpecificationBehavior&gt; a_satisfied_specification;
}

[Subject(<span class="kwrd">typeof</span>(EmailSpecification), <span class="str">&quot;is satisfied&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_validating_an_email_address_with_a_number_in_the_domain_name
    : email_specification_specs
{
    Establish context = () =&gt;
        EmailAddress = <span class="str">&quot;one@two3.com&quot;</span>;

    Behaves_like&lt;SatisfiedSpecificationBehavior&gt; a_satisfied_specification;
}

[Subject(<span class="kwrd">typeof</span>(EmailSpecification), <span class="str">&quot;is satisfied&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_validating_an_email_address_without_an_At_sign
    : email_specification_specs
{
    Establish context = () =&gt;
        EmailAddress = <span class="str">&quot;one_two.com&quot;</span>;

    Behaves_like&lt;UnsatisfiedSpecificationBehavior&gt; an_unsatisfied_specification;
}

[Subject(<span class="kwrd">typeof</span>(EmailSpecification), <span class="str">&quot;is satisfied&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_validating_an_email_address_without_a_domain
    : email_specification_specs
{
    Establish context = () =&gt;
        EmailAddress = <span class="str">&quot;one_two@&quot;</span>;

    Behaves_like&lt;UnsatisfiedSpecificationBehavior&gt; an_unsatisfied_specification;
}</pre>
<style type="text/css">

.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>In order to escape ‘context betrayal’, we’ve split up every context into a separate context/specification. In order to reduce the amount of effort caused by duplicate code, we stripped the context setup to the bare minimum (just a particular e-mail address in this case). The observations are isolated into MSpec behaviors which provides a very readable description of their outcome. Lets take a look at what is needed in order to get these <em>behaviors</em> to work.</p>

<p>But first lets take at look at the abstract base class that we’ve used for the context/specifications we’ve just shown.</p>

<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">abstract</span> <span class="kwrd">class</span> email_specification_specs
{
    Establish context = () =&gt;
    {
        SUT = <span class="kwrd">new</span> EmailSpecification();
    };

    Because of = () =&gt;
        Result = SUT.IsSatisfiedBy(EmailAddress);

    <span class="kwrd">protected</span> <span class="kwrd">static</span> Boolean Result;
    <span class="kwrd">protected</span> <span class="kwrd">static</span> String EmailAddress { get; set; }
    <span class="kwrd">protected</span> <span class="kwrd">static</span> EmailSpecification SUT { get; set; }
}</pre>

<p><style type="text/css">

.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style></p>

<p>&#160;</p>

<p>We abstracted as much as possible into this base class in order to remove duplication in the context/specifications. The creation of the subject-under-test and the calling of its <em>IsSatisfiedBy</em> method, but the important one is the declaration of the <em>Result</em> field. This field contains the outcome of the <em>IsSatisfiedBy</em> method. Finally, lets have a look at the behaviors themselves:</p>

<pre class="csharpcode">[Behaviors]
<span class="kwrd">public</span> <span class="kwrd">class</span> SatisfiedSpecificationBehavior
{
    <span class="kwrd">protected</span> <span class="kwrd">static</span> Boolean Result;
    
    It should_satisfy_the_specification = () =&gt;
        Result.ShouldBeTrue();
}

[Behaviors]
<span class="kwrd">public</span> <span class="kwrd">class</span> UnsatisfiedSpecificationBehavior
{
    <span class="kwrd">protected</span> <span class="kwrd">static</span> Boolean Result;

    It should_not_satisfy_the_specification = () =&gt;
        Result.ShouldBeFalse();
}</pre>
<style type="text/css">

.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>In order to create an MSpec behavior, we just have to create a separate class that we decorate with the <em>Behaviors</em> attribute. Also notice that we have the same declaration of the <em>Result</em> field. MSpec ensures that this field gets initialized with the value of the other <em>Result</em> field that is set in the base class of the context/specifications. Note that you don’t necessarily need to put this field in a base class. You can have that field in every context/specification if you’d like (not sure why) as long as the names match with the fields used in the defined behaviors.</p>

<p>I personally like the way how the MSpec contributors tried to solve testing the same logic with different input patterns and the syntax they provided to back this up.&#160;&#160; </p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/02/26/behaviors-with-mspec/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>MSpec and Auto Mocking</title>
		<link>http://elegantcode.com/2010/02/23/mspec-and-auto-mocking/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=mspec-and-auto-mocking</link>
		<comments>http://elegantcode.com/2010/02/23/mspec-and-auto-mocking/#comments</comments>
		<pubDate>Tue, 23 Feb 2010 20:38:54 +0000</pubDate>
		<dc:creator>Jan Van Ryswyck</dc:creator>
				<category><![CDATA[BDD]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/02/23/mspec-and-auto-mocking/</guid>
		<description><![CDATA[In my previous post, I explained how to get started with Machine.Specifications (or MSpec for short) and showed you how the syntax for context/specifications looks like when using this BDD framework. For this post, I want to show you how to use an auto mocking container (we’ll be using the one provided by StructureMap off [...]]]></description>
			<content:encoded><![CDATA[<p>In my <a href="http://elegantcode.com/2010/02/19/getting-started-with-machine-specifications-mspec/">previous post</a>, I explained how to get started with <a href="http://github.com/machine/machine.specifications">Machine.Specifications</a> (or MSpec for short) and showed you how the syntax for context/specifications looks like when using this BDD framework. For this post, I want to show you how to use an <a href="http://vanryswyckjan.blogspot.com/2008/01/automocking-container.html">auto mocking container</a> (we’ll be using the one provided by StructureMap off course).</p>  <p>We’ll use the same example as the one used in the previous post, but now we’ll deal with the message handler that makes a particular customer preferred.</p> <style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>  <pre class="csharpcode"><span class="rem">//</span>
<span class="rem">// Subject under test</span>
<span class="rem">//</span>
<span class="kwrd">public</span> <span class="kwrd">class</span> MakeCustomerPreferredMessageHandler
{
    <span class="kwrd">private</span> <span class="kwrd">readonly</span> ICustomerRepository&lt;ICanMakeCustomerPreferred&gt; _repository;

    <span class="kwrd">public</span> MakeCustomerPreferredMessageHandler(
        ICustomerRepository&lt;ICanMakeCustomerPreferred&gt; repository)
    {
        _repository = repository;
    }

    <span class="kwrd">public</span> <span class="kwrd">void</span> Handle(MakeCustomerPreferredMessage message)
    {
        var customer = _repository.Get(message.CustomerId);
        <span class="kwrd">if</span>(<span class="kwrd">null</span> == customer)
            <span class="kwrd">throw</span> <span class="kwrd">new</span> InvalidOperationException(
                <span class="str">&quot;No customer for specified identifier&quot;</span>);
        
        customer.MakePreferred();
        _repository.Save(customer);
    }
}</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>The <em>Customer</em> class implements a ‘<a href="http://martinfowler.com/bliki/RoleInterface.html">role interface’</a> called <em>ICanMakeCustomerPreferred</em>. We retrieve a customer from the repository and make it preferred. We throw an exception in case the customer cannot be found in the data store.</p>

<p>Here are the context/specifications for this easy example:</p>

<pre class="csharpcode">[Subject(<span class="str">&quot;Making a customer preferred&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_making_a_customer_preferred
    : context_specification&lt;MakeCustomerPreferredMessageHandler&gt;
{
    Establish context = () =&gt;
    {
        _message = <span class="kwrd">new</span> MakeCustomerPreferredMessage { CustomerId = 6412 };

        Repository.Stub(repository =&gt; repository.Get(_message.CustomerId))
            .Return(Customer);
    };

    Because of = () =&gt; 
        SUT.Handle(_message);
    
    It should_mark_the_customer_as_preferred = () =&gt;
        Customer.AssertWasCalled(customer =&gt; customer.MakePreferred());

    It should_save_the_customer_in_the_repository = () =&gt;
        Repository.AssertWasCalled(repository =&gt; repository.Save(Customer));

    <span class="kwrd">private</span> <span class="kwrd">static</span> ICanMakeCustomerPreferred Customer
    {
        get { <span class="kwrd">return</span> Dependency&lt;ICanMakeCustomerPreferred&gt;(); }
    }

    <span class="kwrd">private</span> <span class="kwrd">static</span> ICustomerRepository&lt;ICanMakeCustomerPreferred&gt; Repository
    {
        get { <span class="kwrd">return</span> Dependency&lt;ICustomerRepository&lt;ICanMakeCustomerPreferred&gt;&gt;(); }
    }

    <span class="kwrd">private</span> <span class="kwrd">static</span> MakeCustomerPreferredMessage _message;
}

[Subject(<span class="str">&quot;Making a customer preferred&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_making_an_unexisting_customer_preferred
    : context_specification&lt;MakeCustomerPreferredMessageHandler&gt;
{
    Establish context = () =&gt;   
    {
        _message = <span class="kwrd">new</span> MakeCustomerPreferredMessage() { CustomerId = 61544 };

        Dependency&lt;ICustomerRepository&lt;ICanMakeCustomerPreferred&gt;&gt;()
            .Stub(repository =&gt; repository.Get(_message.CustomerId))
            .Return(<span class="kwrd">null</span>);
    };

    Because of = () =&gt;
        _resultingException = Catch.Exception(() =&gt; SUT.Handle(_message));

    It should_result_in_an_error = () =&gt;
        _resultingException.ShouldBeOfType&lt;InvalidOperationException&gt;();

    <span class="kwrd">private</span> <span class="kwrd">static</span> MakeCustomerPreferredMessage _message;
    <span class="kwrd">private</span> <span class="kwrd">static</span> Exception _resultingException;
}</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>I want to point out that all fields and properties are made static. This is needed so that the anonymous methods can access them. I’m also using a base class for these specifications which I’ll show next. This base class uses an auto mocking container for providing the requested mocks and stubs through the <em>Dependency</em> and <em>Stub</em> methods. </p>

<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">abstract</span> <span class="kwrd">class</span> context_specification&lt;TSubjectUnderTest&gt;
    <span class="kwrd">where</span> TSubjectUnderTest : <span class="kwrd">class</span>
{
    <span class="kwrd">private</span> <span class="kwrd">static</span> IAutoMockingContainer&lt;TSubjectUnderTest&gt; _autoMockingContainer;
    <span class="kwrd">protected</span> <span class="kwrd">static</span> TSubjectUnderTest SUT { get; set; }

    Establish context = () =&gt;
    {
        _autoMockingContainer = <span class="kwrd">new</span> StructureMapAMC&lt;TSubjectUnderTest&gt;();
        SUT = _autoMockingContainer.Create();     
    };
    
    Cleanup stuff = () =&gt; 
    {
        SUT = <span class="kwrd">null</span>;
        _autoMockingContainer = <span class="kwrd">null</span>;
    };

    <span class="kwrd">protected</span> <span class="kwrd">static</span> TDependency Dependency&lt;TDependency&gt;()
        <span class="kwrd">where</span> TDependency : <span class="kwrd">class</span>
    {
        <span class="kwrd">return</span> _autoMockingContainer.GetMock&lt;TDependency&gt;();
    }

    <span class="kwrd">protected</span> <span class="kwrd">static</span> TStub Stub&lt;TStub&gt;()
        <span class="kwrd">where</span> TStub : <span class="kwrd">class</span>
    {
        <span class="kwrd">return</span> _autoMockingContainer.GetStub&lt;TStub&gt;();
    }
}

<span class="kwrd">public</span> <span class="kwrd">interface</span> IAutoMockingContainer&lt;TSubject&gt;
    <span class="kwrd">where</span> TSubject : <span class="kwrd">class</span>
{
    TSubject Create();
    TMock GetMock&lt;TMock&gt;() <span class="kwrd">where</span> TMock : <span class="kwrd">class</span>;
    TStub GetStub&lt;TStub&gt;() <span class="kwrd">where</span> TStub : <span class="kwrd">class</span>;
}

<span class="kwrd">public</span> <span class="kwrd">class</span> StructureMapAMC&lt;TSubject&gt; 
    : IAutoMockingContainer&lt;TSubject&gt;
    <span class="kwrd">where</span> TSubject : <span class="kwrd">class</span>
{
    <span class="kwrd">private</span> <span class="kwrd">readonly</span> RhinoAutoMocker&lt;TSubject&gt; _rhinoAutoMocker;

    <span class="kwrd">public</span> StructureMapAMC()
    {
        _rhinoAutoMocker = 
            <span class="kwrd">new</span> RhinoAutoMocker&lt;TSubject&gt;(MockMode.AAA);
    }

    <span class="kwrd">public</span> TSubject Create()
    {
        <span class="kwrd">return</span> _rhinoAutoMocker.ClassUnderTest;
    }

    <span class="kwrd">public</span> TMock GetMock&lt;TMock&gt;() 
        <span class="kwrd">where</span> TMock : <span class="kwrd">class</span>
    {
        <span class="kwrd">return</span> GetDependency&lt;TMock&gt;();
    }

    <span class="kwrd">public</span> TStub GetStub&lt;TStub&gt;() 
        <span class="kwrd">where</span> TStub : <span class="kwrd">class</span>
    {
        <span class="kwrd">return</span> GetDependency&lt;TStub&gt;();
    }

    <span class="kwrd">private</span> TDependency GetDependency&lt;TDependency&gt;() 
        <span class="kwrd">where</span> TDependency : <span class="kwrd">class</span>
    {
        <span class="kwrd">return</span> _rhinoAutoMocker.Get&lt;TDependency&gt;();
    }
}</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>Notice that I’m using the <em>Establish</em> and <em>Cleanup</em> delegates in the <em>context_specification</em> base class. This doesn’t prevent that these can be used again in derived context/specifications. MSpec ensures that the anonymous methods are called in the right order. This means that the <em>Establish</em> method of the base class is called before the <em>Establish</em> method of the derived context/specifications.&#160;&#160;&#160;&#160; </p>

<p>Absolutely no rocket science here, but I figured it might come in handy when you need it. For the next post I’ll try to demonstrate how to deal with reusable behaviors.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/02/23/mspec-and-auto-mocking/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Getting Started With Machine.Specifications (MSpec)</title>
		<link>http://elegantcode.com/2010/02/19/getting-started-with-machine-specifications-mspec/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=getting-started-with-machine-specifications-mspec</link>
		<comments>http://elegantcode.com/2010/02/19/getting-started-with-machine-specifications-mspec/#comments</comments>
		<pubDate>Fri, 19 Feb 2010 21:34:17 +0000</pubDate>
		<dc:creator>Jan Van Ryswyck</dc:creator>
				<category><![CDATA[BDD]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/02/19/getting-started-with-machine-specifications-mspec/</guid>
		<description><![CDATA[Its been a while since I evaluated and evolved my approach to BDD. The way I’ve been doing BDD up until now is described in this blog post which goes way back to 2008. Everyone has kind of their own style nowadays. Below you can find the code of two context/specifications for a method named [...]]]></description>
			<content:encoded><![CDATA[<p>Its been a while since I evaluated and evolved my approach to BDD. The way I’ve been doing BDD up until now is described in <a href="http://elegantcode.com/2008/10/25/refining-contextspecification-bdd-using-rhino-mocks-35/">this blog post</a> which goes way back to 2008. Everyone has kind of their own style nowadays. Below you can find the code of two context/specifications for a method named <em>MakePreferred</em> on a <em>Customer </em>class. This simple example clarifies the style that I’ve been following up until now.</p> <style type="text/css">


.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style><style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>  <pre class="csharpcode">[TestFixture]
<span class="kwrd">public</span> <span class="kwrd">class</span> When_making_a_regular_customer_preferred
    : ContextSpecification&lt;Customer&gt;
{
    <span class="kwrd">protected</span> <span class="kwrd">override</span> Customer Create_subject_under_test()
    {
        <span class="kwrd">return</span> <span class="kwrd">new</span> Customer(<span class="kwrd">new</span>[] { _order });
    }

    <span class="kwrd">protected</span> <span class="kwrd">override</span> <span class="kwrd">void</span> Establish_context()
    {
        _order = <span class="kwrd">new</span> Order(<span class="kwrd">new</span>[] { <span class="kwrd">new</span> OrderItem(12), 
                                   <span class="kwrd">new</span> OrderItem(16) });
                                   
        _totalAmountWithoutDiscount = _order.TotalAmount;
    }

    <span class="kwrd">protected</span> <span class="kwrd">override</span> <span class="kwrd">void</span> Because()
    {
        SUT.MakePreferred();
    }

    [Test]
    <span class="kwrd">public</span> <span class="kwrd">void</span> Then_the_customer_should_be_marked_as_preferred()
    {
        SUT.IsPreferred.ShouldBeTrue();
    }

    [Test]
    <span class="kwrd">public</span> <span class="kwrd">void</span> Then_a_ten_percent_discount_should_be_applied_to_all_outstanding_orders()
    {
        _order.TotalAmount.ShouldBeEqualTo(
            _totalAmountWithoutDiscount * 0.9);
    }

    <span class="kwrd">private</span> Order _order;
    <span class="kwrd">private</span> Double _totalAmountWithoutDiscount;
}

[TestFixture]
<span class="kwrd">public</span> <span class="kwrd">class</span> When_making_a_preferred_customer_preferred
    : ContextSpecification&lt;Customer&gt;
{
    <span class="kwrd">protected</span> <span class="kwrd">override</span> Customer Create_subject_under_test()
    {
        var customer = <span class="kwrd">new</span> Customer(<span class="kwrd">new</span>[] { _order });
        customer.MakePreferred();
        <span class="kwrd">return</span> customer;
    }

    <span class="kwrd">protected</span> <span class="kwrd">override</span> <span class="kwrd">void</span> Establish_context()
    {
        _order = <span class="kwrd">new</span> Order(<span class="kwrd">new</span>[] { <span class="kwrd">new</span> OrderItem(12), 
                                   <span class="kwrd">new</span> OrderItem(16) });
        _totalAmountWithoutDiscount = _order.TotalAmount;
    }

    <span class="kwrd">protected</span> <span class="kwrd">override</span> <span class="kwrd">void</span> Because()
    {
        SUT.MakePreferred();
    }

    [Test]
    <span class="kwrd">public</span> <span class="kwrd">void</span> Then_no_additional_discount_should_be_applied_to_the_outstanding_orders()
    {
        _order.TotalAmount.ShouldNotBeEqualTo(
            _totalAmountWithoutDiscount * 0.81);
    }

    <span class="kwrd">private</span> Order _order;
    <span class="kwrd">private</span> Double _totalAmountWithoutDiscount;
}

<span class="rem">//</span>
<span class="rem">// Subject under test</span>
<span class="rem">//</span>
<span class="kwrd">public</span> <span class="kwrd">class</span> Customer
{
    <span class="kwrd">private</span> <span class="kwrd">readonly</span> List&lt;Order&gt; _orders;
    <span class="kwrd">public</span> Boolean IsPreferred { get; <span class="kwrd">private</span> set; }

    <span class="kwrd">public</span> Customer(IEnumerable&lt;Order&gt; orders)
    {
        _orders = <span class="kwrd">new</span> List&lt;Order&gt;(orders);
    }

    <span class="kwrd">public</span> <span class="kwrd">void</span> MakePreferred()
    {
        <span class="kwrd">if</span>(IsPreferred)    
            <span class="kwrd">return</span>;
    
        IsPreferred = <span class="kwrd">true</span>;
        _orders.ForEach(order =&gt; order.ApplyDiscount(10));
    }
}</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>The bottom line of this example is that preferred customers get a 10 percent discount. Customers that are already preferred do not get an additional discount or otherwise we’re out of business ;-). </p>

<p>I’ve been pretty happy with this approach so far, although sometimes there were some quirks associated with this. So it was time for me to look beyond the horizon again, trying to look for ways to improve. </p>

<p><a href="http://github.com/machine/machine.specifications">Machine.Specifications</a> or MSpec for short is something that has been on my ‘cool-things-to-learn-list’ for quite some time now. As you will see later in this post, the syntax is a bit different as one would come to expect from a context/specification framework that targets the C# programming language. Its seems to be heavily inspired by Scott Bellware’s <a href="http://code.google.com/p/specunit-net/">SpecUnit framework</a> and <a href="http://rspec.info/">RSpec</a>.</p>

<p>Lets see how to set things up first. </p>

<p>The most obvious starting point is downloading the bits and bytes. You can grab the <a href="http://github.com/machine/machine.specifications">source code</a> from GitHub and build it or you can wuss out like I did and get the latest build from the <a href="http://teamcity.codebetter.com/login.html">TeamCity.CodeBetter.com</a> builder server (you can log on as a guest and search the artifacts for a latest build).&#160; </p>

<p>When you’re heavily addicted to <a href="http://www.testdriven.net/">TestDriven.NET</a> like I am, then its possible to keep using this wonderful Visual Studio add-in for running MSpec context/specifications. Just create a directory named <em>Machine.Specifications</em> in {$Program_Files}\TestDriven.NET 2.0 and copy the following files:</p>

<ul>
  <li>Machine.Specifications.dll</li>

  <li>Machine.Specifications.TDNetRunner.dll</li>

  <li>InstallTDNetRunner.bat</li>
</ul>

<ul>Run the InstallTDNetRunner.bat file and you’re able to run all MSpec context/specifications using TestDriven.NET.</ul>

<p>I also strongly encourage you to install the plugin for the Resharper test runner (if only to prevent some Resharper warnings later on). First step is to add a directory named <em>Plugins</em> to the <em>Bin</em> directory of Resharper ({$Program_Files}\JetBrains\ReSharper\v4.5\Bin\). Then create a directory named <em>Machine.Specifications</em> in the <em>Plugins</em> directory you just created and copy the following files:</p>

<ul>
  <li>Machine.Specifications.dll</li>

  <li>Machine.Specifications.ReSharperRunner.4.5.dll</li>

  <li>InstallResharperRunner.4.5.bat</li>
</ul>

<p>Run the InstallResharperRunner.4.5.bat file and you’re also able to run MSpec context/specifications using the Resharper test runner.</p>

<p>I’m not going to put this off any longer. Lets look at the code of the context/specifications shown earlier but completely revamped using the MSpec syntax:</p>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<pre class="csharpcode">[Subject(<span class="str">&quot;Making a customer preferred&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_a_regular_customer_is_made_preferred 
{
    Establish context = () =&gt;
    {
        _order = <span class="kwrd">new</span> Order(<span class="kwrd">new</span>[] { <span class="kwrd">new</span> OrderItem(12), 
                                   <span class="kwrd">new</span> OrderItem(16) });
        _totalAmountWithoutDiscount = _order.TotalAmount;

        SUT = <span class="kwrd">new</span> Customer(<span class="kwrd">new</span>[] { _order });
    };

    Because of = () =&gt; 
        SUT.MakePreferred();

    It should_mark_the_customer_as_preferred = () =&gt;
        SUT.IsPreferred.ShouldBeTrue();
        
    It should_apply_a_ten_percent_discount_to_all_outstanding_orders = () =&gt;
        _order.TotalAmount.ShouldEqual(_totalAmountWithoutDiscount * 0.9);      

    <span class="kwrd">private</span> <span class="kwrd">static</span> Customer SUT;
    
    <span class="kwrd">private</span> <span class="kwrd">static</span> Order _order;
    <span class="kwrd">private</span> <span class="kwrd">static</span> Double _totalAmountWithoutDiscount;
}

[Subject(<span class="str">&quot;Making a customer preferred&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_a_preferred_customer_is_made_preferred
{
    Establish context = () =&gt;
    {
        _order = <span class="kwrd">new</span> Order(<span class="kwrd">new</span>[] { <span class="kwrd">new</span> OrderItem(12), 
                                   <span class="kwrd">new</span> OrderItem(16) });
        _totalAmountWithoutDiscount = _order.TotalAmount;

        SUT = <span class="kwrd">new</span> Customer(<span class="kwrd">new</span>[] { _order });
        SUT.MakePreferred();
    };

    Because of = () =&gt;
        SUT.MakePreferred();

    It should_apply_no_additional_discount_to_the_outstanding_orders = () =&gt; 
        _order.TotalAmount.ShouldNotEqual(_totalAmountWithoutDiscount * 0.81);

    <span class="kwrd">private</span> <span class="kwrd">static</span> Customer SUT;

    <span class="kwrd">private</span> <span class="kwrd">static</span> Order _order;
    <span class="kwrd">private</span> <span class="kwrd">static</span> Double _totalAmountWithoutDiscount;
}</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>I warned you about the syntax, didn’t I :-). It only took me a couple of seconds to get used to this syntax but now I’m completely hooked. Instead of using methods and attributes, MSpec utilizes delegates and anonymous methods. But there’s more. </p>

<p>When using <a href="http://www.nunit.com/index.php">NUnit</a> for writing context/ specifications, the <em>Establish_context</em> and <em>Because</em> methods of the example shown earlier is executed before every observation (test). With MSpec, the <em>Establish</em> and <em>Because</em> anonymous methods are executed only once for every context no matter how many observations a particular context class contains. Big difference? Well, at first glance not but on second hand it does make <a href="http://elegantcode.com/2008/12/30/dont-sell-out-on-the-context-dude/">selling out on the context</a> a bit more difficult as it will probably blow up in your face sooner than later. You can force MSpec to execute the <em>Establish</em> and <em>Because</em> anonymous methods before every observation by applying the <em>SetupForEachSpecification</em> attribute to the context class, but I strongly encourage you to stay away from that unless absolutely needed.</p>

<p>Also notice that the fields in the contexts are now all static. This is needed so that the anonymous methods can access those.&#160;&#160;&#160;&#160;&#160; </p>

<p>Running these context/specifications using TestDriven.NET yields the following output in the output window of Visual Studio:</p>

<blockquote>
  <p><font face="Arial">Making a customer preferred, when a regular customer is made preferred
      <br />» should mark the customer as preferred

      <br />» should apply a ten percent discount to all outstanding orders</font></p>

  <p><font face="Arial">Making a customer preferred, when a preferred customer is made preferred
      <br />» should apply no additional discount to the outstanding orders</font></p>
</blockquote>

<p>What’s not to like? Well, the only downside so far is that Resharper was giving me some warnings about classes and fields not being used etc. … . Many of those warnings disappeared by registering the MSpec plugin for the Resharper test runner as I explained earlier.</p>

<p>So far, so good. I’ve got two more posts coming up on MSpec, so stay tuned.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/02/19/getting-started-with-machine-specifications-mspec/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Unity/Moq &#8211; AutoMocker or AutoMockingContainer</title>
		<link>http://elegantcode.com/2010/01/03/unitymoq-automocker-or-automockingcontainer/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=unitymoq-automocker-or-automockingcontainer</link>
		<comments>http://elegantcode.com/2010/01/03/unitymoq-automocker-or-automockingcontainer/#comments</comments>
		<pubDate>Sun, 03 Jan 2010 16:52:33 +0000</pubDate>
		<dc:creator>Jason Jarrett</dc:creator>
				<category><![CDATA[TDD]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Tools and Utilities]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/01/03/unitymoq-automocker-or-automockingcontainer/</guid>
		<description><![CDATA[What is an Auto Mocking Container? This post started to get a little long, so I won’t re-explain the concept. Joshua Flanagan wrote a nice overview at his Los Techies blog: Auto mocking Explained. My post is mainly here to describe the Unity version of an automocking container I threw together. In Jan 2009 I [...]]]></description>
			<content:encoded><![CDATA[<h4>What is an Auto Mocking Container?</h4>  <p>This post started to get a little long, so I won’t re-explain the concept.</p>  <p><a href="http://www.lostechies.com/blogs/joshuaflanagan/default.aspx">Joshua Flanagan</a> wrote a nice overview at his <a href="http://www.lostechies.com/">Los Techies</a> blog: <a href="http://www.lostechies.com/blogs/joshuaflanagan/archive/2009/02/03/auto-mocking-explained.aspx"><strong>Auto mocking Explained</strong></a>.</p>  <p>My post is mainly here to describe the Unity version of an automocking container I threw together.</p>  <h4>In Jan 2009 I blogged about my initial version of the Unity AutoMocker - Why am I blogging about it again?</h4>  <p>I originally wrote the AutoMocker for the Unity container a year ago (Jan 2009, in Silverlight), and finally got around to placing the code up in the <a href="http://code.google.com/p/moq-contrib/">moq-contrib</a> project in June of 2009.</p>  <p>I’m writing another post today in hopes to:</p>  <ol>   <li>Get some feedback on how this little snippet of code should continue. </li>    <li>Give a little more how-to/example code </li>    <li>Describe some updates I made since I originally created it.&#160; </li> </ol>  <h4>Where can I get it?</h4>  <p><strong>This is one part where I’d appreciate some feedback.</strong></p>  <p>I have two slightly different versions out there (currently).</p>  <p>I have one version at the <a href="http://code.google.com/p/elegantcode/source/browse/#svn/trunk/Coders/JasonJarrett/UnityAutoMocker">ElegantCode</a> repository where I was working on it, and the other I threw up at <a href="http://code.google.com/p/moq-contrib/">moq-contrib</a>.</p>  <p>The core of the UnityAutoMockContainer is the same in both places, it’s how the tests are separated out that differ.</p>  <p>In the <a href="http://code.google.com/p/elegantcode/source/browse/#svn/trunk/Coders/JasonJarrett/UnityAutoMocker">ElegantCode repository</a> it’s an all in one self contained single file (that you can copy into your own test project(s)). You can then setup a single test in your own testing framework that runs all internal automocker tests (in case you need to modify it yourself, and don’t want to break any existing functionality). EX: test</p>  <pre class="brush: csharp;">[Test]
public void Should_run_all_UnityAutoMockContainer_internal_tests()
{
    Moq.AutoMocking.SelfTesting.UnityAutoMockContainerFixture
        .RunAllTests(Console.WriteLine);
}</pre>

<p>I kind of like this format as it makes it easy to port between test libraries. Can’t say I like having the tests in the same file as the core, but it certainly is not a large chunk of code (so far) so it’s relatively small to maintain and definitely easier to manage as a single .cs file than another assembly (which would have to be version dependent on both Unity and Moq).</p>

<p>The <a href="http://code.google.com/p/moq-contrib/">moq-contrib</a> is definitely where I think this helper should end up (and it is there). I just happened to break the tests out into the Silverlight test project and the core is alone in a file. </p>

<p>It’s current state isn’t as easy to copy to a test library (Silverlight/Desktop/Unity 1.2/Unity 2.0) as the one at <a href="http://elegantcode.com/">ElegantCode</a>. <strong>What does anyone think?</strong> Should I put them all together in one file?</p>

<p>However it ends up (1. all in one file or two (1 test) (1 core)) it will continue to be maintained on the <a href="http://code.google.com/p/moq-contrib/">moq-contrib</a> project.</p>

<h4>What is the high level API of the container?</h4>

<p>It’s pretty simple, (currently) there are four methods on the container.</p>

<p><strong>Two for registering items with the container</strong>. Say you want to register an already created instance, or say you want to map an interface to a concrete class and _not_ have the container generate mocks automatically for special cases. </p>

<p>And <strong>two for pulling items out of the container</strong>. Whether you want a instance of T or a Mock&lt;T&gt;, it gives you ways to retrieve both.</p>

<blockquote>
  <p><a href="http://elegantcode.com/wp-content/uploads/2010/01/image.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://elegantcode.com/wp-content/uploads/2010/01/image_thumb.png" width="396" height="106" /></a> </p>
</blockquote>

<h4>How can I setup my own registrations with the container? </h4>

<p>Say I don’t want to have the container generate mocks for specific items and I want to supply specific configuration to the UnityContainer.</p>

<blockquote>
  <p>public UnityAutoMockContainer RegisterInstance&lt;TService&gt;(TService instance)</p>

  <p>public UnityAutoMockContainer Register&lt;TService, TImplementation&gt;() 
    <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; where TImplementation : TService</p>
</blockquote>

<p><strong>Note</strong>: both of these registration methods return the container itself so you can fluently stack registration. <strong>EX:</strong></p>

<pre class="brush: csharp;">AutoMockContainer
    .Register&lt;IServiceA, ServiceA&gt;()
    .Register&lt;IServiceB, ServiceB&gt;();</pre>

<p><strong>Let me know</strong>: I haven’t tested or played around with how this automocking container deals with any container specific xml configuration… So although I don’t think you should probably have that in a test assembly (stuff happens). Let me know if there are any issues.</p>

<h4>How do I get items out of the container?</h4>

<p>First is the Resolve&lt;T&gt;(). It will pull an item T out of the container. (Creating it if not already existing)</p>

<blockquote>
  <p>public T Resolve&lt;T&gt;()</p>
</blockquote>

<p>When T is an interface Resolve&lt;T&gt; (unless you setup registration specifically with the container) should return basically “(new Mock&lt;T&gt;()).Object”</p>

<p>When T is a concrete Class, the container should return an instance of T and any of it’s dependencies will be satisfied by mocks. (Note that T will not be any sort of mocked instance of T, unless you used the GetMock&lt;T&gt; as described below first)</p>

<blockquote>
  <p>public Mock&lt;T&gt; GetMock&lt;T&gt;() where T : class</p>
</blockquote>

<p>When T is an interface GetMock&lt;T&gt; should return basically “(new Mock&lt;T&gt;())” </p>

<p>When T is a concrete Class, the container should return a new Mock&lt;T&gt;() and any of it’s dependencies will be satisfied by mocks.</p>

<h4>How do I use the UnityAutoMockContainer?</h4>

<p>It’s pretty basic, you first create an instance of the UnityAutoMockContainer, and from there you can ask it for mocks of an (Interface, Class, or Abstract Class).</p>

<p>If you request an instance of a concrete class, or abstract class, the UnityAutoMockContainer will stuff mocks in for any constructor dependencies of your concrete class (if it can). You can then request from the container those same dependencies one at a time and either apply mocking setups or verifications.</p>

<blockquote>
  <p><strong>NOTE:</strong> Anything the container creates will live as a singleton instance in the container. So any other requests from the container will always return the originally created instance. Therefore, each distinct scenario in a test suite should have their own instances of the container.</p>
</blockquote>

<p>Below his an example of how you can leverage the container in some tests. Given this base fixture class…</p>

<pre class="brush: csharp;">public class FixtureBase
{
    private readonly UnityAutoMockContainer _autoMockContainer = new UnityAutoMockContainer();

    protected UnityAutoMockContainer AutoMockContainer
    {
        get { return _autoMockContainer; }
    }

    [TestFixtureSetUp]
    public void SetupContext_ALL()
    {
        Before_all_tests();
        Because();
    }

    [TestFixtureTearDown]
    public void TearDownContext_ALL()
    {
        After_all_tests();
    }

    protected virtual void Before_all_tests()
    {
    }

    protected virtual void Because()
    {
    }

    protected virtual void After_all_tests()
    {
    }
}</pre>

<p>If I were given the following system to test.</p>

<pre class="brush: csharp;">public interface IServiceA { void RunA(); }
public interface IServiceB { void RunB(); }

public class TestComponent
{
    public TestComponent(IServiceA serviceA, IServiceB serviceB)
    {
        ServiceA = serviceA;
        ServiceB = serviceB;
    }

    public IServiceA ServiceA { get; private set; }
    public IServiceB ServiceB { get; private set; }

    public void RunAll()
    {
        if (!HowDidItGo())
            return;
        ServiceA.RunA();
        ServiceB.RunB();
    }

    public virtual bool HowDidItGo()
    {
        // some really nasty untestable code
        return true;
    }
}</pre>

<p>The below example demonstrates simply verifying some behavior on the mocked dependencies of the system under test.</p>

<pre class="brush: csharp;">[TestFixture]
public class Example__how_to_pull_items_from_the_UnityAutoMockContainer_when_verifying_behavior_after_an_action_was_taken 
    : FixtureBase
{
    private TestComponent _testComponent;

    protected override void Before_all_tests()
    {
        base.Before_all_tests();
        _testComponent = AutoMockContainer.Resolve&lt;TestComponent&gt;();
    }

    protected override void Because()
    {
        _testComponent.RunAll();
    }

    [Test]
    public void Should_run_ServiceA_RunA()
    {
        AutoMockContainer
            .GetMock&lt;IServiceA&gt;()
            .Verify(v =&gt; v.RunA(), Times.Once());
    }

    [Test]
    public void Should_run_ServiceB_RunB()
    {
        AutoMockContainer
            .GetMock&lt;IServiceB&gt;()
            .Verify(v =&gt; v.RunB(), Times.Once());
    }
}</pre>

<p>Next, you may have noticed that the system under test had a complicated internal method (that may not necessarily be testable). You can use the AutoMocker to create the system under test as a Mock itself, so we can override some of the behavior. Here’s how you could quickly do that. </p>

<blockquote>
  <p><strong>Aside</strong>: I’m not saying this is a good practice or aids in good component design, just saying it’s possible</p>
</blockquote>

<pre class="brush: csharp;">[TestFixture]
public class Example__how_to_use_the_UnityAutoMockContainer_to_override_a_method_on_the_SystemUnderTest_to_test_a_certain_behavior
    : FixtureBase
{

    private TestComponent _testComponent;

    protected override void Before_all_tests()
    {
        base.Before_all_tests();
        var mockTestComponent = AutoMockContainer.GetMock&lt;TestComponent&gt;();

        mockTestComponent
            .Setup(s =&gt; s.HowDidItGo())
            .Returns(false);

        _testComponent = mockTestComponent.Object;
    }

    protected override void Because()
    {
        _testComponent.RunAll();
    }

    [Test]
    public void Should_run_ServiceA_RunA()
    {
        AutoMockContainer
            .GetMock&lt;IServiceA&gt;()
            .Verify(v =&gt; v.RunA(), Times.Never());
    }

    [Test]
    public void Should_run_ServiceB_RunB()
    {
        AutoMockContainer
            .GetMock&lt;IServiceB&gt;()
            .Verify(v =&gt; v.RunB(), Times.Never());
    }
}</pre>

<p>&#160;</p>

<p>It’s amazing how much redundant test setup code this little helper has saved me in my tests. I hope others can find some use with this as well.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/01/03/unitymoq-automocker-or-automockingcontainer/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>StatLight &#8211; Goes Open Source</title>
		<link>http://elegantcode.com/2009/12/10/statlight-goes-open-source/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=statlight-goes-open-source</link>
		<comments>http://elegantcode.com/2009/12/10/statlight-goes-open-source/#comments</comments>
		<pubDate>Fri, 11 Dec 2009 03:26:55 +0000</pubDate>
		<dc:creator>Jason Jarrett</dc:creator>
				<category><![CDATA[Esoterica]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[TDD]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Tools and Utilities]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/12/10/statlight-goes-open-source/</guid>
		<description><![CDATA[Although I made a very minor attempt at making StatLight a “for-sale” product, I knew when I started that open-source was most likely going to be my long term path for StatLight. What is it? (Silverlight Testing Automation Tool) StatLight is a tool developed for automating the setup, running, and gathering results of Silverlight unit [...]]]></description>
			<content:encoded><![CDATA[Although I made a very minor attempt at making <a href="http://statlight.net" target="_blank">StatLight</a> a “for-sale” product, I knew when I started that open-source was most likely going to be my long term path for <a href="http://statlight.net" target="_blank">StatLight</a>.
<h5>What is it? (Silverlight Testing Automation Tool)</h5>
StatLight is a tool developed for automating the setup, running, and gathering results of Silverlight unit tests. StatLight helps to speed up the feedback cycles while practicing<a href="http://en.wikipedia.org/wiki/Test-driven_development"> TDD</a>/<a href="http://en.wikipedia.org/wiki/Behavior_Driven_Development">BDD</a>/(insert your test style here) during Silverlight development.
<h5>Where can I get StatLight?</h5>
<a href="http://StatLight.CodePlex.com">http://StatLight.CodePlex.com</a>
<h4>Happy Coding !!!</h4>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/12/10/statlight-goes-open-source/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Wrapping up the StructureMap Automocking Container</title>
		<link>http://elegantcode.com/2009/11/30/wrapping-up-the-structuremap-automocking-container/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=wrapping-up-the-structuremap-automocking-container</link>
		<comments>http://elegantcode.com/2009/11/30/wrapping-up-the-structuremap-automocking-container/#comments</comments>
		<pubDate>Mon, 30 Nov 2009 07:21:43 +0000</pubDate>
		<dc:creator>Richard Cirerol</dc:creator>
				<category><![CDATA[TDD]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Unit Testing]]></category>
		<category><![CDATA[StructureMap; Automocking; MSpec;]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/11/30/wrapping-up-the-structuremap-automocking-container/</guid>
		<description><![CDATA[<p><font color="#804040"><strong>UPDATE</strong>: I apologize…the original wrapper did not allow injected dependencies.&#160; I have fixed this bug and updated the sample.</font></p> I have been using StructureMap.AutoMocking with MSpec (Machine.Specifications) and Rhino.Mocks for a few months now.  Although I am very comfortable with the patterns that emerge from using the frameworks together, introducing StructureMap.Automocking to other developers is sometimes challenging. I decided to wrap the details of the container to make the intention clearer and explanation easier.  I have started using this wrapper in my projects, and have found it makes building up specifications more efficient in my daily coding.]]></description>
			<content:encoded><![CDATA[<span style="color: #804040;"><strong>UPDATE</strong>: I apologize…the original wrapper did not allow injected dependencies.  I have fixed this bug and updated the sample.</span>

I have been using StructureMap.AutoMocking with MSpec (Machine.Specifications) and Rhino.Mocks for a few months now.  Although I am very comfortable with the patterns that emerge from using the frameworks together, introducing StructureMap.Automocking to other developers is sometimes challenging.

When viewing a specification or test set up with the Rhino.Mocks or Moq automocking container, what is being tested is not readily apparent.  Once the concept is explained and demonstrated, these same developers seem to have no issue with maintaining the specifications/tests.

I decided to wrap the details of the container to make the intention clearer and explanation easier.  I have started using this wrapper in my projects, and have found it makes building up specifications more efficient in my daily coding.

Let me know whether this is useful to you, or how it could be made more useful.
<h4>The Examples</h4>
Let’s contrive an example.  We’ll say we have a coffee machine that grinds its own beans before brewing. However, the hopper has to have beans before starting the grind.  Here is the basic specification:
<table border="1" cellspacing="0" cellpadding="2" width="533">
<tbody>
<tr>
<td width="117" valign="top">Action/Behavior</td>
<td width="414" valign="top">Prepare coffee grounds for 12 cups of coffee</td>
</tr>
<tr>
<td rowspan="2" width="117" valign="top">Expectations</td>
<td width="414" valign="top">Should check that hopper has beans (mock returns true)</td>
</tr>
<tr>
<td width="414" valign="top">Because hopper has beans, should ask grinder to grind enough beans for 12 cups of coffee</td>
</tr>
</tbody></table>
We could start without a container, using Rhino.Mocks to build up the CoffeeMachine dependencies manually:
<pre class="brush: csharp;">[Subject(typeof(CoffeeMachine),"using vanilla Rhino.Mocks")]
public class Example01_when_preparing_coffee_grounds
{
    Establish context = () =&gt;
        {
            Grinder = MockRepository.GenerateMock&lt;IGrinder&gt;();
            Hopper = MockRepository.GenerateMock&lt;IHopper&gt;();
            Hopper.Expect(x =&gt; x.HasBeans()).Return(true);
            CoffeeMachine = new CoffeeMachine(Grinder, Hopper);
        };

    Because of = () =&gt; _coffeeMachine.PrepareCoffeeGrounds(12);

    It should_check_if_hopper_has_beans = () =&gt; Hopper.VerifyAllExpectations();
    It should_grind_coffee = () =&gt; Grinder.AssertWasCalled(x =&gt; x.Grind(12));

    static IGrinder Grinder;
    static IHopper Hopper;
    static CoffeeMachine CoffeeMachine;
}</pre>
For those of you not familiar with the MSpec style, please refer to the following posts:
<ul>
	<li><a href="http://blog.wekeroad.com/blog/make-bdd-your-bff-2/" target="_blank">Make BDD Your BFF</a></li>
	<li><a href="http://www.lostechies.com/blogs/seanbiefeld/archive/2009/08/25/step-by-step-to-using-machine-specifications-with-resharper.aspx" target="_blank">Step by Step to Using MSpec (Machine.Specifications) with ReSharper</a></li>
	<li><a href="http://elegantcode.com/2009/07/05/mspec-take-2/" target="_blank">MSpec - Take 2</a></li>
	<li><a href="http://marcinobel.com/index.php/mspec-bdd-installer/" target="_blank">MSpec BDD framework installer</a></li>
	<li><strong>Updated! </strong>From the <a href="http://blog.cwa.me.uk/2009/11/30/the-morning-brew-487/" target="_blank">Morning Brew #487</a>: BDD with MSpec and Rhino Auto Mocks, parts  <a href="http://telldontask.wordpress.com/2009/11/10/bdd-with-mspec-and-rhino-auto-mocks/" target="_blank">1</a>, <a href="http://telldontask.wordpress.com/2009/11/19/bdd-with-mspec-and-rhino-auto-mocks-part-2/" target="_blank">2</a>, and <a href="http://telldontask.wordpress.com/2009/11/29/bdd-with-mspec-and-rhino-auto-mocks-part-3/" target="_blank">3</a>
Here is the same specification using the RhinoAutoMocker&lt;T&gt; class provided by StructureMap.AutoMocking:</li>
</ul>
<pre class="brush: csharp;">[Subject(typeof(CoffeeMachine),"using RhinoAutoMocker&lt;CoffeeMachine&gt;")]
public class Example02_when_preparing_coffee_grounds
{
    Establish context = () =&gt;
        {
            CoffeeMachine = new RhinoAutoMocker&lt;CoffeeMachine&gt;();
            Grinder = CoffeeMachine.Get&lt;IGrinder&gt;();
            Hopper = CoffeeMachine.Get&lt;IHopper&gt;();
            Hopper.Expect(x =&gt; x.HasBeans()).Return(true);
        };

    Because of = () =&gt; v.ClassUnderTest.PrepareCoffeeGrounds(12);

    It should_check_if_hopper_has_beans = () =&gt; Hopper.VerifyAllExpectations();
    It should_grind_coffee = () =&gt; Grinder.AssertWasCalled(x =&gt; x.Grind(12));

    static IGrinder Grinder;
    static IHopper Hopper;
    static RhinoAutoMocker&lt;CoffeeMachine&gt; CoffeeMachine;
}</pre>
Although I think this looks cleaner, the initialization of CoffeeMachine causes some confusion. Unfortunately, a common question would be, “Is RhinoAutoMocker&lt;CoffeeMachine&gt; creating a mocked version of CoffeeMachine?” Well, not exactly.

RhinoAutoMocker is an implementation of the AutoMocker base class which uses StructureMap to fill dependencies.  The RhinoAutoMocker implementation of the container uses Rhino.Mocks to generate all of dependencies of the target class, whereas the MoqAutoMocker implementation uses Moq.  (Optionally, the target class can be partially mocked in order to further isolate behavior.)  We then retrieve the class under test (in this case, CoffeeMachine) and its dependencies (IGrinder and IHopper) from the container for use.

If you do not need to setup any expectations in the specification, there is no need to retrieve the dependency from the container.  However, in this specification, we need both dependencies.

<em>(Incidentally, I do not like the ClassUnderTest name.  I may end up changing this to Instance, ClassInstance, TargetClass, or something similar.  Suggestions?)</em>

By moving the initialization of the RhinoAutoMocker to a base class, some of the chattiness of the context can be hidden.
<ul>
<pre class="brush: csharp;">[Subject(typeof(CoffeeMachine),"using RhinoAutoMocker base")]
public class Example03_when_preparing_coffee_grounds : with_rhinoautomocker
{
    Establish context = () =&gt; Hopper.Expect(x =&gt; x.HasBeans()).Return(true);

    Because of = () =&gt; CoffeeMachine.ClassUnderTest.PrepareCoffeeGrounds(12);

    It should_check_if_hopper_has_beans = () =&gt; Hopper.VerifyAllExpectations();
    It should_grind_coffee = () =&gt; Grinder.AssertWasCalled(x =&gt; x.Grind(12));

}

[Subject("using RhinoAutoMocker&lt;T&gt;")]
public class with_rhinoautomocker
{
    protected static IGrinder Grinder;
    protected static IHopper Hopper;
    protected static RhinoAutoMocker&lt;CoffeeMachine&gt; CoffeeMachine;

    Establish context = () =&gt;
    {
        CoffeeMachine = new RhinoAutoMocker&lt;CoffeeMachine&gt;();
        Grinder = CoffeeMachine.Get&lt;IGrinder&gt;();
        Hopper = CoffeeMachine.Get&lt;IHopper&gt;();
    };
}</pre>
However, we are still initializing and accessing the class in a less than optimal manner.To make the usage of the container a little more seamless, I decided to create a wrapper and factory for the AutoMocker.  Setup of the dependencies and expectations are done through an AutoMocker wrapper object.  The instance of the class under test is accessed through a ClassUnderTest object.
<h4>The Result</h4>
The specification (and base class) now look like this:
<pre class="brush: csharp;">[Subject(typeof(CoffeeMachine),"using coffee machine base")]
public class Example05_when_preparing_coffee_grounds : with_coffee_machine
{
    Establish context = () =&gt; Hopper.Expect(x =&gt; x.HasBeans()).Return(true);

    Because of = () =&gt; ClassUnderTest.PrepareCoffeeGrounds(12);

    It should_check_if_hopper_has_beans = () =&gt; Hopper.VerifyAllExpectations();
    It should_grind_coffee = () =&gt; Grinder.AssertWasCalled(x =&gt; x.Grind(12));
}

[Subject("using SpecificationFor&lt;CoffeeMachine&gt;")]
public class with_coffee_machine : SpecificationFor&lt;CoffeeMachine&gt;
{
    protected static IGrinder Grinder;
    protected static IHopper Hopper;

    public with_coffee_machine
    {
        Grinder = AutoMocker.Get&lt;IGrinder&gt;();
        Hopper = AutoMocker.Get&lt;IHopper&gt;();
    }
}</pre>
As you can see, the base class inherits from SpecificationFor&lt;T&gt;.  The default constructor uses Rhino.Mocks(MockMode.AAA) to generate the dependencies.  It then exposes a AutoMocker object, which is just the wrapper around the AutoMocker base class.  It also exposes a ClassUnderTest object.  If I didn’t need to use the dependencies, I could make the <em>Example05_when_preparing_coffee_grounds</em> class inherit from <em>SpecificationFor&lt;CoffeeMachine&gt; </em>instead of inheriting from the base class<em>.</em>
<h4>The Code</h4>
I have included the code for the wrapper below for your review.  The code and six examples are available on my <a href="http://codeprogression.googlecode.com/svn/trunk/CodeProgression.Framework.Testing" target="_blank">Google code repository</a>. The repository also includes an example using the MoqAutoMocker.  All the examples have the same assertions, but are built up using the different techniques.
<pre class="brush: csharp;">namespace CodeProgression.Framework.Testing
{
    public abstract class SpecificationFor&lt;T&gt; where T: class
    {
        protected static ClassUnderTest&lt;T&gt; Factory;

        // UPDATE 2009-12-21:
        //   Moved initialization here
        protected static T ClassUnderTest {get {return AutoMocker.Instance;} }

        protected SpecificationFor()
        {
            AutoMocker = AutoMockFactory.CreateTarget&lt;T&gt;();

            // UPDATE 2009-12-21:
            //    Initializing here prevented injected dependencies!
            // AutoMocker.PartialMockTheClassUnderTest();
            // ClassUnderTest = AutoMocker.Instance;
        }

        protected SpecificationFor(AutoMockType type)
        {
            AutoMocker = AutoMockFactory.CreateTarget&lt;T&gt;(type);

            // UPDATE 2009-12-21:
            // Initializing here prevented injected dependencies!
            // AutoMocker.PartialMockTheClassUnderTest();
            // ClassUnderTest = AutoMocker.Instance;
        }
    }

    public static class AutoMockFactory
    {
        public static ClassUnderTest&lt;TARGETCLASS&gt; CreateTarget&lt;TARGETCLASS&gt;() where TARGETCLASS : class
        {
            return CreateTarget&lt;TARGETCLASS&gt;(AutoMockType.RhinoMocksAAA);
        }

        public static ClassUnderTest&lt;TARGETCLASS&gt; CreateTarget&lt;TARGETCLASS&gt;(AutoMockType framework) where TARGETCLASS : class
        {
            AutoMocker&lt;TARGETCLASS&gt; mocker;
            ServiceLocator serviceLocator;
            switch (framework)
            {
                case AutoMockType.RhinoMocksAAA:
                    mocker = new RhinoAutoMocker&lt;TARGETCLASS&gt;(MockMode.AAA);
                    serviceLocator = new RhinoMocksAAAServiceLocator();
                    break;
                case AutoMockType.RhinoMocksClassic:
                    mocker = new RhinoAutoMocker&lt;TARGETCLASS&gt;(MockMode.RecordAndReplay);
                    serviceLocator = new RhinoMocksClassicServiceLocator();
                    break;
                case AutoMockType.Moq:
                    mocker = new MoqAutoMocker&lt;TARGETCLASS&gt;();
                    serviceLocator = new MoqServiceLocator();
                    break;
                default:
                    throw new ArgumentOutOfRangeException("framework");
            }
            return new ClassUnderTest&lt;TARGETCLASS&gt;(mocker, serviceLocator);
        }
    }

    public enum AutoMockType
    {
        Moq,
        RhinoMocksAAA,
        RhinoMocksClassic
    }

    public class ClassUnderTest&lt;TARGETCLASS&gt; where TARGETCLASS : class
    {
        readonly IAutoMocker&lt;TARGETCLASS&gt; _mocker;
        readonly ServiceLocator _serviceLocator;

        public ClassUnderTest(IAutoMocker&lt;TARGETCLASS&gt; mocker, ServiceLocator serviceLocator)
        {
            _mocker = mocker;
            _serviceLocator = serviceLocator;
        }

        public AutoMockedContainer Container
        {
            get { return _mocker.Container; }
        }

        public TARGETCLASS Instance
        {
            get { return _mocker.ClassUnderTest; }
        }

        public void MockObjectFactory()
        {
            _mocker.MockObjectFactory();
        }

        public void PartialMockTheClassUnderTest()
        {
            _mocker.PartialMockTheClassUnderTest();
        }

        public T Get&lt;T&gt;() where T : class
        {
            return _mocker.Get&lt;T&gt;();
        }

        public void Inject(Type pluginType, object stub)
        {
            _mocker.Inject(pluginType, stub);
        }

        public void Inject&lt;T&gt;(T target)
        {
            _mocker.Inject(target);
        }

        public T AddAdditionalMockFor&lt;T&gt;() where T : class
        {
            return _mocker.AddAdditionalMockFor&lt;T&gt;();
        }

        public void UseConcreteClassFor&lt;T&gt;()
        {
            _mocker.UseConcreteClassFor&lt;T&gt;();
        }

        public T[] CreateMockArrayFor&lt;T&gt;(int count) where T : class
        {
            return _mocker.CreateMockArrayFor&lt;T&gt;(count);
        }

        public void InjectArray&lt;T&gt;(T[] stubs)
        {
            _mocker.InjectArray(stubs);
        }

        public T Mock&lt;T&gt;() where T : class
        {
            return _serviceLocator.Service&lt;T&gt;();
        }
        public object Mock(Type serviceType)
        {
            return _serviceLocator.Service(serviceType);
        }
        public T PartialMock&lt;T&gt;() where T : class
        {
            return _serviceLocator.PartialMock&lt;T&gt;();
        }
    }
}</pre>
</ul>
<script type="text/javascript">// <![CDATA[
 var cirerolGaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."); document.write(unescape("%3Cscript src='" + cirerolGaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
// ]]&gt;</script>

<script type="text/javascript">// <![CDATA[
 var cirerolPageTracker = _gat._getTracker('UA-8257866-3'); cirerolPageTracker._initData(); cirerolPageTracker._trackPageview();
// ]]&gt;</script>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/11/30/wrapping-up-the-structuremap-automocking-container/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Integration Test Brought to you by Powershell &amp; NUnit &#8211; with a Little Specification Syntax for Flavoring</title>
		<link>http://elegantcode.com/2009/10/25/integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring</link>
		<comments>http://elegantcode.com/2009/10/25/integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring/#comments</comments>
		<pubDate>Mon, 26 Oct 2009 05:00:40 +0000</pubDate>
		<dc:creator>Jason Jarrett</dc:creator>
				<category><![CDATA[Esoterica]]></category>
		<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/10/25/integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring/</guid>
		<description><![CDATA[One of the tools I’ve used the last half of a year and really enjoyed is the C# specification extension methods when writing unit test assertions. If you’re looking for a little more background on the topic, I wrote about Fluent Specification Extensions in a past blog. Recently I wanted to execute a PowerShell script [...]]]></description>
			<content:encoded><![CDATA[One of the tools I’ve used the last half of a year and really enjoyed is the C# specification extension methods when writing unit test assertions. If you’re looking for a little more background on the topic, I wrote about <a href="http://staxmanade.blogspot.com/2009/02/fluent-specification-extensions.html">Fluent Specification Extensions</a> in a past blog.

Recently I wanted to execute a PowerShell script to do some automated <a href="http://en.wikipedia.org/wiki/Functional_testing">functional testing</a>. I wanted to execute an application and apply some assertions on the output of the software(basically running a console app, parse the xml output and assert on values in the output).
<blockquote>FYI: I’m very new to PowerShell, so any suggestions on how I implemented the below are welcome…</blockquote>
I’ve seen a couple examples of writing test assertions in PowerShell out there. One example is <a href="http://www.psunit.org/">PSUnit</a>; however, this seemed a little heavy for my needs and not quite the syntactic sugar I was looking for.

Besides the syntax flavor I was desiring, another thing I wanted to do was leverage the power of NUnit.Framework’s assertion capabilities. I like the error messages generated when strings and other objects fail the assertion.
<h5>Examples of end result ShouldLookLike()…</h5>
$true.ShouldBeTrue()
$false.ShouldBeFalse()
"a".ShouldEqual("a")
"a".ShouldNotEqual("b")
<h5><strong>Step 1</strong>: Figure out how to write a C# style <a href="http://msdn.microsoft.com/en-us/library/bb383977.aspx">extension method</a> in PowerShell.</h5>
<blockquote>I found a great blog post describing how to extend any PowerShell object to add extension methods.

<a href="http://bartdesmet.net/blogs/bart/archive/2007/09/06/extension-methods-in-windows-powershell.aspx">Extension Methods in Windows PowerShell</a></blockquote>
In short, to extend types in PowerShell leveraging the <a href="http://msdn.microsoft.com/en-us/library/ms714419(VS.85).aspx">Extended Type System</a>, you need to define them in an xml file and import the method definitions into the PowerShell runtime instance.

Below is PowerShell XML definition for my NUnit Specification Extensions.
<pre class="brush: xml;">&lt;?xml version="1.0" encoding="utf-16"?&gt;
&lt;Types&gt;
    &lt;Type&gt;
        &lt;Name&gt;System.Object&lt;/Name&gt;
        &lt;Members&gt;
            &lt;ScriptMethod&gt;
                &lt;Name&gt;ShouldBeFalse&lt;/Name&gt;
                &lt;Script&gt;
                    [NUnit.Framework.Assert]::IsFalse($this)
                &lt;/Script&gt;
            &lt;/ScriptMethod&gt;
            &lt;ScriptMethod&gt;
                &lt;Name&gt;ShouldBeTrue&lt;/Name&gt;
                &lt;Script&gt;
                    [NUnit.Framework.Assert]::IsTrue($this)
                &lt;/Script&gt;
            &lt;/ScriptMethod&gt;
            &lt;ScriptMethod&gt;
                &lt;Name&gt;ShouldEqual&lt;/Name&gt;
                &lt;Script&gt;
                    [NUnit.Framework.Assert]::AreEqual($args[0], $this)
                &lt;/Script&gt;
            &lt;/ScriptMethod&gt;
            &lt;ScriptMethod&gt;
                &lt;Name&gt;ShouldNotEqual&lt;/Name&gt;
                &lt;Script&gt;
                    [NUnit.Framework.Assert]::AreNotEqual($args[0], $this)
                &lt;/Script&gt;
            &lt;/ScriptMethod&gt;
        &lt;/Members&gt;
    &lt;/Type&gt;
&lt;/Types&gt;</pre>
<h4></h4>
Take the above XML and save it to a file…
<blockquote>NOTE: the file HAS to be saved with the extension <strong>.ps1xml</strong>

Ex: NunitSpecificationPowerShellExtensions<strong>.ps1xml</strong></blockquote>
<h4></h4>
<h5>Step 2: Load the extended type definition into the PowerShell runtime.</h5>
Once you’ve saved the XML extended types to a file, you need to load it into the PowerShell runtime by executing the command below.
<blockquote>
Update-TypeData -PrependPath NunitSpecificationPowerShellExtensions.ps1xml</blockquote>
Before executing the above statement…Let’s quickly look at a System.String’s members and properties – just to show you what the extension methods look like when applied inside of the runtime.<a href="http://elegantcode.com/wp-content/uploads/2009/10/image3.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" src="http://elegantcode.com/wp-content/uploads/2009/10/image_thumb2.png" border="0" alt="image" width="586" height="479" /></a>

After executing the Update-TypeData command you’ll notice there are a number of “ScriptMethod” MemberTypes added to the object.

<a href="http://elegantcode.com/wp-content/uploads/2009/10/image4.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" src="http://elegantcode.com/wp-content/uploads/2009/10/image_thumb3.png" border="0" alt="image" width="600" height="580" /></a>

Now if you try to execute one of those newly added extension methods, you may get the following error…

PS C:\&gt; $testVar.<strong>ShouldEqual</strong>("hello world")

Exception calling "ShouldEqual" with "1" argument(s): "<strong>Unable to find type [NUnit.Framework.Assert]: make sure that the

assembly containing this type is loaded.</strong>"

At line:1 char:21

+ $testVar.ShouldEqual &lt;&lt;&lt;&lt; ("hello world")

+ CategoryInfo          : NotSpecified: (:) [], MethodInvocationException

+ FullyQualifiedErrorId : ScriptMethodRuntimeException

This is because we need to load the NUnit.Framework assembly into the runtime before we can leverage the extension methods.
<blockquote>[System.Reflection.Assembly]::LoadFrom("C:\Program Files\NUnit 2.5.2\bin\net-2.0\framework\nunit.framework.dll") | Out-Null</blockquote>
Now that the extension methods have been defined and loaded into the runtime, NUnit.Framework is loaded, we can now use the methods on any object that inherits from System.Object (which, as far as I know, is everything in PowerShell).

And now, everything you need in one script (if you have the xml extended type file saved somewhere…)
<pre>#
# Update-TypeData -prependPath C:\Code\NunitSpecificationPowerShellExtensions.ps1xml
#

[System.Reflection.Assembly]::LoadFrom("C:\Program Files\NUnit 2.5.2\bin\net-2.0\framework\nunit.framework.dll") | Out-Null

$true.ShouldBeTrue()

$false.ShouldBeFalse()

"a".ShouldEqual("a")

"a".ShouldNotEqual("b")</pre>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/10/25/integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Visual Studio Team System for Small Teams</title>
		<link>http://elegantcode.com/2010/02/26/behaviors-with-mspec/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=behaviors-with-mspec</link>
		<comments>http://elegantcode.com/2010/02/26/behaviors-with-mspec/#comments</comments>
		<pubDate>Fri, 26 Feb 2010 23:33:28 +0000</pubDate>
		<dc:creator>Jan Van Ryswyck</dc:creator>
				<category><![CDATA[BDD]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/02/26/behaviors-with-mspec/</guid>
		<description><![CDATA[In my previous posts, I showed the syntax for context/specifications using Machine.Specifications (or MSpec for short) and how to use an auto mocking container in conjunction with this excellent Behavior-Driven Development (BDD) framework. For this post, I want to show you one of the nice features of MSpec called behaviors. Suppose we have to create [...]]]></description>
			<content:encoded><![CDATA[<p>In my previous posts, I showed the <a href="http://elegantcode.com/2010/02/19/getting-started-with-machine-specifications-mspec/">syntax for context/specifications</a> using <a href="http://github.com/machine/machine.specifications">Machine.Specifications</a> (or MSpec for short) and <a href="http://elegantcode.com/2010/02/23/mspec-and-auto-mocking">how to use an auto mocking container</a> in conjunction with this excellent Behavior-Driven Development (BDD) framework. For this post, I want to show you one of the nice features of MSpec called <em>behaviors</em>.</p>  <p>Suppose we have to create some sort of specification that validates the format of an e-mail address. We typically use some regular expression in order to ensure that a specified e-mail address is properly formatted.</p>  <pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">class</span> EmailSpecification
{
    <span class="kwrd">private</span> <span class="kwrd">const</span> String EmailRegexPattern = <span class="str">@&quot;.. SOME_REGEX_PATTERN ...&quot;</span>;

    <span class="kwrd">public</span> Boolean IsSatisfiedBy(String candidate)
    {
        var regex = <span class="kwrd">new</span> Regex(EmailRegexPattern);
        <span class="kwrd">return</span> regex.IsMatch(candidate);
    }
}</pre>
<style type="text/css">

.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>I guess this is pretty common and straightforward. One way to provide some unit tests for this particular piece of code is to check a whole number of e-mail addresses that either pass or fail the specification. The following example shows only a couple of scenarios:</p>

<pre class="csharpcode">[TestFixture]
<span class="kwrd">public</span> <span class="kwrd">class</span> When_validating_an_email
    : ContextSpecification&lt;EmailSpecification&gt;
{
    <span class="kwrd">protected</span> <span class="kwrd">override</span> EmailSpecification Create_subject_under_test()
    {
        <span class="kwrd">return</span> <span class="kwrd">new</span> EmailSpecification();
    }

    [Test]
    <span class="kwrd">public</span> <span class="kwrd">void</span> ShouldBeSatisfied()
    {
        Assert.That(SUT.IsSatisfiedBy(<span class="str">&quot;one2@three.com&quot;</span>));
        Assert.That(SUT.IsSatisfiedBy(<span class="str">&quot;one@two3.com&quot;</span>));
    }

    [Test]
    <span class="kwrd">public</span> <span class="kwrd">void</span> ShouldNotBeSatisfied()
    {
        Assert.That(SUT.IsSatisfiedBy(<span class="str">&quot;one_two.com&quot;</span>), Is.False);
        Assert.That(SUT.IsSatisfiedBy(<span class="str">&quot;one_two@&quot;</span>), Is.False);
    }
}</pre>
<style type="text/css">

.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>A slightly more concise approach for these kind of unit tests can be accomplished by utilizing a feature of any decent unit test framework called <em>row tests. </em>With this approach we can, at the very least, reduce the number of asserts we have to write for each unit test.<em>&#160;</em></p>

<pre class="csharpcode">[TestFixture]
<span class="kwrd">public</span> <span class="kwrd">class</span> When_validating_an_email__approach_2
    : ContextSpecification&lt;EmailSpecification&gt;
{
    <span class="kwrd">protected</span> <span class="kwrd">override</span> EmailSpecification Create_subject_under_test()
    {
        <span class="kwrd">return</span> <span class="kwrd">new</span> EmailSpecification();
    }

    [RowTest]
    [Row(<span class="str">&quot;one2@three.com&quot;</span>)]
    [Row(<span class="str">&quot;one@two3.com&quot;</span>)]
    <span class="kwrd">public</span> <span class="kwrd">void</span> ShouldBeSatisfied(String email)
    {
        Assert.That(SUT.IsSatisfiedBy(email));
    }

    [RowTest]
    [Row(<span class="str">&quot;one_two.com&quot;</span>)]
    [Row(<span class="str">&quot;one_two@&quot;</span>)]
    <span class="kwrd">public</span> <span class="kwrd">void</span> ShouldNotBeSatisfied(String email)
    {
        Assert.That(SUT.IsSatisfiedBy(email), Is.False);
    }
}</pre>
<style type="text/css">

.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>Notice that I explicitly called both of these approaches <em>unit tests</em> as they don’t have much to do with BDD in my opinion. I’m not saying that using regular unit tests is a bad thing, but with&#160; behavior-driven development context is king. So these unit tests are perfect examples of ‘<a href="http://elegantcode.com/2008/12/30/dont-sell-out-on-the-context-dude/">context betrayal</a>’ when following the BDD approach. </p>

<p>Lets see what MSpec can bring to the table for these kind of scenarios:</p>

<pre class="csharpcode">[Subject(<span class="kwrd">typeof</span>(EmailSpecification), <span class="str">&quot;is satisfied&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_validating_an_email_address_with_a_number_in_the_local_part
    : email_specification_specs
{
    Establish context = () =&gt;
        EmailAddress = <span class="str">&quot;one2@three.com&quot;</span>;

    Behaves_like&lt;SatisfiedSpecificationBehavior&gt; a_satisfied_specification;
}

[Subject(<span class="kwrd">typeof</span>(EmailSpecification), <span class="str">&quot;is satisfied&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_validating_an_email_address_with_a_number_in_the_domain_name
    : email_specification_specs
{
    Establish context = () =&gt;
        EmailAddress = <span class="str">&quot;one@two3.com&quot;</span>;

    Behaves_like&lt;SatisfiedSpecificationBehavior&gt; a_satisfied_specification;
}

[Subject(<span class="kwrd">typeof</span>(EmailSpecification), <span class="str">&quot;is satisfied&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_validating_an_email_address_without_an_At_sign
    : email_specification_specs
{
    Establish context = () =&gt;
        EmailAddress = <span class="str">&quot;one_two.com&quot;</span>;

    Behaves_like&lt;UnsatisfiedSpecificationBehavior&gt; an_unsatisfied_specification;
}

[Subject(<span class="kwrd">typeof</span>(EmailSpecification), <span class="str">&quot;is satisfied&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_validating_an_email_address_without_a_domain
    : email_specification_specs
{
    Establish context = () =&gt;
        EmailAddress = <span class="str">&quot;one_two@&quot;</span>;

    Behaves_like&lt;UnsatisfiedSpecificationBehavior&gt; an_unsatisfied_specification;
}</pre>
<style type="text/css">

.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>In order to escape ‘context betrayal’, we’ve split up every context into a separate context/specification. In order to reduce the amount of effort caused by duplicate code, we stripped the context setup to the bare minimum (just a particular e-mail address in this case). The observations are isolated into MSpec behaviors which provides a very readable description of their outcome. Lets take a look at what is needed in order to get these <em>behaviors</em> to work.</p>

<p>But first lets take at look at the abstract base class that we’ve used for the context/specifications we’ve just shown.</p>

<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">abstract</span> <span class="kwrd">class</span> email_specification_specs
{
    Establish context = () =&gt;
    {
        SUT = <span class="kwrd">new</span> EmailSpecification();
    };

    Because of = () =&gt;
        Result = SUT.IsSatisfiedBy(EmailAddress);

    <span class="kwrd">protected</span> <span class="kwrd">static</span> Boolean Result;
    <span class="kwrd">protected</span> <span class="kwrd">static</span> String EmailAddress { get; set; }
    <span class="kwrd">protected</span> <span class="kwrd">static</span> EmailSpecification SUT { get; set; }
}</pre>

<p><style type="text/css">

.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style></p>

<p>&#160;</p>

<p>We abstracted as much as possible into this base class in order to remove duplication in the context/specifications. The creation of the subject-under-test and the calling of its <em>IsSatisfiedBy</em> method, but the important one is the declaration of the <em>Result</em> field. This field contains the outcome of the <em>IsSatisfiedBy</em> method. Finally, lets have a look at the behaviors themselves:</p>

<pre class="csharpcode">[Behaviors]
<span class="kwrd">public</span> <span class="kwrd">class</span> SatisfiedSpecificationBehavior
{
    <span class="kwrd">protected</span> <span class="kwrd">static</span> Boolean Result;
    
    It should_satisfy_the_specification = () =&gt;
        Result.ShouldBeTrue();
}

[Behaviors]
<span class="kwrd">public</span> <span class="kwrd">class</span> UnsatisfiedSpecificationBehavior
{
    <span class="kwrd">protected</span> <span class="kwrd">static</span> Boolean Result;

    It should_not_satisfy_the_specification = () =&gt;
        Result.ShouldBeFalse();
}</pre>
<style type="text/css">

.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>In order to create an MSpec behavior, we just have to create a separate class that we decorate with the <em>Behaviors</em> attribute. Also notice that we have the same declaration of the <em>Result</em> field. MSpec ensures that this field gets initialized with the value of the other <em>Result</em> field that is set in the base class of the context/specifications. Note that you don’t necessarily need to put this field in a base class. You can have that field in every context/specification if you’d like (not sure why) as long as the names match with the fields used in the defined behaviors.</p>

<p>I personally like the way how the MSpec contributors tried to solve testing the same logic with different input patterns and the syntax they provided to back this up.&#160;&#160; </p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/02/26/behaviors-with-mspec/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Elegant Code &#187; Unit Testing</title>
	<atom:link href="http://elegantcode.com/category/unit-testing/feed/" rel="self" type="application/rss+xml" />
	<link>http://elegantcode.com</link>
	<description></description>
	<lastBuildDate>Tue, 15 May 2012 10:00:00 +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>AutoTest.NET</title>
		<link>http://elegantcode.com/2010/11/30/autotest-net/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=autotest-net</link>
		<comments>http://elegantcode.com/2010/11/30/autotest-net/#comments</comments>
		<pubDate>Tue, 30 Nov 2010 11:00:00 +0000</pubDate>
		<dc:creator>Jan Van Ryswyck</dc:creator>
				<category><![CDATA[TDD]]></category>
		<category><![CDATA[Tools and Utilities]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/11/30/autotest-net/</guid>
		<description><![CDATA[I just want to quickly point out a tool that I’ve been playing with for a couple of days now, named AutoTest.NET. Its an open-source tool that originates from a popular tool in the Ruby community called ZenTest, which basically runs all your valuable unit tests when you save your source files or when you [...]]]></description>
			<content:encoded><![CDATA[<p>I just want to quickly point out a tool that I’ve been playing with for a couple of days now, named <a href="https://github.com/acken/AutoTest.Net" target="_blank">AutoTest.NET</a>. Its an open-source tool that originates from a popular tool in the Ruby community called <a href="http://www.zenspider.com/ZSS/Products/ZenTest/" target="_blank">ZenTest</a>, which basically runs all your valuable unit tests when you save your source files or when you build your code. It enables you to get feedback about your changes as soon as possible.</p>  <p>The project started out a couple of years ago on <a href="http://code.google.com/p/autotestnet/" target="_blank">Google code</a> and was first initiated by <a href="http://averyblog.com/" target="_blank">James Avery</a>. Contribution stopped at some point until recently where <a href="http://ackenpacken.blogspot.com/" target="_blank">Svein Arne Ackenhausen</a> forked the source code and <a href="https://github.com/acken/AutoTest.Net" target="_blank">put it on GitHub</a>. Now it runs both for .NET as well as Mono, with NUnit, MSTest and xUnit as the currently supported unit test frameworks. </p>  <p>Here’s a screenshot from the feedback window when all tests pass:</p>  <p><a href="http://elegantcode.com/wp-content/uploads/2010/11/Success.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="Success" border="0" alt="Success" src="http://elegantcode.com/wp-content/uploads/2010/11/Success_thumb.png" width="540" height="189" /></a> </p>  <p>And here you can see the same window after I broke one of my unit tests:</p>  <p><a href="http://elegantcode.com/wp-content/uploads/2010/11/Failure.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="Failure" border="0" alt="Failure" src="http://elegantcode.com/wp-content/uploads/2010/11/Failure_thumb.png" width="538" height="319" /></a> </p>  <p>Here you can see which particular unit test has been broken and by clicking the specified link you end up at the right source file in Visual Studio. </p>  <p>I encourage you to pick up this small tool and learn how it can facilitate your TDD flow. Take a look at <a href="https://github.com/acken/AutoTest.Net/wiki/Get-started!" target="_blank">this page</a> in order to get up-and-running in no time. Also don’t forget to provide the owner(s) of this project with some feedback that you might have. Svein has been very helpful over the last week answering all my stupid questions and remarks (and the Nobel price for this year’s most patient person goes to … ;-) ). </p>  <p>I would definitely like to see this tool becoming more popular, so go check it out.&#160;&#160; </p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/11/30/autotest-net/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>If Self-Documenting Code is the What, Unit Tests are the Why</title>
		<link>http://elegantcode.com/2010/04/25/if-self-documenting-code-is-the-what-unit-tests-are-the-why/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=if-self-documenting-code-is-the-what-unit-tests-are-the-why</link>
		<comments>http://elegantcode.com/2010/04/25/if-self-documenting-code-is-the-what-unit-tests-are-the-why/#comments</comments>
		<pubDate>Sun, 25 Apr 2010 19:09:04 +0000</pubDate>
		<dc:creator>John Sonmez</dc:creator>
				<category><![CDATA[Agile]]></category>
		<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Craftsmanship]]></category>
		<category><![CDATA[Documentation]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/04/25/if-self-documenting-code-is-the-what-unit-tests-are-the-why/</guid>
		<description><![CDATA[It is not enough to just write code that is clean and self-documenting.  Eliminating comments and replacing them with clear variable and method names, will tell the reader of your code clearly what it is doing, but it will not properly express why it is doing it. If you recall from my original post on [...]]]></description>
			<content:encoded><![CDATA[It is not enough to just write code that is clean and self-documenting.  <a href="http://elegantcode.com/2010/04/18/eliminating-comments-the-road-to-clarity/">Eliminating comments</a> and replacing them with clear variable and method names, will tell the reader of your code clearly what it is doing, but it will not properly express why it is doing it.

If you recall from my <a href="http://elegantcode.com/2010/04/09/what-does-elegant-code-mean-to-me/">original post</a> on Elegant code, I stated that elegant code is:
<blockquote>Something that is simple yet effective, delivered with grace.</blockquote>
By writing self-documenting code we are hopefully able to achieve some of the aspects of simplicity and grace, but it tells us nothing about the effectiveness of the code.
<h2>Bringing the dead to life</h2>
<a href="http://elegantcode.com/wp-content/uploads/2010/04/zombies.jpg"><img style="border-right-width: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto" title="zombies" src="http://elegantcode.com/wp-content/uploads/2010/04/zombies_thumb.jpg" border="0" alt="zombies" width="441" height="295" /></a>

Throwing out comments is a debatable topic.  <a href="http://www.reddit.com/r/programming/comments/bsutx/">It raises quite a bit of controversy</a>, as you can see from some of the comments on my post about the subject.  The reason, perhaps, that so many people are so staunchly opposed to the idea, is because they are worried, and rightly so, that throwing out comments will reduce the documentation of what the code is doing.

Think about that for a second.  Is documentation of what the code is doing important?  It better be.  What we are trying to accomplish by writing self-documenting code instead of comments, is to take the vessel, which is the code itself, and make that same vessel be the documentation of what the code does.  It is by doing this that we creating a living representation of the functionality of the code.  Comments are akin to a dead representation of the functionality of the code because they do not change automatically with the code.

I diverge to talk about comments so that I can draw a parallel to another form of documentation which is valuable and should be considered necessary.  That other set of documentation is requirements.  Have you ever written requirements documents?  Have you ever captured requirements from the customer and put them into UML diagrams, or perhaps plopped them into some templated Word document, which is never updated again, and no one reads, because no one trusts it is correct?  Wouldn’t it be great if we would replace that dead document or set of documents, with a living one?

The good news is we can, and some of us have.  And I fully expect this recommendation will be just as controversial, because <strong>I am suggesting that we don’t have to write low level specifications of the system at all, instead we can write good unit tests. </strong>When we do this, we are taking a dead form of document and bringing it to life.
<h2>Unit tests tell us why and how our code is effective</h2>
If
<pre class="csharpcode">i = 5;  // Widget count defaults to five.</pre>
is replaced with
<pre class="csharpcode">widgetCount = DEFAULT_WIDGET_COUNT;</pre>
<!--.csharpcode, .csharpcode pre { 	font-size: small; 	color: black; 	font-family: consolas, "Courier New", courier, monospace; 	background-color: #ffffff; 	/*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt  { 	background-color: #f4f4f4; 	width: 100%; 	margin: 0em; } .csharpcode .lnum { color: #606060; } -->

then
<blockquote><span style="background-color: #ffffff;">1.1.5 When a new widget is created, the widget count should be increased by one.</span></blockquote>
is replaced with
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">void</span> When_NewWidgetIsCreated_Then_WidgetCountIsIncreasedByOne()
{
     WidgetFactory.Count = 3;
     WidgetFactory.CreateNew();
     assertEquals(4, WidgetFactory.Count);
}</pre>
The unit test is replacing the low level requirement, which is somewhat open to interpretation and untied to the code, with an absolute and completely tied-to-the-code, specific requirement.

The unit test is telling us why our code is built the way it is.  It is telling us what requirement that particular structure of code is trying to address.  <strong>It is telling us what end result that code is trying to accomplish and what the expectations are on the results of a given condition.</strong>

The unit test is telling us how the code is to be used in order to achieve its result.  It is serving as a living reference to the syntax and use of the code we built.  <strong>Instead of providing instructions on how to use our API, we are providing a living example, and proof that it will indeed work.</strong> Examples are often much more effective than instructions anyway.
<h2>What exactly are we replacing?</h2>
At this point we are not trying to replace all the documentation of the system (at this point).

With self-documenting code, we sought to eliminate comments, and replace them with good variable and method names.

With unit tests, we seek to eliminate technical documentation and requirements of the system, that is targeted at a developer or technical audience.

We are NOT trying to eliminate high level specifications of the system, or use cases. <strong>Unit tests DO NOT replace that kind of documentation! </strong>We will talk about replacing that kind of documentation when we talk about automated functional or system tests.

Simply put, any kind of documentation that you would give to a developer so they understand how the system works and how to use the code or APIs, can be easily replaced by writing good unit tests.

Our simple goal is to replace the “dead” documentation (meaning that it does not update automatically with the thing it is documenting), with “living” documentation in the form of unit tests.

One last point.  I want to be clear that I am not saying that having unit tests automatically results in the ability to replace technical documentation.  Just like having long-named methods and variables doesn’t automatically replace the need for comments.  It is a matter of the quality of the unit tests that are written, just as it is a matter of the quality of the self-documenting code.
<h5>As always, you can subscribe to this <a href="http://feeds2.feedburner.com/ElegantCode">RSS feed</a> to follow my posts on elegant code.  Feel free to check out my main personal blog at <a href="http://simpleprogrammer.com">http://simpleprogrammer.com</a>, which has a wider range of posts, updated 2-3 times a week.  Also, you can follow me on twitter <a href="http://twitter.com/jsonmez">here</a>.</h5>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/04/25/if-self-documenting-code-is-the-what-unit-tests-are-the-why/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Behaviors with MSpec</title>
		<link>http://elegantcode.com/2010/02/26/behaviors-with-mspec/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=behaviors-with-mspec</link>
		<comments>http://elegantcode.com/2010/02/26/behaviors-with-mspec/#comments</comments>
		<pubDate>Fri, 26 Feb 2010 23:33:28 +0000</pubDate>
		<dc:creator>Jan Van Ryswyck</dc:creator>
				<category><![CDATA[BDD]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/02/26/behaviors-with-mspec/</guid>
		<description><![CDATA[In my previous posts, I showed the syntax for context/specifications using Machine.Specifications (or MSpec for short) and how to use an auto mocking container in conjunction with this excellent Behavior-Driven Development (BDD) framework. For this post, I want to show you one of the nice features of MSpec called behaviors. Suppose we have to create [...]]]></description>
			<content:encoded><![CDATA[<p>In my previous posts, I showed the <a href="http://elegantcode.com/2010/02/19/getting-started-with-machine-specifications-mspec/">syntax for context/specifications</a> using <a href="http://github.com/machine/machine.specifications">Machine.Specifications</a> (or MSpec for short) and <a href="http://elegantcode.com/2010/02/23/mspec-and-auto-mocking">how to use an auto mocking container</a> in conjunction with this excellent Behavior-Driven Development (BDD) framework. For this post, I want to show you one of the nice features of MSpec called <em>behaviors</em>.</p>  <p>Suppose we have to create some sort of specification that validates the format of an e-mail address. We typically use some regular expression in order to ensure that a specified e-mail address is properly formatted.</p>  <pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">class</span> EmailSpecification
{
    <span class="kwrd">private</span> <span class="kwrd">const</span> String EmailRegexPattern = <span class="str">@&quot;.. SOME_REGEX_PATTERN ...&quot;</span>;

    <span class="kwrd">public</span> Boolean IsSatisfiedBy(String candidate)
    {
        var regex = <span class="kwrd">new</span> Regex(EmailRegexPattern);
        <span class="kwrd">return</span> regex.IsMatch(candidate);
    }
}</pre>
<style type="text/css">

.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>I guess this is pretty common and straightforward. One way to provide some unit tests for this particular piece of code is to check a whole number of e-mail addresses that either pass or fail the specification. The following example shows only a couple of scenarios:</p>

<pre class="csharpcode">[TestFixture]
<span class="kwrd">public</span> <span class="kwrd">class</span> When_validating_an_email
    : ContextSpecification&lt;EmailSpecification&gt;
{
    <span class="kwrd">protected</span> <span class="kwrd">override</span> EmailSpecification Create_subject_under_test()
    {
        <span class="kwrd">return</span> <span class="kwrd">new</span> EmailSpecification();
    }

    [Test]
    <span class="kwrd">public</span> <span class="kwrd">void</span> ShouldBeSatisfied()
    {
        Assert.That(SUT.IsSatisfiedBy(<span class="str">&quot;one2@three.com&quot;</span>));
        Assert.That(SUT.IsSatisfiedBy(<span class="str">&quot;one@two3.com&quot;</span>));
    }

    [Test]
    <span class="kwrd">public</span> <span class="kwrd">void</span> ShouldNotBeSatisfied()
    {
        Assert.That(SUT.IsSatisfiedBy(<span class="str">&quot;one_two.com&quot;</span>), Is.False);
        Assert.That(SUT.IsSatisfiedBy(<span class="str">&quot;one_two@&quot;</span>), Is.False);
    }
}</pre>
<style type="text/css">

.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>A slightly more concise approach for these kind of unit tests can be accomplished by utilizing a feature of any decent unit test framework called <em>row tests. </em>With this approach we can, at the very least, reduce the number of asserts we have to write for each unit test.<em>&#160;</em></p>

<pre class="csharpcode">[TestFixture]
<span class="kwrd">public</span> <span class="kwrd">class</span> When_validating_an_email__approach_2
    : ContextSpecification&lt;EmailSpecification&gt;
{
    <span class="kwrd">protected</span> <span class="kwrd">override</span> EmailSpecification Create_subject_under_test()
    {
        <span class="kwrd">return</span> <span class="kwrd">new</span> EmailSpecification();
    }

    [RowTest]
    [Row(<span class="str">&quot;one2@three.com&quot;</span>)]
    [Row(<span class="str">&quot;one@two3.com&quot;</span>)]
    <span class="kwrd">public</span> <span class="kwrd">void</span> ShouldBeSatisfied(String email)
    {
        Assert.That(SUT.IsSatisfiedBy(email));
    }

    [RowTest]
    [Row(<span class="str">&quot;one_two.com&quot;</span>)]
    [Row(<span class="str">&quot;one_two@&quot;</span>)]
    <span class="kwrd">public</span> <span class="kwrd">void</span> ShouldNotBeSatisfied(String email)
    {
        Assert.That(SUT.IsSatisfiedBy(email), Is.False);
    }
}</pre>
<style type="text/css">

.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>Notice that I explicitly called both of these approaches <em>unit tests</em> as they don’t have much to do with BDD in my opinion. I’m not saying that using regular unit tests is a bad thing, but with&#160; behavior-driven development context is king. So these unit tests are perfect examples of ‘<a href="http://elegantcode.com/2008/12/30/dont-sell-out-on-the-context-dude/">context betrayal</a>’ when following the BDD approach. </p>

<p>Lets see what MSpec can bring to the table for these kind of scenarios:</p>

<pre class="csharpcode">[Subject(<span class="kwrd">typeof</span>(EmailSpecification), <span class="str">&quot;is satisfied&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_validating_an_email_address_with_a_number_in_the_local_part
    : email_specification_specs
{
    Establish context = () =&gt;
        EmailAddress = <span class="str">&quot;one2@three.com&quot;</span>;

    Behaves_like&lt;SatisfiedSpecificationBehavior&gt; a_satisfied_specification;
}

[Subject(<span class="kwrd">typeof</span>(EmailSpecification), <span class="str">&quot;is satisfied&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_validating_an_email_address_with_a_number_in_the_domain_name
    : email_specification_specs
{
    Establish context = () =&gt;
        EmailAddress = <span class="str">&quot;one@two3.com&quot;</span>;

    Behaves_like&lt;SatisfiedSpecificationBehavior&gt; a_satisfied_specification;
}

[Subject(<span class="kwrd">typeof</span>(EmailSpecification), <span class="str">&quot;is satisfied&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_validating_an_email_address_without_an_At_sign
    : email_specification_specs
{
    Establish context = () =&gt;
        EmailAddress = <span class="str">&quot;one_two.com&quot;</span>;

    Behaves_like&lt;UnsatisfiedSpecificationBehavior&gt; an_unsatisfied_specification;
}

[Subject(<span class="kwrd">typeof</span>(EmailSpecification), <span class="str">&quot;is satisfied&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_validating_an_email_address_without_a_domain
    : email_specification_specs
{
    Establish context = () =&gt;
        EmailAddress = <span class="str">&quot;one_two@&quot;</span>;

    Behaves_like&lt;UnsatisfiedSpecificationBehavior&gt; an_unsatisfied_specification;
}</pre>
<style type="text/css">

.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>In order to escape ‘context betrayal’, we’ve split up every context into a separate context/specification. In order to reduce the amount of effort caused by duplicate code, we stripped the context setup to the bare minimum (just a particular e-mail address in this case). The observations are isolated into MSpec behaviors which provides a very readable description of their outcome. Lets take a look at what is needed in order to get these <em>behaviors</em> to work.</p>

<p>But first lets take at look at the abstract base class that we’ve used for the context/specifications we’ve just shown.</p>

<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">abstract</span> <span class="kwrd">class</span> email_specification_specs
{
    Establish context = () =&gt;
    {
        SUT = <span class="kwrd">new</span> EmailSpecification();
    };

    Because of = () =&gt;
        Result = SUT.IsSatisfiedBy(EmailAddress);

    <span class="kwrd">protected</span> <span class="kwrd">static</span> Boolean Result;
    <span class="kwrd">protected</span> <span class="kwrd">static</span> String EmailAddress { get; set; }
    <span class="kwrd">protected</span> <span class="kwrd">static</span> EmailSpecification SUT { get; set; }
}</pre>

<p><style type="text/css">

.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style></p>

<p>&#160;</p>

<p>We abstracted as much as possible into this base class in order to remove duplication in the context/specifications. The creation of the subject-under-test and the calling of its <em>IsSatisfiedBy</em> method, but the important one is the declaration of the <em>Result</em> field. This field contains the outcome of the <em>IsSatisfiedBy</em> method. Finally, lets have a look at the behaviors themselves:</p>

<pre class="csharpcode">[Behaviors]
<span class="kwrd">public</span> <span class="kwrd">class</span> SatisfiedSpecificationBehavior
{
    <span class="kwrd">protected</span> <span class="kwrd">static</span> Boolean Result;
    
    It should_satisfy_the_specification = () =&gt;
        Result.ShouldBeTrue();
}

[Behaviors]
<span class="kwrd">public</span> <span class="kwrd">class</span> UnsatisfiedSpecificationBehavior
{
    <span class="kwrd">protected</span> <span class="kwrd">static</span> Boolean Result;

    It should_not_satisfy_the_specification = () =&gt;
        Result.ShouldBeFalse();
}</pre>
<style type="text/css">

.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>In order to create an MSpec behavior, we just have to create a separate class that we decorate with the <em>Behaviors</em> attribute. Also notice that we have the same declaration of the <em>Result</em> field. MSpec ensures that this field gets initialized with the value of the other <em>Result</em> field that is set in the base class of the context/specifications. Note that you don’t necessarily need to put this field in a base class. You can have that field in every context/specification if you’d like (not sure why) as long as the names match with the fields used in the defined behaviors.</p>

<p>I personally like the way how the MSpec contributors tried to solve testing the same logic with different input patterns and the syntax they provided to back this up.&#160;&#160; </p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/02/26/behaviors-with-mspec/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>MSpec and Auto Mocking</title>
		<link>http://elegantcode.com/2010/02/23/mspec-and-auto-mocking/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=mspec-and-auto-mocking</link>
		<comments>http://elegantcode.com/2010/02/23/mspec-and-auto-mocking/#comments</comments>
		<pubDate>Tue, 23 Feb 2010 20:38:54 +0000</pubDate>
		<dc:creator>Jan Van Ryswyck</dc:creator>
				<category><![CDATA[BDD]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/02/23/mspec-and-auto-mocking/</guid>
		<description><![CDATA[In my previous post, I explained how to get started with Machine.Specifications (or MSpec for short) and showed you how the syntax for context/specifications looks like when using this BDD framework. For this post, I want to show you how to use an auto mocking container (we’ll be using the one provided by StructureMap off [...]]]></description>
			<content:encoded><![CDATA[<p>In my <a href="http://elegantcode.com/2010/02/19/getting-started-with-machine-specifications-mspec/">previous post</a>, I explained how to get started with <a href="http://github.com/machine/machine.specifications">Machine.Specifications</a> (or MSpec for short) and showed you how the syntax for context/specifications looks like when using this BDD framework. For this post, I want to show you how to use an <a href="http://vanryswyckjan.blogspot.com/2008/01/automocking-container.html">auto mocking container</a> (we’ll be using the one provided by StructureMap off course).</p>  <p>We’ll use the same example as the one used in the previous post, but now we’ll deal with the message handler that makes a particular customer preferred.</p> <style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>  <pre class="csharpcode"><span class="rem">//</span>
<span class="rem">// Subject under test</span>
<span class="rem">//</span>
<span class="kwrd">public</span> <span class="kwrd">class</span> MakeCustomerPreferredMessageHandler
{
    <span class="kwrd">private</span> <span class="kwrd">readonly</span> ICustomerRepository&lt;ICanMakeCustomerPreferred&gt; _repository;

    <span class="kwrd">public</span> MakeCustomerPreferredMessageHandler(
        ICustomerRepository&lt;ICanMakeCustomerPreferred&gt; repository)
    {
        _repository = repository;
    }

    <span class="kwrd">public</span> <span class="kwrd">void</span> Handle(MakeCustomerPreferredMessage message)
    {
        var customer = _repository.Get(message.CustomerId);
        <span class="kwrd">if</span>(<span class="kwrd">null</span> == customer)
            <span class="kwrd">throw</span> <span class="kwrd">new</span> InvalidOperationException(
                <span class="str">&quot;No customer for specified identifier&quot;</span>);
        
        customer.MakePreferred();
        _repository.Save(customer);
    }
}</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>The <em>Customer</em> class implements a ‘<a href="http://martinfowler.com/bliki/RoleInterface.html">role interface’</a> called <em>ICanMakeCustomerPreferred</em>. We retrieve a customer from the repository and make it preferred. We throw an exception in case the customer cannot be found in the data store.</p>

<p>Here are the context/specifications for this easy example:</p>

<pre class="csharpcode">[Subject(<span class="str">&quot;Making a customer preferred&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_making_a_customer_preferred
    : context_specification&lt;MakeCustomerPreferredMessageHandler&gt;
{
    Establish context = () =&gt;
    {
        _message = <span class="kwrd">new</span> MakeCustomerPreferredMessage { CustomerId = 6412 };

        Repository.Stub(repository =&gt; repository.Get(_message.CustomerId))
            .Return(Customer);
    };

    Because of = () =&gt; 
        SUT.Handle(_message);
    
    It should_mark_the_customer_as_preferred = () =&gt;
        Customer.AssertWasCalled(customer =&gt; customer.MakePreferred());

    It should_save_the_customer_in_the_repository = () =&gt;
        Repository.AssertWasCalled(repository =&gt; repository.Save(Customer));

    <span class="kwrd">private</span> <span class="kwrd">static</span> ICanMakeCustomerPreferred Customer
    {
        get { <span class="kwrd">return</span> Dependency&lt;ICanMakeCustomerPreferred&gt;(); }
    }

    <span class="kwrd">private</span> <span class="kwrd">static</span> ICustomerRepository&lt;ICanMakeCustomerPreferred&gt; Repository
    {
        get { <span class="kwrd">return</span> Dependency&lt;ICustomerRepository&lt;ICanMakeCustomerPreferred&gt;&gt;(); }
    }

    <span class="kwrd">private</span> <span class="kwrd">static</span> MakeCustomerPreferredMessage _message;
}

[Subject(<span class="str">&quot;Making a customer preferred&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_making_an_unexisting_customer_preferred
    : context_specification&lt;MakeCustomerPreferredMessageHandler&gt;
{
    Establish context = () =&gt;   
    {
        _message = <span class="kwrd">new</span> MakeCustomerPreferredMessage() { CustomerId = 61544 };

        Dependency&lt;ICustomerRepository&lt;ICanMakeCustomerPreferred&gt;&gt;()
            .Stub(repository =&gt; repository.Get(_message.CustomerId))
            .Return(<span class="kwrd">null</span>);
    };

    Because of = () =&gt;
        _resultingException = Catch.Exception(() =&gt; SUT.Handle(_message));

    It should_result_in_an_error = () =&gt;
        _resultingException.ShouldBeOfType&lt;InvalidOperationException&gt;();

    <span class="kwrd">private</span> <span class="kwrd">static</span> MakeCustomerPreferredMessage _message;
    <span class="kwrd">private</span> <span class="kwrd">static</span> Exception _resultingException;
}</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>I want to point out that all fields and properties are made static. This is needed so that the anonymous methods can access them. I’m also using a base class for these specifications which I’ll show next. This base class uses an auto mocking container for providing the requested mocks and stubs through the <em>Dependency</em> and <em>Stub</em> methods. </p>

<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">abstract</span> <span class="kwrd">class</span> context_specification&lt;TSubjectUnderTest&gt;
    <span class="kwrd">where</span> TSubjectUnderTest : <span class="kwrd">class</span>
{
    <span class="kwrd">private</span> <span class="kwrd">static</span> IAutoMockingContainer&lt;TSubjectUnderTest&gt; _autoMockingContainer;
    <span class="kwrd">protected</span> <span class="kwrd">static</span> TSubjectUnderTest SUT { get; set; }

    Establish context = () =&gt;
    {
        _autoMockingContainer = <span class="kwrd">new</span> StructureMapAMC&lt;TSubjectUnderTest&gt;();
        SUT = _autoMockingContainer.Create();     
    };
    
    Cleanup stuff = () =&gt; 
    {
        SUT = <span class="kwrd">null</span>;
        _autoMockingContainer = <span class="kwrd">null</span>;
    };

    <span class="kwrd">protected</span> <span class="kwrd">static</span> TDependency Dependency&lt;TDependency&gt;()
        <span class="kwrd">where</span> TDependency : <span class="kwrd">class</span>
    {
        <span class="kwrd">return</span> _autoMockingContainer.GetMock&lt;TDependency&gt;();
    }

    <span class="kwrd">protected</span> <span class="kwrd">static</span> TStub Stub&lt;TStub&gt;()
        <span class="kwrd">where</span> TStub : <span class="kwrd">class</span>
    {
        <span class="kwrd">return</span> _autoMockingContainer.GetStub&lt;TStub&gt;();
    }
}

<span class="kwrd">public</span> <span class="kwrd">interface</span> IAutoMockingContainer&lt;TSubject&gt;
    <span class="kwrd">where</span> TSubject : <span class="kwrd">class</span>
{
    TSubject Create();
    TMock GetMock&lt;TMock&gt;() <span class="kwrd">where</span> TMock : <span class="kwrd">class</span>;
    TStub GetStub&lt;TStub&gt;() <span class="kwrd">where</span> TStub : <span class="kwrd">class</span>;
}

<span class="kwrd">public</span> <span class="kwrd">class</span> StructureMapAMC&lt;TSubject&gt; 
    : IAutoMockingContainer&lt;TSubject&gt;
    <span class="kwrd">where</span> TSubject : <span class="kwrd">class</span>
{
    <span class="kwrd">private</span> <span class="kwrd">readonly</span> RhinoAutoMocker&lt;TSubject&gt; _rhinoAutoMocker;

    <span class="kwrd">public</span> StructureMapAMC()
    {
        _rhinoAutoMocker = 
            <span class="kwrd">new</span> RhinoAutoMocker&lt;TSubject&gt;(MockMode.AAA);
    }

    <span class="kwrd">public</span> TSubject Create()
    {
        <span class="kwrd">return</span> _rhinoAutoMocker.ClassUnderTest;
    }

    <span class="kwrd">public</span> TMock GetMock&lt;TMock&gt;() 
        <span class="kwrd">where</span> TMock : <span class="kwrd">class</span>
    {
        <span class="kwrd">return</span> GetDependency&lt;TMock&gt;();
    }

    <span class="kwrd">public</span> TStub GetStub&lt;TStub&gt;() 
        <span class="kwrd">where</span> TStub : <span class="kwrd">class</span>
    {
        <span class="kwrd">return</span> GetDependency&lt;TStub&gt;();
    }

    <span class="kwrd">private</span> TDependency GetDependency&lt;TDependency&gt;() 
        <span class="kwrd">where</span> TDependency : <span class="kwrd">class</span>
    {
        <span class="kwrd">return</span> _rhinoAutoMocker.Get&lt;TDependency&gt;();
    }
}</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>Notice that I’m using the <em>Establish</em> and <em>Cleanup</em> delegates in the <em>context_specification</em> base class. This doesn’t prevent that these can be used again in derived context/specifications. MSpec ensures that the anonymous methods are called in the right order. This means that the <em>Establish</em> method of the base class is called before the <em>Establish</em> method of the derived context/specifications.&#160;&#160;&#160;&#160; </p>

<p>Absolutely no rocket science here, but I figured it might come in handy when you need it. For the next post I’ll try to demonstrate how to deal with reusable behaviors.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/02/23/mspec-and-auto-mocking/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Getting Started With Machine.Specifications (MSpec)</title>
		<link>http://elegantcode.com/2010/02/19/getting-started-with-machine-specifications-mspec/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=getting-started-with-machine-specifications-mspec</link>
		<comments>http://elegantcode.com/2010/02/19/getting-started-with-machine-specifications-mspec/#comments</comments>
		<pubDate>Fri, 19 Feb 2010 21:34:17 +0000</pubDate>
		<dc:creator>Jan Van Ryswyck</dc:creator>
				<category><![CDATA[BDD]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/02/19/getting-started-with-machine-specifications-mspec/</guid>
		<description><![CDATA[Its been a while since I evaluated and evolved my approach to BDD. The way I’ve been doing BDD up until now is described in this blog post which goes way back to 2008. Everyone has kind of their own style nowadays. Below you can find the code of two context/specifications for a method named [...]]]></description>
			<content:encoded><![CDATA[<p>Its been a while since I evaluated and evolved my approach to BDD. The way I’ve been doing BDD up until now is described in <a href="http://elegantcode.com/2008/10/25/refining-contextspecification-bdd-using-rhino-mocks-35/">this blog post</a> which goes way back to 2008. Everyone has kind of their own style nowadays. Below you can find the code of two context/specifications for a method named <em>MakePreferred</em> on a <em>Customer </em>class. This simple example clarifies the style that I’ve been following up until now.</p> <style type="text/css">


.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style><style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>  <pre class="csharpcode">[TestFixture]
<span class="kwrd">public</span> <span class="kwrd">class</span> When_making_a_regular_customer_preferred
    : ContextSpecification&lt;Customer&gt;
{
    <span class="kwrd">protected</span> <span class="kwrd">override</span> Customer Create_subject_under_test()
    {
        <span class="kwrd">return</span> <span class="kwrd">new</span> Customer(<span class="kwrd">new</span>[] { _order });
    }

    <span class="kwrd">protected</span> <span class="kwrd">override</span> <span class="kwrd">void</span> Establish_context()
    {
        _order = <span class="kwrd">new</span> Order(<span class="kwrd">new</span>[] { <span class="kwrd">new</span> OrderItem(12), 
                                   <span class="kwrd">new</span> OrderItem(16) });
                                   
        _totalAmountWithoutDiscount = _order.TotalAmount;
    }

    <span class="kwrd">protected</span> <span class="kwrd">override</span> <span class="kwrd">void</span> Because()
    {
        SUT.MakePreferred();
    }

    [Test]
    <span class="kwrd">public</span> <span class="kwrd">void</span> Then_the_customer_should_be_marked_as_preferred()
    {
        SUT.IsPreferred.ShouldBeTrue();
    }

    [Test]
    <span class="kwrd">public</span> <span class="kwrd">void</span> Then_a_ten_percent_discount_should_be_applied_to_all_outstanding_orders()
    {
        _order.TotalAmount.ShouldBeEqualTo(
            _totalAmountWithoutDiscount * 0.9);
    }

    <span class="kwrd">private</span> Order _order;
    <span class="kwrd">private</span> Double _totalAmountWithoutDiscount;
}

[TestFixture]
<span class="kwrd">public</span> <span class="kwrd">class</span> When_making_a_preferred_customer_preferred
    : ContextSpecification&lt;Customer&gt;
{
    <span class="kwrd">protected</span> <span class="kwrd">override</span> Customer Create_subject_under_test()
    {
        var customer = <span class="kwrd">new</span> Customer(<span class="kwrd">new</span>[] { _order });
        customer.MakePreferred();
        <span class="kwrd">return</span> customer;
    }

    <span class="kwrd">protected</span> <span class="kwrd">override</span> <span class="kwrd">void</span> Establish_context()
    {
        _order = <span class="kwrd">new</span> Order(<span class="kwrd">new</span>[] { <span class="kwrd">new</span> OrderItem(12), 
                                   <span class="kwrd">new</span> OrderItem(16) });
        _totalAmountWithoutDiscount = _order.TotalAmount;
    }

    <span class="kwrd">protected</span> <span class="kwrd">override</span> <span class="kwrd">void</span> Because()
    {
        SUT.MakePreferred();
    }

    [Test]
    <span class="kwrd">public</span> <span class="kwrd">void</span> Then_no_additional_discount_should_be_applied_to_the_outstanding_orders()
    {
        _order.TotalAmount.ShouldNotBeEqualTo(
            _totalAmountWithoutDiscount * 0.81);
    }

    <span class="kwrd">private</span> Order _order;
    <span class="kwrd">private</span> Double _totalAmountWithoutDiscount;
}

<span class="rem">//</span>
<span class="rem">// Subject under test</span>
<span class="rem">//</span>
<span class="kwrd">public</span> <span class="kwrd">class</span> Customer
{
    <span class="kwrd">private</span> <span class="kwrd">readonly</span> List&lt;Order&gt; _orders;
    <span class="kwrd">public</span> Boolean IsPreferred { get; <span class="kwrd">private</span> set; }

    <span class="kwrd">public</span> Customer(IEnumerable&lt;Order&gt; orders)
    {
        _orders = <span class="kwrd">new</span> List&lt;Order&gt;(orders);
    }

    <span class="kwrd">public</span> <span class="kwrd">void</span> MakePreferred()
    {
        <span class="kwrd">if</span>(IsPreferred)    
            <span class="kwrd">return</span>;
    
        IsPreferred = <span class="kwrd">true</span>;
        _orders.ForEach(order =&gt; order.ApplyDiscount(10));
    }
}</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>The bottom line of this example is that preferred customers get a 10 percent discount. Customers that are already preferred do not get an additional discount or otherwise we’re out of business ;-). </p>

<p>I’ve been pretty happy with this approach so far, although sometimes there were some quirks associated with this. So it was time for me to look beyond the horizon again, trying to look for ways to improve. </p>

<p><a href="http://github.com/machine/machine.specifications">Machine.Specifications</a> or MSpec for short is something that has been on my ‘cool-things-to-learn-list’ for quite some time now. As you will see later in this post, the syntax is a bit different as one would come to expect from a context/specification framework that targets the C# programming language. Its seems to be heavily inspired by Scott Bellware’s <a href="http://code.google.com/p/specunit-net/">SpecUnit framework</a> and <a href="http://rspec.info/">RSpec</a>.</p>

<p>Lets see how to set things up first. </p>

<p>The most obvious starting point is downloading the bits and bytes. You can grab the <a href="http://github.com/machine/machine.specifications">source code</a> from GitHub and build it or you can wuss out like I did and get the latest build from the <a href="http://teamcity.codebetter.com/login.html">TeamCity.CodeBetter.com</a> builder server (you can log on as a guest and search the artifacts for a latest build).&#160; </p>

<p>When you’re heavily addicted to <a href="http://www.testdriven.net/">TestDriven.NET</a> like I am, then its possible to keep using this wonderful Visual Studio add-in for running MSpec context/specifications. Just create a directory named <em>Machine.Specifications</em> in {$Program_Files}\TestDriven.NET 2.0 and copy the following files:</p>

<ul>
  <li>Machine.Specifications.dll</li>

  <li>Machine.Specifications.TDNetRunner.dll</li>

  <li>InstallTDNetRunner.bat</li>
</ul>

<ul>Run the InstallTDNetRunner.bat file and you’re able to run all MSpec context/specifications using TestDriven.NET.</ul>

<p>I also strongly encourage you to install the plugin for the Resharper test runner (if only to prevent some Resharper warnings later on). First step is to add a directory named <em>Plugins</em> to the <em>Bin</em> directory of Resharper ({$Program_Files}\JetBrains\ReSharper\v4.5\Bin\). Then create a directory named <em>Machine.Specifications</em> in the <em>Plugins</em> directory you just created and copy the following files:</p>

<ul>
  <li>Machine.Specifications.dll</li>

  <li>Machine.Specifications.ReSharperRunner.4.5.dll</li>

  <li>InstallResharperRunner.4.5.bat</li>
</ul>

<p>Run the InstallResharperRunner.4.5.bat file and you’re also able to run MSpec context/specifications using the Resharper test runner.</p>

<p>I’m not going to put this off any longer. Lets look at the code of the context/specifications shown earlier but completely revamped using the MSpec syntax:</p>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<pre class="csharpcode">[Subject(<span class="str">&quot;Making a customer preferred&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_a_regular_customer_is_made_preferred 
{
    Establish context = () =&gt;
    {
        _order = <span class="kwrd">new</span> Order(<span class="kwrd">new</span>[] { <span class="kwrd">new</span> OrderItem(12), 
                                   <span class="kwrd">new</span> OrderItem(16) });
        _totalAmountWithoutDiscount = _order.TotalAmount;

        SUT = <span class="kwrd">new</span> Customer(<span class="kwrd">new</span>[] { _order });
    };

    Because of = () =&gt; 
        SUT.MakePreferred();

    It should_mark_the_customer_as_preferred = () =&gt;
        SUT.IsPreferred.ShouldBeTrue();
        
    It should_apply_a_ten_percent_discount_to_all_outstanding_orders = () =&gt;
        _order.TotalAmount.ShouldEqual(_totalAmountWithoutDiscount * 0.9);      

    <span class="kwrd">private</span> <span class="kwrd">static</span> Customer SUT;
    
    <span class="kwrd">private</span> <span class="kwrd">static</span> Order _order;
    <span class="kwrd">private</span> <span class="kwrd">static</span> Double _totalAmountWithoutDiscount;
}

[Subject(<span class="str">&quot;Making a customer preferred&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_a_preferred_customer_is_made_preferred
{
    Establish context = () =&gt;
    {
        _order = <span class="kwrd">new</span> Order(<span class="kwrd">new</span>[] { <span class="kwrd">new</span> OrderItem(12), 
                                   <span class="kwrd">new</span> OrderItem(16) });
        _totalAmountWithoutDiscount = _order.TotalAmount;

        SUT = <span class="kwrd">new</span> Customer(<span class="kwrd">new</span>[] { _order });
        SUT.MakePreferred();
    };

    Because of = () =&gt;
        SUT.MakePreferred();

    It should_apply_no_additional_discount_to_the_outstanding_orders = () =&gt; 
        _order.TotalAmount.ShouldNotEqual(_totalAmountWithoutDiscount * 0.81);

    <span class="kwrd">private</span> <span class="kwrd">static</span> Customer SUT;

    <span class="kwrd">private</span> <span class="kwrd">static</span> Order _order;
    <span class="kwrd">private</span> <span class="kwrd">static</span> Double _totalAmountWithoutDiscount;
}</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>I warned you about the syntax, didn’t I :-). It only took me a couple of seconds to get used to this syntax but now I’m completely hooked. Instead of using methods and attributes, MSpec utilizes delegates and anonymous methods. But there’s more. </p>

<p>When using <a href="http://www.nunit.com/index.php">NUnit</a> for writing context/ specifications, the <em>Establish_context</em> and <em>Because</em> methods of the example shown earlier is executed before every observation (test). With MSpec, the <em>Establish</em> and <em>Because</em> anonymous methods are executed only once for every context no matter how many observations a particular context class contains. Big difference? Well, at first glance not but on second hand it does make <a href="http://elegantcode.com/2008/12/30/dont-sell-out-on-the-context-dude/">selling out on the context</a> a bit more difficult as it will probably blow up in your face sooner than later. You can force MSpec to execute the <em>Establish</em> and <em>Because</em> anonymous methods before every observation by applying the <em>SetupForEachSpecification</em> attribute to the context class, but I strongly encourage you to stay away from that unless absolutely needed.</p>

<p>Also notice that the fields in the contexts are now all static. This is needed so that the anonymous methods can access those.&#160;&#160;&#160;&#160;&#160; </p>

<p>Running these context/specifications using TestDriven.NET yields the following output in the output window of Visual Studio:</p>

<blockquote>
  <p><font face="Arial">Making a customer preferred, when a regular customer is made preferred
      <br />» should mark the customer as preferred

      <br />» should apply a ten percent discount to all outstanding orders</font></p>

  <p><font face="Arial">Making a customer preferred, when a preferred customer is made preferred
      <br />» should apply no additional discount to the outstanding orders</font></p>
</blockquote>

<p>What’s not to like? Well, the only downside so far is that Resharper was giving me some warnings about classes and fields not being used etc. … . Many of those warnings disappeared by registering the MSpec plugin for the Resharper test runner as I explained earlier.</p>

<p>So far, so good. I’ve got two more posts coming up on MSpec, so stay tuned.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/02/19/getting-started-with-machine-specifications-mspec/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Unity/Moq &#8211; AutoMocker or AutoMockingContainer</title>
		<link>http://elegantcode.com/2010/01/03/unitymoq-automocker-or-automockingcontainer/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=unitymoq-automocker-or-automockingcontainer</link>
		<comments>http://elegantcode.com/2010/01/03/unitymoq-automocker-or-automockingcontainer/#comments</comments>
		<pubDate>Sun, 03 Jan 2010 16:52:33 +0000</pubDate>
		<dc:creator>Jason Jarrett</dc:creator>
				<category><![CDATA[TDD]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Tools and Utilities]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/01/03/unitymoq-automocker-or-automockingcontainer/</guid>
		<description><![CDATA[What is an Auto Mocking Container? This post started to get a little long, so I won’t re-explain the concept. Joshua Flanagan wrote a nice overview at his Los Techies blog: Auto mocking Explained. My post is mainly here to describe the Unity version of an automocking container I threw together. In Jan 2009 I [...]]]></description>
			<content:encoded><![CDATA[<h4>What is an Auto Mocking Container?</h4>  <p>This post started to get a little long, so I won’t re-explain the concept.</p>  <p><a href="http://www.lostechies.com/blogs/joshuaflanagan/default.aspx">Joshua Flanagan</a> wrote a nice overview at his <a href="http://www.lostechies.com/">Los Techies</a> blog: <a href="http://www.lostechies.com/blogs/joshuaflanagan/archive/2009/02/03/auto-mocking-explained.aspx"><strong>Auto mocking Explained</strong></a>.</p>  <p>My post is mainly here to describe the Unity version of an automocking container I threw together.</p>  <h4>In Jan 2009 I blogged about my initial version of the Unity AutoMocker - Why am I blogging about it again?</h4>  <p>I originally wrote the AutoMocker for the Unity container a year ago (Jan 2009, in Silverlight), and finally got around to placing the code up in the <a href="http://code.google.com/p/moq-contrib/">moq-contrib</a> project in June of 2009.</p>  <p>I’m writing another post today in hopes to:</p>  <ol>   <li>Get some feedback on how this little snippet of code should continue. </li>    <li>Give a little more how-to/example code </li>    <li>Describe some updates I made since I originally created it.&#160; </li> </ol>  <h4>Where can I get it?</h4>  <p><strong>This is one part where I’d appreciate some feedback.</strong></p>  <p>I have two slightly different versions out there (currently).</p>  <p>I have one version at the <a href="http://code.google.com/p/elegantcode/source/browse/#svn/trunk/Coders/JasonJarrett/UnityAutoMocker">ElegantCode</a> repository where I was working on it, and the other I threw up at <a href="http://code.google.com/p/moq-contrib/">moq-contrib</a>.</p>  <p>The core of the UnityAutoMockContainer is the same in both places, it’s how the tests are separated out that differ.</p>  <p>In the <a href="http://code.google.com/p/elegantcode/source/browse/#svn/trunk/Coders/JasonJarrett/UnityAutoMocker">ElegantCode repository</a> it’s an all in one self contained single file (that you can copy into your own test project(s)). You can then setup a single test in your own testing framework that runs all internal automocker tests (in case you need to modify it yourself, and don’t want to break any existing functionality). EX: test</p>  <pre class="brush: csharp;">[Test]
public void Should_run_all_UnityAutoMockContainer_internal_tests()
{
    Moq.AutoMocking.SelfTesting.UnityAutoMockContainerFixture
        .RunAllTests(Console.WriteLine);
}</pre>

<p>I kind of like this format as it makes it easy to port between test libraries. Can’t say I like having the tests in the same file as the core, but it certainly is not a large chunk of code (so far) so it’s relatively small to maintain and definitely easier to manage as a single .cs file than another assembly (which would have to be version dependent on both Unity and Moq).</p>

<p>The <a href="http://code.google.com/p/moq-contrib/">moq-contrib</a> is definitely where I think this helper should end up (and it is there). I just happened to break the tests out into the Silverlight test project and the core is alone in a file. </p>

<p>It’s current state isn’t as easy to copy to a test library (Silverlight/Desktop/Unity 1.2/Unity 2.0) as the one at <a href="http://elegantcode.com/">ElegantCode</a>. <strong>What does anyone think?</strong> Should I put them all together in one file?</p>

<p>However it ends up (1. all in one file or two (1 test) (1 core)) it will continue to be maintained on the <a href="http://code.google.com/p/moq-contrib/">moq-contrib</a> project.</p>

<h4>What is the high level API of the container?</h4>

<p>It’s pretty simple, (currently) there are four methods on the container.</p>

<p><strong>Two for registering items with the container</strong>. Say you want to register an already created instance, or say you want to map an interface to a concrete class and _not_ have the container generate mocks automatically for special cases. </p>

<p>And <strong>two for pulling items out of the container</strong>. Whether you want a instance of T or a Mock&lt;T&gt;, it gives you ways to retrieve both.</p>

<blockquote>
  <p><a href="http://elegantcode.com/wp-content/uploads/2010/01/image.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://elegantcode.com/wp-content/uploads/2010/01/image_thumb.png" width="396" height="106" /></a> </p>
</blockquote>

<h4>How can I setup my own registrations with the container? </h4>

<p>Say I don’t want to have the container generate mocks for specific items and I want to supply specific configuration to the UnityContainer.</p>

<blockquote>
  <p>public UnityAutoMockContainer RegisterInstance&lt;TService&gt;(TService instance)</p>

  <p>public UnityAutoMockContainer Register&lt;TService, TImplementation&gt;() 
    <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; where TImplementation : TService</p>
</blockquote>

<p><strong>Note</strong>: both of these registration methods return the container itself so you can fluently stack registration. <strong>EX:</strong></p>

<pre class="brush: csharp;">AutoMockContainer
    .Register&lt;IServiceA, ServiceA&gt;()
    .Register&lt;IServiceB, ServiceB&gt;();</pre>

<p><strong>Let me know</strong>: I haven’t tested or played around with how this automocking container deals with any container specific xml configuration… So although I don’t think you should probably have that in a test assembly (stuff happens). Let me know if there are any issues.</p>

<h4>How do I get items out of the container?</h4>

<p>First is the Resolve&lt;T&gt;(). It will pull an item T out of the container. (Creating it if not already existing)</p>

<blockquote>
  <p>public T Resolve&lt;T&gt;()</p>
</blockquote>

<p>When T is an interface Resolve&lt;T&gt; (unless you setup registration specifically with the container) should return basically “(new Mock&lt;T&gt;()).Object”</p>

<p>When T is a concrete Class, the container should return an instance of T and any of it’s dependencies will be satisfied by mocks. (Note that T will not be any sort of mocked instance of T, unless you used the GetMock&lt;T&gt; as described below first)</p>

<blockquote>
  <p>public Mock&lt;T&gt; GetMock&lt;T&gt;() where T : class</p>
</blockquote>

<p>When T is an interface GetMock&lt;T&gt; should return basically “(new Mock&lt;T&gt;())” </p>

<p>When T is a concrete Class, the container should return a new Mock&lt;T&gt;() and any of it’s dependencies will be satisfied by mocks.</p>

<h4>How do I use the UnityAutoMockContainer?</h4>

<p>It’s pretty basic, you first create an instance of the UnityAutoMockContainer, and from there you can ask it for mocks of an (Interface, Class, or Abstract Class).</p>

<p>If you request an instance of a concrete class, or abstract class, the UnityAutoMockContainer will stuff mocks in for any constructor dependencies of your concrete class (if it can). You can then request from the container those same dependencies one at a time and either apply mocking setups or verifications.</p>

<blockquote>
  <p><strong>NOTE:</strong> Anything the container creates will live as a singleton instance in the container. So any other requests from the container will always return the originally created instance. Therefore, each distinct scenario in a test suite should have their own instances of the container.</p>
</blockquote>

<p>Below his an example of how you can leverage the container in some tests. Given this base fixture class…</p>

<pre class="brush: csharp;">public class FixtureBase
{
    private readonly UnityAutoMockContainer _autoMockContainer = new UnityAutoMockContainer();

    protected UnityAutoMockContainer AutoMockContainer
    {
        get { return _autoMockContainer; }
    }

    [TestFixtureSetUp]
    public void SetupContext_ALL()
    {
        Before_all_tests();
        Because();
    }

    [TestFixtureTearDown]
    public void TearDownContext_ALL()
    {
        After_all_tests();
    }

    protected virtual void Before_all_tests()
    {
    }

    protected virtual void Because()
    {
    }

    protected virtual void After_all_tests()
    {
    }
}</pre>

<p>If I were given the following system to test.</p>

<pre class="brush: csharp;">public interface IServiceA { void RunA(); }
public interface IServiceB { void RunB(); }

public class TestComponent
{
    public TestComponent(IServiceA serviceA, IServiceB serviceB)
    {
        ServiceA = serviceA;
        ServiceB = serviceB;
    }

    public IServiceA ServiceA { get; private set; }
    public IServiceB ServiceB { get; private set; }

    public void RunAll()
    {
        if (!HowDidItGo())
            return;
        ServiceA.RunA();
        ServiceB.RunB();
    }

    public virtual bool HowDidItGo()
    {
        // some really nasty untestable code
        return true;
    }
}</pre>

<p>The below example demonstrates simply verifying some behavior on the mocked dependencies of the system under test.</p>

<pre class="brush: csharp;">[TestFixture]
public class Example__how_to_pull_items_from_the_UnityAutoMockContainer_when_verifying_behavior_after_an_action_was_taken 
    : FixtureBase
{
    private TestComponent _testComponent;

    protected override void Before_all_tests()
    {
        base.Before_all_tests();
        _testComponent = AutoMockContainer.Resolve&lt;TestComponent&gt;();
    }

    protected override void Because()
    {
        _testComponent.RunAll();
    }

    [Test]
    public void Should_run_ServiceA_RunA()
    {
        AutoMockContainer
            .GetMock&lt;IServiceA&gt;()
            .Verify(v =&gt; v.RunA(), Times.Once());
    }

    [Test]
    public void Should_run_ServiceB_RunB()
    {
        AutoMockContainer
            .GetMock&lt;IServiceB&gt;()
            .Verify(v =&gt; v.RunB(), Times.Once());
    }
}</pre>

<p>Next, you may have noticed that the system under test had a complicated internal method (that may not necessarily be testable). You can use the AutoMocker to create the system under test as a Mock itself, so we can override some of the behavior. Here’s how you could quickly do that. </p>

<blockquote>
  <p><strong>Aside</strong>: I’m not saying this is a good practice or aids in good component design, just saying it’s possible</p>
</blockquote>

<pre class="brush: csharp;">[TestFixture]
public class Example__how_to_use_the_UnityAutoMockContainer_to_override_a_method_on_the_SystemUnderTest_to_test_a_certain_behavior
    : FixtureBase
{

    private TestComponent _testComponent;

    protected override void Before_all_tests()
    {
        base.Before_all_tests();
        var mockTestComponent = AutoMockContainer.GetMock&lt;TestComponent&gt;();

        mockTestComponent
            .Setup(s =&gt; s.HowDidItGo())
            .Returns(false);

        _testComponent = mockTestComponent.Object;
    }

    protected override void Because()
    {
        _testComponent.RunAll();
    }

    [Test]
    public void Should_run_ServiceA_RunA()
    {
        AutoMockContainer
            .GetMock&lt;IServiceA&gt;()
            .Verify(v =&gt; v.RunA(), Times.Never());
    }

    [Test]
    public void Should_run_ServiceB_RunB()
    {
        AutoMockContainer
            .GetMock&lt;IServiceB&gt;()
            .Verify(v =&gt; v.RunB(), Times.Never());
    }
}</pre>

<p>&#160;</p>

<p>It’s amazing how much redundant test setup code this little helper has saved me in my tests. I hope others can find some use with this as well.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/01/03/unitymoq-automocker-or-automockingcontainer/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>StatLight &#8211; Goes Open Source</title>
		<link>http://elegantcode.com/2009/12/10/statlight-goes-open-source/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=statlight-goes-open-source</link>
		<comments>http://elegantcode.com/2009/12/10/statlight-goes-open-source/#comments</comments>
		<pubDate>Fri, 11 Dec 2009 03:26:55 +0000</pubDate>
		<dc:creator>Jason Jarrett</dc:creator>
				<category><![CDATA[Esoterica]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[TDD]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Tools and Utilities]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/12/10/statlight-goes-open-source/</guid>
		<description><![CDATA[Although I made a very minor attempt at making StatLight a “for-sale” product, I knew when I started that open-source was most likely going to be my long term path for StatLight. What is it? (Silverlight Testing Automation Tool) StatLight is a tool developed for automating the setup, running, and gathering results of Silverlight unit [...]]]></description>
			<content:encoded><![CDATA[Although I made a very minor attempt at making <a href="http://statlight.net" target="_blank">StatLight</a> a “for-sale” product, I knew when I started that open-source was most likely going to be my long term path for <a href="http://statlight.net" target="_blank">StatLight</a>.
<h5>What is it? (Silverlight Testing Automation Tool)</h5>
StatLight is a tool developed for automating the setup, running, and gathering results of Silverlight unit tests. StatLight helps to speed up the feedback cycles while practicing<a href="http://en.wikipedia.org/wiki/Test-driven_development"> TDD</a>/<a href="http://en.wikipedia.org/wiki/Behavior_Driven_Development">BDD</a>/(insert your test style here) during Silverlight development.
<h5>Where can I get StatLight?</h5>
<a href="http://StatLight.CodePlex.com">http://StatLight.CodePlex.com</a>
<h4>Happy Coding !!!</h4>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/12/10/statlight-goes-open-source/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Wrapping up the StructureMap Automocking Container</title>
		<link>http://elegantcode.com/2009/11/30/wrapping-up-the-structuremap-automocking-container/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=wrapping-up-the-structuremap-automocking-container</link>
		<comments>http://elegantcode.com/2009/11/30/wrapping-up-the-structuremap-automocking-container/#comments</comments>
		<pubDate>Mon, 30 Nov 2009 07:21:43 +0000</pubDate>
		<dc:creator>Richard Cirerol</dc:creator>
				<category><![CDATA[TDD]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Unit Testing]]></category>
		<category><![CDATA[StructureMap; Automocking; MSpec;]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/11/30/wrapping-up-the-structuremap-automocking-container/</guid>
		<description><![CDATA[<p><font color="#804040"><strong>UPDATE</strong>: I apologize…the original wrapper did not allow injected dependencies.&#160; I have fixed this bug and updated the sample.</font></p> I have been using StructureMap.AutoMocking with MSpec (Machine.Specifications) and Rhino.Mocks for a few months now.  Although I am very comfortable with the patterns that emerge from using the frameworks together, introducing StructureMap.Automocking to other developers is sometimes challenging. I decided to wrap the details of the container to make the intention clearer and explanation easier.  I have started using this wrapper in my projects, and have found it makes building up specifications more efficient in my daily coding.]]></description>
			<content:encoded><![CDATA[<span style="color: #804040;"><strong>UPDATE</strong>: I apologize…the original wrapper did not allow injected dependencies.  I have fixed this bug and updated the sample.</span>

I have been using StructureMap.AutoMocking with MSpec (Machine.Specifications) and Rhino.Mocks for a few months now.  Although I am very comfortable with the patterns that emerge from using the frameworks together, introducing StructureMap.Automocking to other developers is sometimes challenging.

When viewing a specification or test set up with the Rhino.Mocks or Moq automocking container, what is being tested is not readily apparent.  Once the concept is explained and demonstrated, these same developers seem to have no issue with maintaining the specifications/tests.

I decided to wrap the details of the container to make the intention clearer and explanation easier.  I have started using this wrapper in my projects, and have found it makes building up specifications more efficient in my daily coding.

Let me know whether this is useful to you, or how it could be made more useful.
<h4>The Examples</h4>
Let’s contrive an example.  We’ll say we have a coffee machine that grinds its own beans before brewing. However, the hopper has to have beans before starting the grind.  Here is the basic specification:
<table border="1" cellspacing="0" cellpadding="2" width="533">
<tbody>
<tr>
<td width="117" valign="top">Action/Behavior</td>
<td width="414" valign="top">Prepare coffee grounds for 12 cups of coffee</td>
</tr>
<tr>
<td rowspan="2" width="117" valign="top">Expectations</td>
<td width="414" valign="top">Should check that hopper has beans (mock returns true)</td>
</tr>
<tr>
<td width="414" valign="top">Because hopper has beans, should ask grinder to grind enough beans for 12 cups of coffee</td>
</tr>
</tbody></table>
We could start without a container, using Rhino.Mocks to build up the CoffeeMachine dependencies manually:
<pre class="brush: csharp;">[Subject(typeof(CoffeeMachine),"using vanilla Rhino.Mocks")]
public class Example01_when_preparing_coffee_grounds
{
    Establish context = () =&gt;
        {
            Grinder = MockRepository.GenerateMock&lt;IGrinder&gt;();
            Hopper = MockRepository.GenerateMock&lt;IHopper&gt;();
            Hopper.Expect(x =&gt; x.HasBeans()).Return(true);
            CoffeeMachine = new CoffeeMachine(Grinder, Hopper);
        };

    Because of = () =&gt; _coffeeMachine.PrepareCoffeeGrounds(12);

    It should_check_if_hopper_has_beans = () =&gt; Hopper.VerifyAllExpectations();
    It should_grind_coffee = () =&gt; Grinder.AssertWasCalled(x =&gt; x.Grind(12));

    static IGrinder Grinder;
    static IHopper Hopper;
    static CoffeeMachine CoffeeMachine;
}</pre>
For those of you not familiar with the MSpec style, please refer to the following posts:
<ul>
	<li><a href="http://blog.wekeroad.com/blog/make-bdd-your-bff-2/" target="_blank">Make BDD Your BFF</a></li>
	<li><a href="http://www.lostechies.com/blogs/seanbiefeld/archive/2009/08/25/step-by-step-to-using-machine-specifications-with-resharper.aspx" target="_blank">Step by Step to Using MSpec (Machine.Specifications) with ReSharper</a></li>
	<li><a href="http://elegantcode.com/2009/07/05/mspec-take-2/" target="_blank">MSpec - Take 2</a></li>
	<li><a href="http://marcinobel.com/index.php/mspec-bdd-installer/" target="_blank">MSpec BDD framework installer</a></li>
	<li><strong>Updated! </strong>From the <a href="http://blog.cwa.me.uk/2009/11/30/the-morning-brew-487/" target="_blank">Morning Brew #487</a>: BDD with MSpec and Rhino Auto Mocks, parts  <a href="http://telldontask.wordpress.com/2009/11/10/bdd-with-mspec-and-rhino-auto-mocks/" target="_blank">1</a>, <a href="http://telldontask.wordpress.com/2009/11/19/bdd-with-mspec-and-rhino-auto-mocks-part-2/" target="_blank">2</a>, and <a href="http://telldontask.wordpress.com/2009/11/29/bdd-with-mspec-and-rhino-auto-mocks-part-3/" target="_blank">3</a>
Here is the same specification using the RhinoAutoMocker&lt;T&gt; class provided by StructureMap.AutoMocking:</li>
</ul>
<pre class="brush: csharp;">[Subject(typeof(CoffeeMachine),"using RhinoAutoMocker&lt;CoffeeMachine&gt;")]
public class Example02_when_preparing_coffee_grounds
{
    Establish context = () =&gt;
        {
            CoffeeMachine = new RhinoAutoMocker&lt;CoffeeMachine&gt;();
            Grinder = CoffeeMachine.Get&lt;IGrinder&gt;();
            Hopper = CoffeeMachine.Get&lt;IHopper&gt;();
            Hopper.Expect(x =&gt; x.HasBeans()).Return(true);
        };

    Because of = () =&gt; v.ClassUnderTest.PrepareCoffeeGrounds(12);

    It should_check_if_hopper_has_beans = () =&gt; Hopper.VerifyAllExpectations();
    It should_grind_coffee = () =&gt; Grinder.AssertWasCalled(x =&gt; x.Grind(12));

    static IGrinder Grinder;
    static IHopper Hopper;
    static RhinoAutoMocker&lt;CoffeeMachine&gt; CoffeeMachine;
}</pre>
Although I think this looks cleaner, the initialization of CoffeeMachine causes some confusion. Unfortunately, a common question would be, “Is RhinoAutoMocker&lt;CoffeeMachine&gt; creating a mocked version of CoffeeMachine?” Well, not exactly.

RhinoAutoMocker is an implementation of the AutoMocker base class which uses StructureMap to fill dependencies.  The RhinoAutoMocker implementation of the container uses Rhino.Mocks to generate all of dependencies of the target class, whereas the MoqAutoMocker implementation uses Moq.  (Optionally, the target class can be partially mocked in order to further isolate behavior.)  We then retrieve the class under test (in this case, CoffeeMachine) and its dependencies (IGrinder and IHopper) from the container for use.

If you do not need to setup any expectations in the specification, there is no need to retrieve the dependency from the container.  However, in this specification, we need both dependencies.

<em>(Incidentally, I do not like the ClassUnderTest name.  I may end up changing this to Instance, ClassInstance, TargetClass, or something similar.  Suggestions?)</em>

By moving the initialization of the RhinoAutoMocker to a base class, some of the chattiness of the context can be hidden.
<ul>
<pre class="brush: csharp;">[Subject(typeof(CoffeeMachine),"using RhinoAutoMocker base")]
public class Example03_when_preparing_coffee_grounds : with_rhinoautomocker
{
    Establish context = () =&gt; Hopper.Expect(x =&gt; x.HasBeans()).Return(true);

    Because of = () =&gt; CoffeeMachine.ClassUnderTest.PrepareCoffeeGrounds(12);

    It should_check_if_hopper_has_beans = () =&gt; Hopper.VerifyAllExpectations();
    It should_grind_coffee = () =&gt; Grinder.AssertWasCalled(x =&gt; x.Grind(12));

}

[Subject("using RhinoAutoMocker&lt;T&gt;")]
public class with_rhinoautomocker
{
    protected static IGrinder Grinder;
    protected static IHopper Hopper;
    protected static RhinoAutoMocker&lt;CoffeeMachine&gt; CoffeeMachine;

    Establish context = () =&gt;
    {
        CoffeeMachine = new RhinoAutoMocker&lt;CoffeeMachine&gt;();
        Grinder = CoffeeMachine.Get&lt;IGrinder&gt;();
        Hopper = CoffeeMachine.Get&lt;IHopper&gt;();
    };
}</pre>
However, we are still initializing and accessing the class in a less than optimal manner.To make the usage of the container a little more seamless, I decided to create a wrapper and factory for the AutoMocker.  Setup of the dependencies and expectations are done through an AutoMocker wrapper object.  The instance of the class under test is accessed through a ClassUnderTest object.
<h4>The Result</h4>
The specification (and base class) now look like this:
<pre class="brush: csharp;">[Subject(typeof(CoffeeMachine),"using coffee machine base")]
public class Example05_when_preparing_coffee_grounds : with_coffee_machine
{
    Establish context = () =&gt; Hopper.Expect(x =&gt; x.HasBeans()).Return(true);

    Because of = () =&gt; ClassUnderTest.PrepareCoffeeGrounds(12);

    It should_check_if_hopper_has_beans = () =&gt; Hopper.VerifyAllExpectations();
    It should_grind_coffee = () =&gt; Grinder.AssertWasCalled(x =&gt; x.Grind(12));
}

[Subject("using SpecificationFor&lt;CoffeeMachine&gt;")]
public class with_coffee_machine : SpecificationFor&lt;CoffeeMachine&gt;
{
    protected static IGrinder Grinder;
    protected static IHopper Hopper;

    public with_coffee_machine
    {
        Grinder = AutoMocker.Get&lt;IGrinder&gt;();
        Hopper = AutoMocker.Get&lt;IHopper&gt;();
    }
}</pre>
As you can see, the base class inherits from SpecificationFor&lt;T&gt;.  The default constructor uses Rhino.Mocks(MockMode.AAA) to generate the dependencies.  It then exposes a AutoMocker object, which is just the wrapper around the AutoMocker base class.  It also exposes a ClassUnderTest object.  If I didn’t need to use the dependencies, I could make the <em>Example05_when_preparing_coffee_grounds</em> class inherit from <em>SpecificationFor&lt;CoffeeMachine&gt; </em>instead of inheriting from the base class<em>.</em>
<h4>The Code</h4>
I have included the code for the wrapper below for your review.  The code and six examples are available on my <a href="http://codeprogression.googlecode.com/svn/trunk/CodeProgression.Framework.Testing" target="_blank">Google code repository</a>. The repository also includes an example using the MoqAutoMocker.  All the examples have the same assertions, but are built up using the different techniques.
<pre class="brush: csharp;">namespace CodeProgression.Framework.Testing
{
    public abstract class SpecificationFor&lt;T&gt; where T: class
    {
        protected static ClassUnderTest&lt;T&gt; Factory;

        // UPDATE 2009-12-21:
        //   Moved initialization here
        protected static T ClassUnderTest {get {return AutoMocker.Instance;} }

        protected SpecificationFor()
        {
            AutoMocker = AutoMockFactory.CreateTarget&lt;T&gt;();

            // UPDATE 2009-12-21:
            //    Initializing here prevented injected dependencies!
            // AutoMocker.PartialMockTheClassUnderTest();
            // ClassUnderTest = AutoMocker.Instance;
        }

        protected SpecificationFor(AutoMockType type)
        {
            AutoMocker = AutoMockFactory.CreateTarget&lt;T&gt;(type);

            // UPDATE 2009-12-21:
            // Initializing here prevented injected dependencies!
            // AutoMocker.PartialMockTheClassUnderTest();
            // ClassUnderTest = AutoMocker.Instance;
        }
    }

    public static class AutoMockFactory
    {
        public static ClassUnderTest&lt;TARGETCLASS&gt; CreateTarget&lt;TARGETCLASS&gt;() where TARGETCLASS : class
        {
            return CreateTarget&lt;TARGETCLASS&gt;(AutoMockType.RhinoMocksAAA);
        }

        public static ClassUnderTest&lt;TARGETCLASS&gt; CreateTarget&lt;TARGETCLASS&gt;(AutoMockType framework) where TARGETCLASS : class
        {
            AutoMocker&lt;TARGETCLASS&gt; mocker;
            ServiceLocator serviceLocator;
            switch (framework)
            {
                case AutoMockType.RhinoMocksAAA:
                    mocker = new RhinoAutoMocker&lt;TARGETCLASS&gt;(MockMode.AAA);
                    serviceLocator = new RhinoMocksAAAServiceLocator();
                    break;
                case AutoMockType.RhinoMocksClassic:
                    mocker = new RhinoAutoMocker&lt;TARGETCLASS&gt;(MockMode.RecordAndReplay);
                    serviceLocator = new RhinoMocksClassicServiceLocator();
                    break;
                case AutoMockType.Moq:
                    mocker = new MoqAutoMocker&lt;TARGETCLASS&gt;();
                    serviceLocator = new MoqServiceLocator();
                    break;
                default:
                    throw new ArgumentOutOfRangeException("framework");
            }
            return new ClassUnderTest&lt;TARGETCLASS&gt;(mocker, serviceLocator);
        }
    }

    public enum AutoMockType
    {
        Moq,
        RhinoMocksAAA,
        RhinoMocksClassic
    }

    public class ClassUnderTest&lt;TARGETCLASS&gt; where TARGETCLASS : class
    {
        readonly IAutoMocker&lt;TARGETCLASS&gt; _mocker;
        readonly ServiceLocator _serviceLocator;

        public ClassUnderTest(IAutoMocker&lt;TARGETCLASS&gt; mocker, ServiceLocator serviceLocator)
        {
            _mocker = mocker;
            _serviceLocator = serviceLocator;
        }

        public AutoMockedContainer Container
        {
            get { return _mocker.Container; }
        }

        public TARGETCLASS Instance
        {
            get { return _mocker.ClassUnderTest; }
        }

        public void MockObjectFactory()
        {
            _mocker.MockObjectFactory();
        }

        public void PartialMockTheClassUnderTest()
        {
            _mocker.PartialMockTheClassUnderTest();
        }

        public T Get&lt;T&gt;() where T : class
        {
            return _mocker.Get&lt;T&gt;();
        }

        public void Inject(Type pluginType, object stub)
        {
            _mocker.Inject(pluginType, stub);
        }

        public void Inject&lt;T&gt;(T target)
        {
            _mocker.Inject(target);
        }

        public T AddAdditionalMockFor&lt;T&gt;() where T : class
        {
            return _mocker.AddAdditionalMockFor&lt;T&gt;();
        }

        public void UseConcreteClassFor&lt;T&gt;()
        {
            _mocker.UseConcreteClassFor&lt;T&gt;();
        }

        public T[] CreateMockArrayFor&lt;T&gt;(int count) where T : class
        {
            return _mocker.CreateMockArrayFor&lt;T&gt;(count);
        }

        public void InjectArray&lt;T&gt;(T[] stubs)
        {
            _mocker.InjectArray(stubs);
        }

        public T Mock&lt;T&gt;() where T : class
        {
            return _serviceLocator.Service&lt;T&gt;();
        }
        public object Mock(Type serviceType)
        {
            return _serviceLocator.Service(serviceType);
        }
        public T PartialMock&lt;T&gt;() where T : class
        {
            return _serviceLocator.PartialMock&lt;T&gt;();
        }
    }
}</pre>
</ul>
<script type="text/javascript">// <![CDATA[
 var cirerolGaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."); document.write(unescape("%3Cscript src='" + cirerolGaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
// ]]&gt;</script>

<script type="text/javascript">// <![CDATA[
 var cirerolPageTracker = _gat._getTracker('UA-8257866-3'); cirerolPageTracker._initData(); cirerolPageTracker._trackPageview();
// ]]&gt;</script>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/11/30/wrapping-up-the-structuremap-automocking-container/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Integration Test Brought to you by Powershell &amp; NUnit &#8211; with a Little Specification Syntax for Flavoring</title>
		<link>http://elegantcode.com/2009/10/25/integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring</link>
		<comments>http://elegantcode.com/2009/10/25/integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring/#comments</comments>
		<pubDate>Mon, 26 Oct 2009 05:00:40 +0000</pubDate>
		<dc:creator>Jason Jarrett</dc:creator>
				<category><![CDATA[Esoterica]]></category>
		<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/10/25/integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring/</guid>
		<description><![CDATA[One of the tools I’ve used the last half of a year and really enjoyed is the C# specification extension methods when writing unit test assertions. If you’re looking for a little more background on the topic, I wrote about Fluent Specification Extensions in a past blog. Recently I wanted to execute a PowerShell script [...]]]></description>
			<content:encoded><![CDATA[One of the tools I’ve used the last half of a year and really enjoyed is the C# specification extension methods when writing unit test assertions. If you’re looking for a little more background on the topic, I wrote about <a href="http://staxmanade.blogspot.com/2009/02/fluent-specification-extensions.html">Fluent Specification Extensions</a> in a past blog.

Recently I wanted to execute a PowerShell script to do some automated <a href="http://en.wikipedia.org/wiki/Functional_testing">functional testing</a>. I wanted to execute an application and apply some assertions on the output of the software(basically running a console app, parse the xml output and assert on values in the output).
<blockquote>FYI: I’m very new to PowerShell, so any suggestions on how I implemented the below are welcome…</blockquote>
I’ve seen a couple examples of writing test assertions in PowerShell out there. One example is <a href="http://www.psunit.org/">PSUnit</a>; however, this seemed a little heavy for my needs and not quite the syntactic sugar I was looking for.

Besides the syntax flavor I was desiring, another thing I wanted to do was leverage the power of NUnit.Framework’s assertion capabilities. I like the error messages generated when strings and other objects fail the assertion.
<h5>Examples of end result ShouldLookLike()…</h5>
$true.ShouldBeTrue()
$false.ShouldBeFalse()
"a".ShouldEqual("a")
"a".ShouldNotEqual("b")
<h5><strong>Step 1</strong>: Figure out how to write a C# style <a href="http://msdn.microsoft.com/en-us/library/bb383977.aspx">extension method</a> in PowerShell.</h5>
<blockquote>I found a great blog post describing how to extend any PowerShell object to add extension methods.

<a href="http://bartdesmet.net/blogs/bart/archive/2007/09/06/extension-methods-in-windows-powershell.aspx">Extension Methods in Windows PowerShell</a></blockquote>
In short, to extend types in PowerShell leveraging the <a href="http://msdn.microsoft.com/en-us/library/ms714419(VS.85).aspx">Extended Type System</a>, you need to define them in an xml file and import the method definitions into the PowerShell runtime instance.

Below is PowerShell XML definition for my NUnit Specification Extensions.
<pre class="brush: xml;">&lt;?xml version="1.0" encoding="utf-16"?&gt;
&lt;Types&gt;
    &lt;Type&gt;
        &lt;Name&gt;System.Object&lt;/Name&gt;
        &lt;Members&gt;
            &lt;ScriptMethod&gt;
                &lt;Name&gt;ShouldBeFalse&lt;/Name&gt;
                &lt;Script&gt;
                    [NUnit.Framework.Assert]::IsFalse($this)
                &lt;/Script&gt;
            &lt;/ScriptMethod&gt;
            &lt;ScriptMethod&gt;
                &lt;Name&gt;ShouldBeTrue&lt;/Name&gt;
                &lt;Script&gt;
                    [NUnit.Framework.Assert]::IsTrue($this)
                &lt;/Script&gt;
            &lt;/ScriptMethod&gt;
            &lt;ScriptMethod&gt;
                &lt;Name&gt;ShouldEqual&lt;/Name&gt;
                &lt;Script&gt;
                    [NUnit.Framework.Assert]::AreEqual($args[0], $this)
                &lt;/Script&gt;
            &lt;/ScriptMethod&gt;
            &lt;ScriptMethod&gt;
                &lt;Name&gt;ShouldNotEqual&lt;/Name&gt;
                &lt;Script&gt;
                    [NUnit.Framework.Assert]::AreNotEqual($args[0], $this)
                &lt;/Script&gt;
            &lt;/ScriptMethod&gt;
        &lt;/Members&gt;
    &lt;/Type&gt;
&lt;/Types&gt;</pre>
<h4></h4>
Take the above XML and save it to a file…
<blockquote>NOTE: the file HAS to be saved with the extension <strong>.ps1xml</strong>

Ex: NunitSpecificationPowerShellExtensions<strong>.ps1xml</strong></blockquote>
<h4></h4>
<h5>Step 2: Load the extended type definition into the PowerShell runtime.</h5>
Once you’ve saved the XML extended types to a file, you need to load it into the PowerShell runtime by executing the command below.
<blockquote>
Update-TypeData -PrependPath NunitSpecificationPowerShellExtensions.ps1xml</blockquote>
Before executing the above statement…Let’s quickly look at a System.String’s members and properties – just to show you what the extension methods look like when applied inside of the runtime.<a href="http://elegantcode.com/wp-content/uploads/2009/10/image3.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" src="http://elegantcode.com/wp-content/uploads/2009/10/image_thumb2.png" border="0" alt="image" width="586" height="479" /></a>

After executing the Update-TypeData command you’ll notice there are a number of “ScriptMethod” MemberTypes added to the object.

<a href="http://elegantcode.com/wp-content/uploads/2009/10/image4.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" src="http://elegantcode.com/wp-content/uploads/2009/10/image_thumb3.png" border="0" alt="image" width="600" height="580" /></a>

Now if you try to execute one of those newly added extension methods, you may get the following error…

PS C:\&gt; $testVar.<strong>ShouldEqual</strong>("hello world")

Exception calling "ShouldEqual" with "1" argument(s): "<strong>Unable to find type [NUnit.Framework.Assert]: make sure that the

assembly containing this type is loaded.</strong>"

At line:1 char:21

+ $testVar.ShouldEqual &lt;&lt;&lt;&lt; ("hello world")

+ CategoryInfo          : NotSpecified: (:) [], MethodInvocationException

+ FullyQualifiedErrorId : ScriptMethodRuntimeException

This is because we need to load the NUnit.Framework assembly into the runtime before we can leverage the extension methods.
<blockquote>[System.Reflection.Assembly]::LoadFrom("C:\Program Files\NUnit 2.5.2\bin\net-2.0\framework\nunit.framework.dll") | Out-Null</blockquote>
Now that the extension methods have been defined and loaded into the runtime, NUnit.Framework is loaded, we can now use the methods on any object that inherits from System.Object (which, as far as I know, is everything in PowerShell).

And now, everything you need in one script (if you have the xml extended type file saved somewhere…)
<pre>#
# Update-TypeData -prependPath C:\Code\NunitSpecificationPowerShellExtensions.ps1xml
#

[System.Reflection.Assembly]::LoadFrom("C:\Program Files\NUnit 2.5.2\bin\net-2.0\framework\nunit.framework.dll") | Out-Null

$true.ShouldBeTrue()

$false.ShouldBeFalse()

"a".ShouldEqual("a")

"a".ShouldNotEqual("b")</pre>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/10/25/integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Visual Studio Team System for Small Teams</title>
		<link>http://elegantcode.com/2010/02/23/mspec-and-auto-mocking/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=mspec-and-auto-mocking</link>
		<comments>http://elegantcode.com/2010/02/23/mspec-and-auto-mocking/#comments</comments>
		<pubDate>Tue, 23 Feb 2010 20:38:54 +0000</pubDate>
		<dc:creator>Jan Van Ryswyck</dc:creator>
				<category><![CDATA[BDD]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/02/23/mspec-and-auto-mocking/</guid>
		<description><![CDATA[In my previous post, I explained how to get started with Machine.Specifications (or MSpec for short) and showed you how the syntax for context/specifications looks like when using this BDD framework. For this post, I want to show you how to use an auto mocking container (we’ll be using the one provided by StructureMap off [...]]]></description>
			<content:encoded><![CDATA[<p>In my <a href="http://elegantcode.com/2010/02/19/getting-started-with-machine-specifications-mspec/">previous post</a>, I explained how to get started with <a href="http://github.com/machine/machine.specifications">Machine.Specifications</a> (or MSpec for short) and showed you how the syntax for context/specifications looks like when using this BDD framework. For this post, I want to show you how to use an <a href="http://vanryswyckjan.blogspot.com/2008/01/automocking-container.html">auto mocking container</a> (we’ll be using the one provided by StructureMap off course).</p>  <p>We’ll use the same example as the one used in the previous post, but now we’ll deal with the message handler that makes a particular customer preferred.</p> <style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>  <pre class="csharpcode"><span class="rem">//</span>
<span class="rem">// Subject under test</span>
<span class="rem">//</span>
<span class="kwrd">public</span> <span class="kwrd">class</span> MakeCustomerPreferredMessageHandler
{
    <span class="kwrd">private</span> <span class="kwrd">readonly</span> ICustomerRepository&lt;ICanMakeCustomerPreferred&gt; _repository;

    <span class="kwrd">public</span> MakeCustomerPreferredMessageHandler(
        ICustomerRepository&lt;ICanMakeCustomerPreferred&gt; repository)
    {
        _repository = repository;
    }

    <span class="kwrd">public</span> <span class="kwrd">void</span> Handle(MakeCustomerPreferredMessage message)
    {
        var customer = _repository.Get(message.CustomerId);
        <span class="kwrd">if</span>(<span class="kwrd">null</span> == customer)
            <span class="kwrd">throw</span> <span class="kwrd">new</span> InvalidOperationException(
                <span class="str">&quot;No customer for specified identifier&quot;</span>);
        
        customer.MakePreferred();
        _repository.Save(customer);
    }
}</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>The <em>Customer</em> class implements a ‘<a href="http://martinfowler.com/bliki/RoleInterface.html">role interface’</a> called <em>ICanMakeCustomerPreferred</em>. We retrieve a customer from the repository and make it preferred. We throw an exception in case the customer cannot be found in the data store.</p>

<p>Here are the context/specifications for this easy example:</p>

<pre class="csharpcode">[Subject(<span class="str">&quot;Making a customer preferred&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_making_a_customer_preferred
    : context_specification&lt;MakeCustomerPreferredMessageHandler&gt;
{
    Establish context = () =&gt;
    {
        _message = <span class="kwrd">new</span> MakeCustomerPreferredMessage { CustomerId = 6412 };

        Repository.Stub(repository =&gt; repository.Get(_message.CustomerId))
            .Return(Customer);
    };

    Because of = () =&gt; 
        SUT.Handle(_message);
    
    It should_mark_the_customer_as_preferred = () =&gt;
        Customer.AssertWasCalled(customer =&gt; customer.MakePreferred());

    It should_save_the_customer_in_the_repository = () =&gt;
        Repository.AssertWasCalled(repository =&gt; repository.Save(Customer));

    <span class="kwrd">private</span> <span class="kwrd">static</span> ICanMakeCustomerPreferred Customer
    {
        get { <span class="kwrd">return</span> Dependency&lt;ICanMakeCustomerPreferred&gt;(); }
    }

    <span class="kwrd">private</span> <span class="kwrd">static</span> ICustomerRepository&lt;ICanMakeCustomerPreferred&gt; Repository
    {
        get { <span class="kwrd">return</span> Dependency&lt;ICustomerRepository&lt;ICanMakeCustomerPreferred&gt;&gt;(); }
    }

    <span class="kwrd">private</span> <span class="kwrd">static</span> MakeCustomerPreferredMessage _message;
}

[Subject(<span class="str">&quot;Making a customer preferred&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_making_an_unexisting_customer_preferred
    : context_specification&lt;MakeCustomerPreferredMessageHandler&gt;
{
    Establish context = () =&gt;   
    {
        _message = <span class="kwrd">new</span> MakeCustomerPreferredMessage() { CustomerId = 61544 };

        Dependency&lt;ICustomerRepository&lt;ICanMakeCustomerPreferred&gt;&gt;()
            .Stub(repository =&gt; repository.Get(_message.CustomerId))
            .Return(<span class="kwrd">null</span>);
    };

    Because of = () =&gt;
        _resultingException = Catch.Exception(() =&gt; SUT.Handle(_message));

    It should_result_in_an_error = () =&gt;
        _resultingException.ShouldBeOfType&lt;InvalidOperationException&gt;();

    <span class="kwrd">private</span> <span class="kwrd">static</span> MakeCustomerPreferredMessage _message;
    <span class="kwrd">private</span> <span class="kwrd">static</span> Exception _resultingException;
}</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>I want to point out that all fields and properties are made static. This is needed so that the anonymous methods can access them. I’m also using a base class for these specifications which I’ll show next. This base class uses an auto mocking container for providing the requested mocks and stubs through the <em>Dependency</em> and <em>Stub</em> methods. </p>

<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">abstract</span> <span class="kwrd">class</span> context_specification&lt;TSubjectUnderTest&gt;
    <span class="kwrd">where</span> TSubjectUnderTest : <span class="kwrd">class</span>
{
    <span class="kwrd">private</span> <span class="kwrd">static</span> IAutoMockingContainer&lt;TSubjectUnderTest&gt; _autoMockingContainer;
    <span class="kwrd">protected</span> <span class="kwrd">static</span> TSubjectUnderTest SUT { get; set; }

    Establish context = () =&gt;
    {
        _autoMockingContainer = <span class="kwrd">new</span> StructureMapAMC&lt;TSubjectUnderTest&gt;();
        SUT = _autoMockingContainer.Create();     
    };
    
    Cleanup stuff = () =&gt; 
    {
        SUT = <span class="kwrd">null</span>;
        _autoMockingContainer = <span class="kwrd">null</span>;
    };

    <span class="kwrd">protected</span> <span class="kwrd">static</span> TDependency Dependency&lt;TDependency&gt;()
        <span class="kwrd">where</span> TDependency : <span class="kwrd">class</span>
    {
        <span class="kwrd">return</span> _autoMockingContainer.GetMock&lt;TDependency&gt;();
    }

    <span class="kwrd">protected</span> <span class="kwrd">static</span> TStub Stub&lt;TStub&gt;()
        <span class="kwrd">where</span> TStub : <span class="kwrd">class</span>
    {
        <span class="kwrd">return</span> _autoMockingContainer.GetStub&lt;TStub&gt;();
    }
}

<span class="kwrd">public</span> <span class="kwrd">interface</span> IAutoMockingContainer&lt;TSubject&gt;
    <span class="kwrd">where</span> TSubject : <span class="kwrd">class</span>
{
    TSubject Create();
    TMock GetMock&lt;TMock&gt;() <span class="kwrd">where</span> TMock : <span class="kwrd">class</span>;
    TStub GetStub&lt;TStub&gt;() <span class="kwrd">where</span> TStub : <span class="kwrd">class</span>;
}

<span class="kwrd">public</span> <span class="kwrd">class</span> StructureMapAMC&lt;TSubject&gt; 
    : IAutoMockingContainer&lt;TSubject&gt;
    <span class="kwrd">where</span> TSubject : <span class="kwrd">class</span>
{
    <span class="kwrd">private</span> <span class="kwrd">readonly</span> RhinoAutoMocker&lt;TSubject&gt; _rhinoAutoMocker;

    <span class="kwrd">public</span> StructureMapAMC()
    {
        _rhinoAutoMocker = 
            <span class="kwrd">new</span> RhinoAutoMocker&lt;TSubject&gt;(MockMode.AAA);
    }

    <span class="kwrd">public</span> TSubject Create()
    {
        <span class="kwrd">return</span> _rhinoAutoMocker.ClassUnderTest;
    }

    <span class="kwrd">public</span> TMock GetMock&lt;TMock&gt;() 
        <span class="kwrd">where</span> TMock : <span class="kwrd">class</span>
    {
        <span class="kwrd">return</span> GetDependency&lt;TMock&gt;();
    }

    <span class="kwrd">public</span> TStub GetStub&lt;TStub&gt;() 
        <span class="kwrd">where</span> TStub : <span class="kwrd">class</span>
    {
        <span class="kwrd">return</span> GetDependency&lt;TStub&gt;();
    }

    <span class="kwrd">private</span> TDependency GetDependency&lt;TDependency&gt;() 
        <span class="kwrd">where</span> TDependency : <span class="kwrd">class</span>
    {
        <span class="kwrd">return</span> _rhinoAutoMocker.Get&lt;TDependency&gt;();
    }
}</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>Notice that I’m using the <em>Establish</em> and <em>Cleanup</em> delegates in the <em>context_specification</em> base class. This doesn’t prevent that these can be used again in derived context/specifications. MSpec ensures that the anonymous methods are called in the right order. This means that the <em>Establish</em> method of the base class is called before the <em>Establish</em> method of the derived context/specifications.&#160;&#160;&#160;&#160; </p>

<p>Absolutely no rocket science here, but I figured it might come in handy when you need it. For the next post I’ll try to demonstrate how to deal with reusable behaviors.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/02/23/mspec-and-auto-mocking/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Elegant Code &#187; Unit Testing</title>
	<atom:link href="http://elegantcode.com/category/unit-testing/feed/" rel="self" type="application/rss+xml" />
	<link>http://elegantcode.com</link>
	<description></description>
	<lastBuildDate>Tue, 15 May 2012 10:00:00 +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>AutoTest.NET</title>
		<link>http://elegantcode.com/2010/11/30/autotest-net/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=autotest-net</link>
		<comments>http://elegantcode.com/2010/11/30/autotest-net/#comments</comments>
		<pubDate>Tue, 30 Nov 2010 11:00:00 +0000</pubDate>
		<dc:creator>Jan Van Ryswyck</dc:creator>
				<category><![CDATA[TDD]]></category>
		<category><![CDATA[Tools and Utilities]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/11/30/autotest-net/</guid>
		<description><![CDATA[I just want to quickly point out a tool that I’ve been playing with for a couple of days now, named AutoTest.NET. Its an open-source tool that originates from a popular tool in the Ruby community called ZenTest, which basically runs all your valuable unit tests when you save your source files or when you [...]]]></description>
			<content:encoded><![CDATA[<p>I just want to quickly point out a tool that I’ve been playing with for a couple of days now, named <a href="https://github.com/acken/AutoTest.Net" target="_blank">AutoTest.NET</a>. Its an open-source tool that originates from a popular tool in the Ruby community called <a href="http://www.zenspider.com/ZSS/Products/ZenTest/" target="_blank">ZenTest</a>, which basically runs all your valuable unit tests when you save your source files or when you build your code. It enables you to get feedback about your changes as soon as possible.</p>  <p>The project started out a couple of years ago on <a href="http://code.google.com/p/autotestnet/" target="_blank">Google code</a> and was first initiated by <a href="http://averyblog.com/" target="_blank">James Avery</a>. Contribution stopped at some point until recently where <a href="http://ackenpacken.blogspot.com/" target="_blank">Svein Arne Ackenhausen</a> forked the source code and <a href="https://github.com/acken/AutoTest.Net" target="_blank">put it on GitHub</a>. Now it runs both for .NET as well as Mono, with NUnit, MSTest and xUnit as the currently supported unit test frameworks. </p>  <p>Here’s a screenshot from the feedback window when all tests pass:</p>  <p><a href="http://elegantcode.com/wp-content/uploads/2010/11/Success.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="Success" border="0" alt="Success" src="http://elegantcode.com/wp-content/uploads/2010/11/Success_thumb.png" width="540" height="189" /></a> </p>  <p>And here you can see the same window after I broke one of my unit tests:</p>  <p><a href="http://elegantcode.com/wp-content/uploads/2010/11/Failure.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="Failure" border="0" alt="Failure" src="http://elegantcode.com/wp-content/uploads/2010/11/Failure_thumb.png" width="538" height="319" /></a> </p>  <p>Here you can see which particular unit test has been broken and by clicking the specified link you end up at the right source file in Visual Studio. </p>  <p>I encourage you to pick up this small tool and learn how it can facilitate your TDD flow. Take a look at <a href="https://github.com/acken/AutoTest.Net/wiki/Get-started!" target="_blank">this page</a> in order to get up-and-running in no time. Also don’t forget to provide the owner(s) of this project with some feedback that you might have. Svein has been very helpful over the last week answering all my stupid questions and remarks (and the Nobel price for this year’s most patient person goes to … ;-) ). </p>  <p>I would definitely like to see this tool becoming more popular, so go check it out.&#160;&#160; </p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/11/30/autotest-net/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>If Self-Documenting Code is the What, Unit Tests are the Why</title>
		<link>http://elegantcode.com/2010/04/25/if-self-documenting-code-is-the-what-unit-tests-are-the-why/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=if-self-documenting-code-is-the-what-unit-tests-are-the-why</link>
		<comments>http://elegantcode.com/2010/04/25/if-self-documenting-code-is-the-what-unit-tests-are-the-why/#comments</comments>
		<pubDate>Sun, 25 Apr 2010 19:09:04 +0000</pubDate>
		<dc:creator>John Sonmez</dc:creator>
				<category><![CDATA[Agile]]></category>
		<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Craftsmanship]]></category>
		<category><![CDATA[Documentation]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/04/25/if-self-documenting-code-is-the-what-unit-tests-are-the-why/</guid>
		<description><![CDATA[It is not enough to just write code that is clean and self-documenting.  Eliminating comments and replacing them with clear variable and method names, will tell the reader of your code clearly what it is doing, but it will not properly express why it is doing it. If you recall from my original post on [...]]]></description>
			<content:encoded><![CDATA[It is not enough to just write code that is clean and self-documenting.  <a href="http://elegantcode.com/2010/04/18/eliminating-comments-the-road-to-clarity/">Eliminating comments</a> and replacing them with clear variable and method names, will tell the reader of your code clearly what it is doing, but it will not properly express why it is doing it.

If you recall from my <a href="http://elegantcode.com/2010/04/09/what-does-elegant-code-mean-to-me/">original post</a> on Elegant code, I stated that elegant code is:
<blockquote>Something that is simple yet effective, delivered with grace.</blockquote>
By writing self-documenting code we are hopefully able to achieve some of the aspects of simplicity and grace, but it tells us nothing about the effectiveness of the code.
<h2>Bringing the dead to life</h2>
<a href="http://elegantcode.com/wp-content/uploads/2010/04/zombies.jpg"><img style="border-right-width: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto" title="zombies" src="http://elegantcode.com/wp-content/uploads/2010/04/zombies_thumb.jpg" border="0" alt="zombies" width="441" height="295" /></a>

Throwing out comments is a debatable topic.  <a href="http://www.reddit.com/r/programming/comments/bsutx/">It raises quite a bit of controversy</a>, as you can see from some of the comments on my post about the subject.  The reason, perhaps, that so many people are so staunchly opposed to the idea, is because they are worried, and rightly so, that throwing out comments will reduce the documentation of what the code is doing.

Think about that for a second.  Is documentation of what the code is doing important?  It better be.  What we are trying to accomplish by writing self-documenting code instead of comments, is to take the vessel, which is the code itself, and make that same vessel be the documentation of what the code does.  It is by doing this that we creating a living representation of the functionality of the code.  Comments are akin to a dead representation of the functionality of the code because they do not change automatically with the code.

I diverge to talk about comments so that I can draw a parallel to another form of documentation which is valuable and should be considered necessary.  That other set of documentation is requirements.  Have you ever written requirements documents?  Have you ever captured requirements from the customer and put them into UML diagrams, or perhaps plopped them into some templated Word document, which is never updated again, and no one reads, because no one trusts it is correct?  Wouldn’t it be great if we would replace that dead document or set of documents, with a living one?

The good news is we can, and some of us have.  And I fully expect this recommendation will be just as controversial, because <strong>I am suggesting that we don’t have to write low level specifications of the system at all, instead we can write good unit tests. </strong>When we do this, we are taking a dead form of document and bringing it to life.
<h2>Unit tests tell us why and how our code is effective</h2>
If
<pre class="csharpcode">i = 5;  // Widget count defaults to five.</pre>
is replaced with
<pre class="csharpcode">widgetCount = DEFAULT_WIDGET_COUNT;</pre>
<!--.csharpcode, .csharpcode pre { 	font-size: small; 	color: black; 	font-family: consolas, "Courier New", courier, monospace; 	background-color: #ffffff; 	/*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt  { 	background-color: #f4f4f4; 	width: 100%; 	margin: 0em; } .csharpcode .lnum { color: #606060; } -->

then
<blockquote><span style="background-color: #ffffff;">1.1.5 When a new widget is created, the widget count should be increased by one.</span></blockquote>
is replaced with
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">void</span> When_NewWidgetIsCreated_Then_WidgetCountIsIncreasedByOne()
{
     WidgetFactory.Count = 3;
     WidgetFactory.CreateNew();
     assertEquals(4, WidgetFactory.Count);
}</pre>
The unit test is replacing the low level requirement, which is somewhat open to interpretation and untied to the code, with an absolute and completely tied-to-the-code, specific requirement.

The unit test is telling us why our code is built the way it is.  It is telling us what requirement that particular structure of code is trying to address.  <strong>It is telling us what end result that code is trying to accomplish and what the expectations are on the results of a given condition.</strong>

The unit test is telling us how the code is to be used in order to achieve its result.  It is serving as a living reference to the syntax and use of the code we built.  <strong>Instead of providing instructions on how to use our API, we are providing a living example, and proof that it will indeed work.</strong> Examples are often much more effective than instructions anyway.
<h2>What exactly are we replacing?</h2>
At this point we are not trying to replace all the documentation of the system (at this point).

With self-documenting code, we sought to eliminate comments, and replace them with good variable and method names.

With unit tests, we seek to eliminate technical documentation and requirements of the system, that is targeted at a developer or technical audience.

We are NOT trying to eliminate high level specifications of the system, or use cases. <strong>Unit tests DO NOT replace that kind of documentation! </strong>We will talk about replacing that kind of documentation when we talk about automated functional or system tests.

Simply put, any kind of documentation that you would give to a developer so they understand how the system works and how to use the code or APIs, can be easily replaced by writing good unit tests.

Our simple goal is to replace the “dead” documentation (meaning that it does not update automatically with the thing it is documenting), with “living” documentation in the form of unit tests.

One last point.  I want to be clear that I am not saying that having unit tests automatically results in the ability to replace technical documentation.  Just like having long-named methods and variables doesn’t automatically replace the need for comments.  It is a matter of the quality of the unit tests that are written, just as it is a matter of the quality of the self-documenting code.
<h5>As always, you can subscribe to this <a href="http://feeds2.feedburner.com/ElegantCode">RSS feed</a> to follow my posts on elegant code.  Feel free to check out my main personal blog at <a href="http://simpleprogrammer.com">http://simpleprogrammer.com</a>, which has a wider range of posts, updated 2-3 times a week.  Also, you can follow me on twitter <a href="http://twitter.com/jsonmez">here</a>.</h5>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/04/25/if-self-documenting-code-is-the-what-unit-tests-are-the-why/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Behaviors with MSpec</title>
		<link>http://elegantcode.com/2010/02/26/behaviors-with-mspec/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=behaviors-with-mspec</link>
		<comments>http://elegantcode.com/2010/02/26/behaviors-with-mspec/#comments</comments>
		<pubDate>Fri, 26 Feb 2010 23:33:28 +0000</pubDate>
		<dc:creator>Jan Van Ryswyck</dc:creator>
				<category><![CDATA[BDD]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/02/26/behaviors-with-mspec/</guid>
		<description><![CDATA[In my previous posts, I showed the syntax for context/specifications using Machine.Specifications (or MSpec for short) and how to use an auto mocking container in conjunction with this excellent Behavior-Driven Development (BDD) framework. For this post, I want to show you one of the nice features of MSpec called behaviors. Suppose we have to create [...]]]></description>
			<content:encoded><![CDATA[<p>In my previous posts, I showed the <a href="http://elegantcode.com/2010/02/19/getting-started-with-machine-specifications-mspec/">syntax for context/specifications</a> using <a href="http://github.com/machine/machine.specifications">Machine.Specifications</a> (or MSpec for short) and <a href="http://elegantcode.com/2010/02/23/mspec-and-auto-mocking">how to use an auto mocking container</a> in conjunction with this excellent Behavior-Driven Development (BDD) framework. For this post, I want to show you one of the nice features of MSpec called <em>behaviors</em>.</p>  <p>Suppose we have to create some sort of specification that validates the format of an e-mail address. We typically use some regular expression in order to ensure that a specified e-mail address is properly formatted.</p>  <pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">class</span> EmailSpecification
{
    <span class="kwrd">private</span> <span class="kwrd">const</span> String EmailRegexPattern = <span class="str">@&quot;.. SOME_REGEX_PATTERN ...&quot;</span>;

    <span class="kwrd">public</span> Boolean IsSatisfiedBy(String candidate)
    {
        var regex = <span class="kwrd">new</span> Regex(EmailRegexPattern);
        <span class="kwrd">return</span> regex.IsMatch(candidate);
    }
}</pre>
<style type="text/css">

.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>I guess this is pretty common and straightforward. One way to provide some unit tests for this particular piece of code is to check a whole number of e-mail addresses that either pass or fail the specification. The following example shows only a couple of scenarios:</p>

<pre class="csharpcode">[TestFixture]
<span class="kwrd">public</span> <span class="kwrd">class</span> When_validating_an_email
    : ContextSpecification&lt;EmailSpecification&gt;
{
    <span class="kwrd">protected</span> <span class="kwrd">override</span> EmailSpecification Create_subject_under_test()
    {
        <span class="kwrd">return</span> <span class="kwrd">new</span> EmailSpecification();
    }

    [Test]
    <span class="kwrd">public</span> <span class="kwrd">void</span> ShouldBeSatisfied()
    {
        Assert.That(SUT.IsSatisfiedBy(<span class="str">&quot;one2@three.com&quot;</span>));
        Assert.That(SUT.IsSatisfiedBy(<span class="str">&quot;one@two3.com&quot;</span>));
    }

    [Test]
    <span class="kwrd">public</span> <span class="kwrd">void</span> ShouldNotBeSatisfied()
    {
        Assert.That(SUT.IsSatisfiedBy(<span class="str">&quot;one_two.com&quot;</span>), Is.False);
        Assert.That(SUT.IsSatisfiedBy(<span class="str">&quot;one_two@&quot;</span>), Is.False);
    }
}</pre>
<style type="text/css">

.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>A slightly more concise approach for these kind of unit tests can be accomplished by utilizing a feature of any decent unit test framework called <em>row tests. </em>With this approach we can, at the very least, reduce the number of asserts we have to write for each unit test.<em>&#160;</em></p>

<pre class="csharpcode">[TestFixture]
<span class="kwrd">public</span> <span class="kwrd">class</span> When_validating_an_email__approach_2
    : ContextSpecification&lt;EmailSpecification&gt;
{
    <span class="kwrd">protected</span> <span class="kwrd">override</span> EmailSpecification Create_subject_under_test()
    {
        <span class="kwrd">return</span> <span class="kwrd">new</span> EmailSpecification();
    }

    [RowTest]
    [Row(<span class="str">&quot;one2@three.com&quot;</span>)]
    [Row(<span class="str">&quot;one@two3.com&quot;</span>)]
    <span class="kwrd">public</span> <span class="kwrd">void</span> ShouldBeSatisfied(String email)
    {
        Assert.That(SUT.IsSatisfiedBy(email));
    }

    [RowTest]
    [Row(<span class="str">&quot;one_two.com&quot;</span>)]
    [Row(<span class="str">&quot;one_two@&quot;</span>)]
    <span class="kwrd">public</span> <span class="kwrd">void</span> ShouldNotBeSatisfied(String email)
    {
        Assert.That(SUT.IsSatisfiedBy(email), Is.False);
    }
}</pre>
<style type="text/css">

.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>Notice that I explicitly called both of these approaches <em>unit tests</em> as they don’t have much to do with BDD in my opinion. I’m not saying that using regular unit tests is a bad thing, but with&#160; behavior-driven development context is king. So these unit tests are perfect examples of ‘<a href="http://elegantcode.com/2008/12/30/dont-sell-out-on-the-context-dude/">context betrayal</a>’ when following the BDD approach. </p>

<p>Lets see what MSpec can bring to the table for these kind of scenarios:</p>

<pre class="csharpcode">[Subject(<span class="kwrd">typeof</span>(EmailSpecification), <span class="str">&quot;is satisfied&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_validating_an_email_address_with_a_number_in_the_local_part
    : email_specification_specs
{
    Establish context = () =&gt;
        EmailAddress = <span class="str">&quot;one2@three.com&quot;</span>;

    Behaves_like&lt;SatisfiedSpecificationBehavior&gt; a_satisfied_specification;
}

[Subject(<span class="kwrd">typeof</span>(EmailSpecification), <span class="str">&quot;is satisfied&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_validating_an_email_address_with_a_number_in_the_domain_name
    : email_specification_specs
{
    Establish context = () =&gt;
        EmailAddress = <span class="str">&quot;one@two3.com&quot;</span>;

    Behaves_like&lt;SatisfiedSpecificationBehavior&gt; a_satisfied_specification;
}

[Subject(<span class="kwrd">typeof</span>(EmailSpecification), <span class="str">&quot;is satisfied&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_validating_an_email_address_without_an_At_sign
    : email_specification_specs
{
    Establish context = () =&gt;
        EmailAddress = <span class="str">&quot;one_two.com&quot;</span>;

    Behaves_like&lt;UnsatisfiedSpecificationBehavior&gt; an_unsatisfied_specification;
}

[Subject(<span class="kwrd">typeof</span>(EmailSpecification), <span class="str">&quot;is satisfied&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_validating_an_email_address_without_a_domain
    : email_specification_specs
{
    Establish context = () =&gt;
        EmailAddress = <span class="str">&quot;one_two@&quot;</span>;

    Behaves_like&lt;UnsatisfiedSpecificationBehavior&gt; an_unsatisfied_specification;
}</pre>
<style type="text/css">

.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>In order to escape ‘context betrayal’, we’ve split up every context into a separate context/specification. In order to reduce the amount of effort caused by duplicate code, we stripped the context setup to the bare minimum (just a particular e-mail address in this case). The observations are isolated into MSpec behaviors which provides a very readable description of their outcome. Lets take a look at what is needed in order to get these <em>behaviors</em> to work.</p>

<p>But first lets take at look at the abstract base class that we’ve used for the context/specifications we’ve just shown.</p>

<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">abstract</span> <span class="kwrd">class</span> email_specification_specs
{
    Establish context = () =&gt;
    {
        SUT = <span class="kwrd">new</span> EmailSpecification();
    };

    Because of = () =&gt;
        Result = SUT.IsSatisfiedBy(EmailAddress);

    <span class="kwrd">protected</span> <span class="kwrd">static</span> Boolean Result;
    <span class="kwrd">protected</span> <span class="kwrd">static</span> String EmailAddress { get; set; }
    <span class="kwrd">protected</span> <span class="kwrd">static</span> EmailSpecification SUT { get; set; }
}</pre>

<p><style type="text/css">

.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style></p>

<p>&#160;</p>

<p>We abstracted as much as possible into this base class in order to remove duplication in the context/specifications. The creation of the subject-under-test and the calling of its <em>IsSatisfiedBy</em> method, but the important one is the declaration of the <em>Result</em> field. This field contains the outcome of the <em>IsSatisfiedBy</em> method. Finally, lets have a look at the behaviors themselves:</p>

<pre class="csharpcode">[Behaviors]
<span class="kwrd">public</span> <span class="kwrd">class</span> SatisfiedSpecificationBehavior
{
    <span class="kwrd">protected</span> <span class="kwrd">static</span> Boolean Result;
    
    It should_satisfy_the_specification = () =&gt;
        Result.ShouldBeTrue();
}

[Behaviors]
<span class="kwrd">public</span> <span class="kwrd">class</span> UnsatisfiedSpecificationBehavior
{
    <span class="kwrd">protected</span> <span class="kwrd">static</span> Boolean Result;

    It should_not_satisfy_the_specification = () =&gt;
        Result.ShouldBeFalse();
}</pre>
<style type="text/css">

.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>In order to create an MSpec behavior, we just have to create a separate class that we decorate with the <em>Behaviors</em> attribute. Also notice that we have the same declaration of the <em>Result</em> field. MSpec ensures that this field gets initialized with the value of the other <em>Result</em> field that is set in the base class of the context/specifications. Note that you don’t necessarily need to put this field in a base class. You can have that field in every context/specification if you’d like (not sure why) as long as the names match with the fields used in the defined behaviors.</p>

<p>I personally like the way how the MSpec contributors tried to solve testing the same logic with different input patterns and the syntax they provided to back this up.&#160;&#160; </p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/02/26/behaviors-with-mspec/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>MSpec and Auto Mocking</title>
		<link>http://elegantcode.com/2010/02/23/mspec-and-auto-mocking/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=mspec-and-auto-mocking</link>
		<comments>http://elegantcode.com/2010/02/23/mspec-and-auto-mocking/#comments</comments>
		<pubDate>Tue, 23 Feb 2010 20:38:54 +0000</pubDate>
		<dc:creator>Jan Van Ryswyck</dc:creator>
				<category><![CDATA[BDD]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/02/23/mspec-and-auto-mocking/</guid>
		<description><![CDATA[In my previous post, I explained how to get started with Machine.Specifications (or MSpec for short) and showed you how the syntax for context/specifications looks like when using this BDD framework. For this post, I want to show you how to use an auto mocking container (we’ll be using the one provided by StructureMap off [...]]]></description>
			<content:encoded><![CDATA[<p>In my <a href="http://elegantcode.com/2010/02/19/getting-started-with-machine-specifications-mspec/">previous post</a>, I explained how to get started with <a href="http://github.com/machine/machine.specifications">Machine.Specifications</a> (or MSpec for short) and showed you how the syntax for context/specifications looks like when using this BDD framework. For this post, I want to show you how to use an <a href="http://vanryswyckjan.blogspot.com/2008/01/automocking-container.html">auto mocking container</a> (we’ll be using the one provided by StructureMap off course).</p>  <p>We’ll use the same example as the one used in the previous post, but now we’ll deal with the message handler that makes a particular customer preferred.</p> <style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>  <pre class="csharpcode"><span class="rem">//</span>
<span class="rem">// Subject under test</span>
<span class="rem">//</span>
<span class="kwrd">public</span> <span class="kwrd">class</span> MakeCustomerPreferredMessageHandler
{
    <span class="kwrd">private</span> <span class="kwrd">readonly</span> ICustomerRepository&lt;ICanMakeCustomerPreferred&gt; _repository;

    <span class="kwrd">public</span> MakeCustomerPreferredMessageHandler(
        ICustomerRepository&lt;ICanMakeCustomerPreferred&gt; repository)
    {
        _repository = repository;
    }

    <span class="kwrd">public</span> <span class="kwrd">void</span> Handle(MakeCustomerPreferredMessage message)
    {
        var customer = _repository.Get(message.CustomerId);
        <span class="kwrd">if</span>(<span class="kwrd">null</span> == customer)
            <span class="kwrd">throw</span> <span class="kwrd">new</span> InvalidOperationException(
                <span class="str">&quot;No customer for specified identifier&quot;</span>);
        
        customer.MakePreferred();
        _repository.Save(customer);
    }
}</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>The <em>Customer</em> class implements a ‘<a href="http://martinfowler.com/bliki/RoleInterface.html">role interface’</a> called <em>ICanMakeCustomerPreferred</em>. We retrieve a customer from the repository and make it preferred. We throw an exception in case the customer cannot be found in the data store.</p>

<p>Here are the context/specifications for this easy example:</p>

<pre class="csharpcode">[Subject(<span class="str">&quot;Making a customer preferred&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_making_a_customer_preferred
    : context_specification&lt;MakeCustomerPreferredMessageHandler&gt;
{
    Establish context = () =&gt;
    {
        _message = <span class="kwrd">new</span> MakeCustomerPreferredMessage { CustomerId = 6412 };

        Repository.Stub(repository =&gt; repository.Get(_message.CustomerId))
            .Return(Customer);
    };

    Because of = () =&gt; 
        SUT.Handle(_message);
    
    It should_mark_the_customer_as_preferred = () =&gt;
        Customer.AssertWasCalled(customer =&gt; customer.MakePreferred());

    It should_save_the_customer_in_the_repository = () =&gt;
        Repository.AssertWasCalled(repository =&gt; repository.Save(Customer));

    <span class="kwrd">private</span> <span class="kwrd">static</span> ICanMakeCustomerPreferred Customer
    {
        get { <span class="kwrd">return</span> Dependency&lt;ICanMakeCustomerPreferred&gt;(); }
    }

    <span class="kwrd">private</span> <span class="kwrd">static</span> ICustomerRepository&lt;ICanMakeCustomerPreferred&gt; Repository
    {
        get { <span class="kwrd">return</span> Dependency&lt;ICustomerRepository&lt;ICanMakeCustomerPreferred&gt;&gt;(); }
    }

    <span class="kwrd">private</span> <span class="kwrd">static</span> MakeCustomerPreferredMessage _message;
}

[Subject(<span class="str">&quot;Making a customer preferred&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_making_an_unexisting_customer_preferred
    : context_specification&lt;MakeCustomerPreferredMessageHandler&gt;
{
    Establish context = () =&gt;   
    {
        _message = <span class="kwrd">new</span> MakeCustomerPreferredMessage() { CustomerId = 61544 };

        Dependency&lt;ICustomerRepository&lt;ICanMakeCustomerPreferred&gt;&gt;()
            .Stub(repository =&gt; repository.Get(_message.CustomerId))
            .Return(<span class="kwrd">null</span>);
    };

    Because of = () =&gt;
        _resultingException = Catch.Exception(() =&gt; SUT.Handle(_message));

    It should_result_in_an_error = () =&gt;
        _resultingException.ShouldBeOfType&lt;InvalidOperationException&gt;();

    <span class="kwrd">private</span> <span class="kwrd">static</span> MakeCustomerPreferredMessage _message;
    <span class="kwrd">private</span> <span class="kwrd">static</span> Exception _resultingException;
}</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>I want to point out that all fields and properties are made static. This is needed so that the anonymous methods can access them. I’m also using a base class for these specifications which I’ll show next. This base class uses an auto mocking container for providing the requested mocks and stubs through the <em>Dependency</em> and <em>Stub</em> methods. </p>

<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">abstract</span> <span class="kwrd">class</span> context_specification&lt;TSubjectUnderTest&gt;
    <span class="kwrd">where</span> TSubjectUnderTest : <span class="kwrd">class</span>
{
    <span class="kwrd">private</span> <span class="kwrd">static</span> IAutoMockingContainer&lt;TSubjectUnderTest&gt; _autoMockingContainer;
    <span class="kwrd">protected</span> <span class="kwrd">static</span> TSubjectUnderTest SUT { get; set; }

    Establish context = () =&gt;
    {
        _autoMockingContainer = <span class="kwrd">new</span> StructureMapAMC&lt;TSubjectUnderTest&gt;();
        SUT = _autoMockingContainer.Create();     
    };
    
    Cleanup stuff = () =&gt; 
    {
        SUT = <span class="kwrd">null</span>;
        _autoMockingContainer = <span class="kwrd">null</span>;
    };

    <span class="kwrd">protected</span> <span class="kwrd">static</span> TDependency Dependency&lt;TDependency&gt;()
        <span class="kwrd">where</span> TDependency : <span class="kwrd">class</span>
    {
        <span class="kwrd">return</span> _autoMockingContainer.GetMock&lt;TDependency&gt;();
    }

    <span class="kwrd">protected</span> <span class="kwrd">static</span> TStub Stub&lt;TStub&gt;()
        <span class="kwrd">where</span> TStub : <span class="kwrd">class</span>
    {
        <span class="kwrd">return</span> _autoMockingContainer.GetStub&lt;TStub&gt;();
    }
}

<span class="kwrd">public</span> <span class="kwrd">interface</span> IAutoMockingContainer&lt;TSubject&gt;
    <span class="kwrd">where</span> TSubject : <span class="kwrd">class</span>
{
    TSubject Create();
    TMock GetMock&lt;TMock&gt;() <span class="kwrd">where</span> TMock : <span class="kwrd">class</span>;
    TStub GetStub&lt;TStub&gt;() <span class="kwrd">where</span> TStub : <span class="kwrd">class</span>;
}

<span class="kwrd">public</span> <span class="kwrd">class</span> StructureMapAMC&lt;TSubject&gt; 
    : IAutoMockingContainer&lt;TSubject&gt;
    <span class="kwrd">where</span> TSubject : <span class="kwrd">class</span>
{
    <span class="kwrd">private</span> <span class="kwrd">readonly</span> RhinoAutoMocker&lt;TSubject&gt; _rhinoAutoMocker;

    <span class="kwrd">public</span> StructureMapAMC()
    {
        _rhinoAutoMocker = 
            <span class="kwrd">new</span> RhinoAutoMocker&lt;TSubject&gt;(MockMode.AAA);
    }

    <span class="kwrd">public</span> TSubject Create()
    {
        <span class="kwrd">return</span> _rhinoAutoMocker.ClassUnderTest;
    }

    <span class="kwrd">public</span> TMock GetMock&lt;TMock&gt;() 
        <span class="kwrd">where</span> TMock : <span class="kwrd">class</span>
    {
        <span class="kwrd">return</span> GetDependency&lt;TMock&gt;();
    }

    <span class="kwrd">public</span> TStub GetStub&lt;TStub&gt;() 
        <span class="kwrd">where</span> TStub : <span class="kwrd">class</span>
    {
        <span class="kwrd">return</span> GetDependency&lt;TStub&gt;();
    }

    <span class="kwrd">private</span> TDependency GetDependency&lt;TDependency&gt;() 
        <span class="kwrd">where</span> TDependency : <span class="kwrd">class</span>
    {
        <span class="kwrd">return</span> _rhinoAutoMocker.Get&lt;TDependency&gt;();
    }
}</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>Notice that I’m using the <em>Establish</em> and <em>Cleanup</em> delegates in the <em>context_specification</em> base class. This doesn’t prevent that these can be used again in derived context/specifications. MSpec ensures that the anonymous methods are called in the right order. This means that the <em>Establish</em> method of the base class is called before the <em>Establish</em> method of the derived context/specifications.&#160;&#160;&#160;&#160; </p>

<p>Absolutely no rocket science here, but I figured it might come in handy when you need it. For the next post I’ll try to demonstrate how to deal with reusable behaviors.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/02/23/mspec-and-auto-mocking/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Getting Started With Machine.Specifications (MSpec)</title>
		<link>http://elegantcode.com/2010/02/19/getting-started-with-machine-specifications-mspec/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=getting-started-with-machine-specifications-mspec</link>
		<comments>http://elegantcode.com/2010/02/19/getting-started-with-machine-specifications-mspec/#comments</comments>
		<pubDate>Fri, 19 Feb 2010 21:34:17 +0000</pubDate>
		<dc:creator>Jan Van Ryswyck</dc:creator>
				<category><![CDATA[BDD]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/02/19/getting-started-with-machine-specifications-mspec/</guid>
		<description><![CDATA[Its been a while since I evaluated and evolved my approach to BDD. The way I’ve been doing BDD up until now is described in this blog post which goes way back to 2008. Everyone has kind of their own style nowadays. Below you can find the code of two context/specifications for a method named [...]]]></description>
			<content:encoded><![CDATA[<p>Its been a while since I evaluated and evolved my approach to BDD. The way I’ve been doing BDD up until now is described in <a href="http://elegantcode.com/2008/10/25/refining-contextspecification-bdd-using-rhino-mocks-35/">this blog post</a> which goes way back to 2008. Everyone has kind of their own style nowadays. Below you can find the code of two context/specifications for a method named <em>MakePreferred</em> on a <em>Customer </em>class. This simple example clarifies the style that I’ve been following up until now.</p> <style type="text/css">


.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style><style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>  <pre class="csharpcode">[TestFixture]
<span class="kwrd">public</span> <span class="kwrd">class</span> When_making_a_regular_customer_preferred
    : ContextSpecification&lt;Customer&gt;
{
    <span class="kwrd">protected</span> <span class="kwrd">override</span> Customer Create_subject_under_test()
    {
        <span class="kwrd">return</span> <span class="kwrd">new</span> Customer(<span class="kwrd">new</span>[] { _order });
    }

    <span class="kwrd">protected</span> <span class="kwrd">override</span> <span class="kwrd">void</span> Establish_context()
    {
        _order = <span class="kwrd">new</span> Order(<span class="kwrd">new</span>[] { <span class="kwrd">new</span> OrderItem(12), 
                                   <span class="kwrd">new</span> OrderItem(16) });
                                   
        _totalAmountWithoutDiscount = _order.TotalAmount;
    }

    <span class="kwrd">protected</span> <span class="kwrd">override</span> <span class="kwrd">void</span> Because()
    {
        SUT.MakePreferred();
    }

    [Test]
    <span class="kwrd">public</span> <span class="kwrd">void</span> Then_the_customer_should_be_marked_as_preferred()
    {
        SUT.IsPreferred.ShouldBeTrue();
    }

    [Test]
    <span class="kwrd">public</span> <span class="kwrd">void</span> Then_a_ten_percent_discount_should_be_applied_to_all_outstanding_orders()
    {
        _order.TotalAmount.ShouldBeEqualTo(
            _totalAmountWithoutDiscount * 0.9);
    }

    <span class="kwrd">private</span> Order _order;
    <span class="kwrd">private</span> Double _totalAmountWithoutDiscount;
}

[TestFixture]
<span class="kwrd">public</span> <span class="kwrd">class</span> When_making_a_preferred_customer_preferred
    : ContextSpecification&lt;Customer&gt;
{
    <span class="kwrd">protected</span> <span class="kwrd">override</span> Customer Create_subject_under_test()
    {
        var customer = <span class="kwrd">new</span> Customer(<span class="kwrd">new</span>[] { _order });
        customer.MakePreferred();
        <span class="kwrd">return</span> customer;
    }

    <span class="kwrd">protected</span> <span class="kwrd">override</span> <span class="kwrd">void</span> Establish_context()
    {
        _order = <span class="kwrd">new</span> Order(<span class="kwrd">new</span>[] { <span class="kwrd">new</span> OrderItem(12), 
                                   <span class="kwrd">new</span> OrderItem(16) });
        _totalAmountWithoutDiscount = _order.TotalAmount;
    }

    <span class="kwrd">protected</span> <span class="kwrd">override</span> <span class="kwrd">void</span> Because()
    {
        SUT.MakePreferred();
    }

    [Test]
    <span class="kwrd">public</span> <span class="kwrd">void</span> Then_no_additional_discount_should_be_applied_to_the_outstanding_orders()
    {
        _order.TotalAmount.ShouldNotBeEqualTo(
            _totalAmountWithoutDiscount * 0.81);
    }

    <span class="kwrd">private</span> Order _order;
    <span class="kwrd">private</span> Double _totalAmountWithoutDiscount;
}

<span class="rem">//</span>
<span class="rem">// Subject under test</span>
<span class="rem">//</span>
<span class="kwrd">public</span> <span class="kwrd">class</span> Customer
{
    <span class="kwrd">private</span> <span class="kwrd">readonly</span> List&lt;Order&gt; _orders;
    <span class="kwrd">public</span> Boolean IsPreferred { get; <span class="kwrd">private</span> set; }

    <span class="kwrd">public</span> Customer(IEnumerable&lt;Order&gt; orders)
    {
        _orders = <span class="kwrd">new</span> List&lt;Order&gt;(orders);
    }

    <span class="kwrd">public</span> <span class="kwrd">void</span> MakePreferred()
    {
        <span class="kwrd">if</span>(IsPreferred)    
            <span class="kwrd">return</span>;
    
        IsPreferred = <span class="kwrd">true</span>;
        _orders.ForEach(order =&gt; order.ApplyDiscount(10));
    }
}</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>The bottom line of this example is that preferred customers get a 10 percent discount. Customers that are already preferred do not get an additional discount or otherwise we’re out of business ;-). </p>

<p>I’ve been pretty happy with this approach so far, although sometimes there were some quirks associated with this. So it was time for me to look beyond the horizon again, trying to look for ways to improve. </p>

<p><a href="http://github.com/machine/machine.specifications">Machine.Specifications</a> or MSpec for short is something that has been on my ‘cool-things-to-learn-list’ for quite some time now. As you will see later in this post, the syntax is a bit different as one would come to expect from a context/specification framework that targets the C# programming language. Its seems to be heavily inspired by Scott Bellware’s <a href="http://code.google.com/p/specunit-net/">SpecUnit framework</a> and <a href="http://rspec.info/">RSpec</a>.</p>

<p>Lets see how to set things up first. </p>

<p>The most obvious starting point is downloading the bits and bytes. You can grab the <a href="http://github.com/machine/machine.specifications">source code</a> from GitHub and build it or you can wuss out like I did and get the latest build from the <a href="http://teamcity.codebetter.com/login.html">TeamCity.CodeBetter.com</a> builder server (you can log on as a guest and search the artifacts for a latest build).&#160; </p>

<p>When you’re heavily addicted to <a href="http://www.testdriven.net/">TestDriven.NET</a> like I am, then its possible to keep using this wonderful Visual Studio add-in for running MSpec context/specifications. Just create a directory named <em>Machine.Specifications</em> in {$Program_Files}\TestDriven.NET 2.0 and copy the following files:</p>

<ul>
  <li>Machine.Specifications.dll</li>

  <li>Machine.Specifications.TDNetRunner.dll</li>

  <li>InstallTDNetRunner.bat</li>
</ul>

<ul>Run the InstallTDNetRunner.bat file and you’re able to run all MSpec context/specifications using TestDriven.NET.</ul>

<p>I also strongly encourage you to install the plugin for the Resharper test runner (if only to prevent some Resharper warnings later on). First step is to add a directory named <em>Plugins</em> to the <em>Bin</em> directory of Resharper ({$Program_Files}\JetBrains\ReSharper\v4.5\Bin\). Then create a directory named <em>Machine.Specifications</em> in the <em>Plugins</em> directory you just created and copy the following files:</p>

<ul>
  <li>Machine.Specifications.dll</li>

  <li>Machine.Specifications.ReSharperRunner.4.5.dll</li>

  <li>InstallResharperRunner.4.5.bat</li>
</ul>

<p>Run the InstallResharperRunner.4.5.bat file and you’re also able to run MSpec context/specifications using the Resharper test runner.</p>

<p>I’m not going to put this off any longer. Lets look at the code of the context/specifications shown earlier but completely revamped using the MSpec syntax:</p>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<pre class="csharpcode">[Subject(<span class="str">&quot;Making a customer preferred&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_a_regular_customer_is_made_preferred 
{
    Establish context = () =&gt;
    {
        _order = <span class="kwrd">new</span> Order(<span class="kwrd">new</span>[] { <span class="kwrd">new</span> OrderItem(12), 
                                   <span class="kwrd">new</span> OrderItem(16) });
        _totalAmountWithoutDiscount = _order.TotalAmount;

        SUT = <span class="kwrd">new</span> Customer(<span class="kwrd">new</span>[] { _order });
    };

    Because of = () =&gt; 
        SUT.MakePreferred();

    It should_mark_the_customer_as_preferred = () =&gt;
        SUT.IsPreferred.ShouldBeTrue();
        
    It should_apply_a_ten_percent_discount_to_all_outstanding_orders = () =&gt;
        _order.TotalAmount.ShouldEqual(_totalAmountWithoutDiscount * 0.9);      

    <span class="kwrd">private</span> <span class="kwrd">static</span> Customer SUT;
    
    <span class="kwrd">private</span> <span class="kwrd">static</span> Order _order;
    <span class="kwrd">private</span> <span class="kwrd">static</span> Double _totalAmountWithoutDiscount;
}

[Subject(<span class="str">&quot;Making a customer preferred&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_a_preferred_customer_is_made_preferred
{
    Establish context = () =&gt;
    {
        _order = <span class="kwrd">new</span> Order(<span class="kwrd">new</span>[] { <span class="kwrd">new</span> OrderItem(12), 
                                   <span class="kwrd">new</span> OrderItem(16) });
        _totalAmountWithoutDiscount = _order.TotalAmount;

        SUT = <span class="kwrd">new</span> Customer(<span class="kwrd">new</span>[] { _order });
        SUT.MakePreferred();
    };

    Because of = () =&gt;
        SUT.MakePreferred();

    It should_apply_no_additional_discount_to_the_outstanding_orders = () =&gt; 
        _order.TotalAmount.ShouldNotEqual(_totalAmountWithoutDiscount * 0.81);

    <span class="kwrd">private</span> <span class="kwrd">static</span> Customer SUT;

    <span class="kwrd">private</span> <span class="kwrd">static</span> Order _order;
    <span class="kwrd">private</span> <span class="kwrd">static</span> Double _totalAmountWithoutDiscount;
}</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>I warned you about the syntax, didn’t I :-). It only took me a couple of seconds to get used to this syntax but now I’m completely hooked. Instead of using methods and attributes, MSpec utilizes delegates and anonymous methods. But there’s more. </p>

<p>When using <a href="http://www.nunit.com/index.php">NUnit</a> for writing context/ specifications, the <em>Establish_context</em> and <em>Because</em> methods of the example shown earlier is executed before every observation (test). With MSpec, the <em>Establish</em> and <em>Because</em> anonymous methods are executed only once for every context no matter how many observations a particular context class contains. Big difference? Well, at first glance not but on second hand it does make <a href="http://elegantcode.com/2008/12/30/dont-sell-out-on-the-context-dude/">selling out on the context</a> a bit more difficult as it will probably blow up in your face sooner than later. You can force MSpec to execute the <em>Establish</em> and <em>Because</em> anonymous methods before every observation by applying the <em>SetupForEachSpecification</em> attribute to the context class, but I strongly encourage you to stay away from that unless absolutely needed.</p>

<p>Also notice that the fields in the contexts are now all static. This is needed so that the anonymous methods can access those.&#160;&#160;&#160;&#160;&#160; </p>

<p>Running these context/specifications using TestDriven.NET yields the following output in the output window of Visual Studio:</p>

<blockquote>
  <p><font face="Arial">Making a customer preferred, when a regular customer is made preferred
      <br />» should mark the customer as preferred

      <br />» should apply a ten percent discount to all outstanding orders</font></p>

  <p><font face="Arial">Making a customer preferred, when a preferred customer is made preferred
      <br />» should apply no additional discount to the outstanding orders</font></p>
</blockquote>

<p>What’s not to like? Well, the only downside so far is that Resharper was giving me some warnings about classes and fields not being used etc. … . Many of those warnings disappeared by registering the MSpec plugin for the Resharper test runner as I explained earlier.</p>

<p>So far, so good. I’ve got two more posts coming up on MSpec, so stay tuned.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/02/19/getting-started-with-machine-specifications-mspec/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Unity/Moq &#8211; AutoMocker or AutoMockingContainer</title>
		<link>http://elegantcode.com/2010/01/03/unitymoq-automocker-or-automockingcontainer/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=unitymoq-automocker-or-automockingcontainer</link>
		<comments>http://elegantcode.com/2010/01/03/unitymoq-automocker-or-automockingcontainer/#comments</comments>
		<pubDate>Sun, 03 Jan 2010 16:52:33 +0000</pubDate>
		<dc:creator>Jason Jarrett</dc:creator>
				<category><![CDATA[TDD]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Tools and Utilities]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/01/03/unitymoq-automocker-or-automockingcontainer/</guid>
		<description><![CDATA[What is an Auto Mocking Container? This post started to get a little long, so I won’t re-explain the concept. Joshua Flanagan wrote a nice overview at his Los Techies blog: Auto mocking Explained. My post is mainly here to describe the Unity version of an automocking container I threw together. In Jan 2009 I [...]]]></description>
			<content:encoded><![CDATA[<h4>What is an Auto Mocking Container?</h4>  <p>This post started to get a little long, so I won’t re-explain the concept.</p>  <p><a href="http://www.lostechies.com/blogs/joshuaflanagan/default.aspx">Joshua Flanagan</a> wrote a nice overview at his <a href="http://www.lostechies.com/">Los Techies</a> blog: <a href="http://www.lostechies.com/blogs/joshuaflanagan/archive/2009/02/03/auto-mocking-explained.aspx"><strong>Auto mocking Explained</strong></a>.</p>  <p>My post is mainly here to describe the Unity version of an automocking container I threw together.</p>  <h4>In Jan 2009 I blogged about my initial version of the Unity AutoMocker - Why am I blogging about it again?</h4>  <p>I originally wrote the AutoMocker for the Unity container a year ago (Jan 2009, in Silverlight), and finally got around to placing the code up in the <a href="http://code.google.com/p/moq-contrib/">moq-contrib</a> project in June of 2009.</p>  <p>I’m writing another post today in hopes to:</p>  <ol>   <li>Get some feedback on how this little snippet of code should continue. </li>    <li>Give a little more how-to/example code </li>    <li>Describe some updates I made since I originally created it.&#160; </li> </ol>  <h4>Where can I get it?</h4>  <p><strong>This is one part where I’d appreciate some feedback.</strong></p>  <p>I have two slightly different versions out there (currently).</p>  <p>I have one version at the <a href="http://code.google.com/p/elegantcode/source/browse/#svn/trunk/Coders/JasonJarrett/UnityAutoMocker">ElegantCode</a> repository where I was working on it, and the other I threw up at <a href="http://code.google.com/p/moq-contrib/">moq-contrib</a>.</p>  <p>The core of the UnityAutoMockContainer is the same in both places, it’s how the tests are separated out that differ.</p>  <p>In the <a href="http://code.google.com/p/elegantcode/source/browse/#svn/trunk/Coders/JasonJarrett/UnityAutoMocker">ElegantCode repository</a> it’s an all in one self contained single file (that you can copy into your own test project(s)). You can then setup a single test in your own testing framework that runs all internal automocker tests (in case you need to modify it yourself, and don’t want to break any existing functionality). EX: test</p>  <pre class="brush: csharp;">[Test]
public void Should_run_all_UnityAutoMockContainer_internal_tests()
{
    Moq.AutoMocking.SelfTesting.UnityAutoMockContainerFixture
        .RunAllTests(Console.WriteLine);
}</pre>

<p>I kind of like this format as it makes it easy to port between test libraries. Can’t say I like having the tests in the same file as the core, but it certainly is not a large chunk of code (so far) so it’s relatively small to maintain and definitely easier to manage as a single .cs file than another assembly (which would have to be version dependent on both Unity and Moq).</p>

<p>The <a href="http://code.google.com/p/moq-contrib/">moq-contrib</a> is definitely where I think this helper should end up (and it is there). I just happened to break the tests out into the Silverlight test project and the core is alone in a file. </p>

<p>It’s current state isn’t as easy to copy to a test library (Silverlight/Desktop/Unity 1.2/Unity 2.0) as the one at <a href="http://elegantcode.com/">ElegantCode</a>. <strong>What does anyone think?</strong> Should I put them all together in one file?</p>

<p>However it ends up (1. all in one file or two (1 test) (1 core)) it will continue to be maintained on the <a href="http://code.google.com/p/moq-contrib/">moq-contrib</a> project.</p>

<h4>What is the high level API of the container?</h4>

<p>It’s pretty simple, (currently) there are four methods on the container.</p>

<p><strong>Two for registering items with the container</strong>. Say you want to register an already created instance, or say you want to map an interface to a concrete class and _not_ have the container generate mocks automatically for special cases. </p>

<p>And <strong>two for pulling items out of the container</strong>. Whether you want a instance of T or a Mock&lt;T&gt;, it gives you ways to retrieve both.</p>

<blockquote>
  <p><a href="http://elegantcode.com/wp-content/uploads/2010/01/image.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://elegantcode.com/wp-content/uploads/2010/01/image_thumb.png" width="396" height="106" /></a> </p>
</blockquote>

<h4>How can I setup my own registrations with the container? </h4>

<p>Say I don’t want to have the container generate mocks for specific items and I want to supply specific configuration to the UnityContainer.</p>

<blockquote>
  <p>public UnityAutoMockContainer RegisterInstance&lt;TService&gt;(TService instance)</p>

  <p>public UnityAutoMockContainer Register&lt;TService, TImplementation&gt;() 
    <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; where TImplementation : TService</p>
</blockquote>

<p><strong>Note</strong>: both of these registration methods return the container itself so you can fluently stack registration. <strong>EX:</strong></p>

<pre class="brush: csharp;">AutoMockContainer
    .Register&lt;IServiceA, ServiceA&gt;()
    .Register&lt;IServiceB, ServiceB&gt;();</pre>

<p><strong>Let me know</strong>: I haven’t tested or played around with how this automocking container deals with any container specific xml configuration… So although I don’t think you should probably have that in a test assembly (stuff happens). Let me know if there are any issues.</p>

<h4>How do I get items out of the container?</h4>

<p>First is the Resolve&lt;T&gt;(). It will pull an item T out of the container. (Creating it if not already existing)</p>

<blockquote>
  <p>public T Resolve&lt;T&gt;()</p>
</blockquote>

<p>When T is an interface Resolve&lt;T&gt; (unless you setup registration specifically with the container) should return basically “(new Mock&lt;T&gt;()).Object”</p>

<p>When T is a concrete Class, the container should return an instance of T and any of it’s dependencies will be satisfied by mocks. (Note that T will not be any sort of mocked instance of T, unless you used the GetMock&lt;T&gt; as described below first)</p>

<blockquote>
  <p>public Mock&lt;T&gt; GetMock&lt;T&gt;() where T : class</p>
</blockquote>

<p>When T is an interface GetMock&lt;T&gt; should return basically “(new Mock&lt;T&gt;())” </p>

<p>When T is a concrete Class, the container should return a new Mock&lt;T&gt;() and any of it’s dependencies will be satisfied by mocks.</p>

<h4>How do I use the UnityAutoMockContainer?</h4>

<p>It’s pretty basic, you first create an instance of the UnityAutoMockContainer, and from there you can ask it for mocks of an (Interface, Class, or Abstract Class).</p>

<p>If you request an instance of a concrete class, or abstract class, the UnityAutoMockContainer will stuff mocks in for any constructor dependencies of your concrete class (if it can). You can then request from the container those same dependencies one at a time and either apply mocking setups or verifications.</p>

<blockquote>
  <p><strong>NOTE:</strong> Anything the container creates will live as a singleton instance in the container. So any other requests from the container will always return the originally created instance. Therefore, each distinct scenario in a test suite should have their own instances of the container.</p>
</blockquote>

<p>Below his an example of how you can leverage the container in some tests. Given this base fixture class…</p>

<pre class="brush: csharp;">public class FixtureBase
{
    private readonly UnityAutoMockContainer _autoMockContainer = new UnityAutoMockContainer();

    protected UnityAutoMockContainer AutoMockContainer
    {
        get { return _autoMockContainer; }
    }

    [TestFixtureSetUp]
    public void SetupContext_ALL()
    {
        Before_all_tests();
        Because();
    }

    [TestFixtureTearDown]
    public void TearDownContext_ALL()
    {
        After_all_tests();
    }

    protected virtual void Before_all_tests()
    {
    }

    protected virtual void Because()
    {
    }

    protected virtual void After_all_tests()
    {
    }
}</pre>

<p>If I were given the following system to test.</p>

<pre class="brush: csharp;">public interface IServiceA { void RunA(); }
public interface IServiceB { void RunB(); }

public class TestComponent
{
    public TestComponent(IServiceA serviceA, IServiceB serviceB)
    {
        ServiceA = serviceA;
        ServiceB = serviceB;
    }

    public IServiceA ServiceA { get; private set; }
    public IServiceB ServiceB { get; private set; }

    public void RunAll()
    {
        if (!HowDidItGo())
            return;
        ServiceA.RunA();
        ServiceB.RunB();
    }

    public virtual bool HowDidItGo()
    {
        // some really nasty untestable code
        return true;
    }
}</pre>

<p>The below example demonstrates simply verifying some behavior on the mocked dependencies of the system under test.</p>

<pre class="brush: csharp;">[TestFixture]
public class Example__how_to_pull_items_from_the_UnityAutoMockContainer_when_verifying_behavior_after_an_action_was_taken 
    : FixtureBase
{
    private TestComponent _testComponent;

    protected override void Before_all_tests()
    {
        base.Before_all_tests();
        _testComponent = AutoMockContainer.Resolve&lt;TestComponent&gt;();
    }

    protected override void Because()
    {
        _testComponent.RunAll();
    }

    [Test]
    public void Should_run_ServiceA_RunA()
    {
        AutoMockContainer
            .GetMock&lt;IServiceA&gt;()
            .Verify(v =&gt; v.RunA(), Times.Once());
    }

    [Test]
    public void Should_run_ServiceB_RunB()
    {
        AutoMockContainer
            .GetMock&lt;IServiceB&gt;()
            .Verify(v =&gt; v.RunB(), Times.Once());
    }
}</pre>

<p>Next, you may have noticed that the system under test had a complicated internal method (that may not necessarily be testable). You can use the AutoMocker to create the system under test as a Mock itself, so we can override some of the behavior. Here’s how you could quickly do that. </p>

<blockquote>
  <p><strong>Aside</strong>: I’m not saying this is a good practice or aids in good component design, just saying it’s possible</p>
</blockquote>

<pre class="brush: csharp;">[TestFixture]
public class Example__how_to_use_the_UnityAutoMockContainer_to_override_a_method_on_the_SystemUnderTest_to_test_a_certain_behavior
    : FixtureBase
{

    private TestComponent _testComponent;

    protected override void Before_all_tests()
    {
        base.Before_all_tests();
        var mockTestComponent = AutoMockContainer.GetMock&lt;TestComponent&gt;();

        mockTestComponent
            .Setup(s =&gt; s.HowDidItGo())
            .Returns(false);

        _testComponent = mockTestComponent.Object;
    }

    protected override void Because()
    {
        _testComponent.RunAll();
    }

    [Test]
    public void Should_run_ServiceA_RunA()
    {
        AutoMockContainer
            .GetMock&lt;IServiceA&gt;()
            .Verify(v =&gt; v.RunA(), Times.Never());
    }

    [Test]
    public void Should_run_ServiceB_RunB()
    {
        AutoMockContainer
            .GetMock&lt;IServiceB&gt;()
            .Verify(v =&gt; v.RunB(), Times.Never());
    }
}</pre>

<p>&#160;</p>

<p>It’s amazing how much redundant test setup code this little helper has saved me in my tests. I hope others can find some use with this as well.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/01/03/unitymoq-automocker-or-automockingcontainer/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>StatLight &#8211; Goes Open Source</title>
		<link>http://elegantcode.com/2009/12/10/statlight-goes-open-source/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=statlight-goes-open-source</link>
		<comments>http://elegantcode.com/2009/12/10/statlight-goes-open-source/#comments</comments>
		<pubDate>Fri, 11 Dec 2009 03:26:55 +0000</pubDate>
		<dc:creator>Jason Jarrett</dc:creator>
				<category><![CDATA[Esoterica]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[TDD]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Tools and Utilities]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/12/10/statlight-goes-open-source/</guid>
		<description><![CDATA[Although I made a very minor attempt at making StatLight a “for-sale” product, I knew when I started that open-source was most likely going to be my long term path for StatLight. What is it? (Silverlight Testing Automation Tool) StatLight is a tool developed for automating the setup, running, and gathering results of Silverlight unit [...]]]></description>
			<content:encoded><![CDATA[Although I made a very minor attempt at making <a href="http://statlight.net" target="_blank">StatLight</a> a “for-sale” product, I knew when I started that open-source was most likely going to be my long term path for <a href="http://statlight.net" target="_blank">StatLight</a>.
<h5>What is it? (Silverlight Testing Automation Tool)</h5>
StatLight is a tool developed for automating the setup, running, and gathering results of Silverlight unit tests. StatLight helps to speed up the feedback cycles while practicing<a href="http://en.wikipedia.org/wiki/Test-driven_development"> TDD</a>/<a href="http://en.wikipedia.org/wiki/Behavior_Driven_Development">BDD</a>/(insert your test style here) during Silverlight development.
<h5>Where can I get StatLight?</h5>
<a href="http://StatLight.CodePlex.com">http://StatLight.CodePlex.com</a>
<h4>Happy Coding !!!</h4>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/12/10/statlight-goes-open-source/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Wrapping up the StructureMap Automocking Container</title>
		<link>http://elegantcode.com/2009/11/30/wrapping-up-the-structuremap-automocking-container/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=wrapping-up-the-structuremap-automocking-container</link>
		<comments>http://elegantcode.com/2009/11/30/wrapping-up-the-structuremap-automocking-container/#comments</comments>
		<pubDate>Mon, 30 Nov 2009 07:21:43 +0000</pubDate>
		<dc:creator>Richard Cirerol</dc:creator>
				<category><![CDATA[TDD]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Unit Testing]]></category>
		<category><![CDATA[StructureMap; Automocking; MSpec;]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/11/30/wrapping-up-the-structuremap-automocking-container/</guid>
		<description><![CDATA[<p><font color="#804040"><strong>UPDATE</strong>: I apologize…the original wrapper did not allow injected dependencies.&#160; I have fixed this bug and updated the sample.</font></p> I have been using StructureMap.AutoMocking with MSpec (Machine.Specifications) and Rhino.Mocks for a few months now.  Although I am very comfortable with the patterns that emerge from using the frameworks together, introducing StructureMap.Automocking to other developers is sometimes challenging. I decided to wrap the details of the container to make the intention clearer and explanation easier.  I have started using this wrapper in my projects, and have found it makes building up specifications more efficient in my daily coding.]]></description>
			<content:encoded><![CDATA[<span style="color: #804040;"><strong>UPDATE</strong>: I apologize…the original wrapper did not allow injected dependencies.  I have fixed this bug and updated the sample.</span>

I have been using StructureMap.AutoMocking with MSpec (Machine.Specifications) and Rhino.Mocks for a few months now.  Although I am very comfortable with the patterns that emerge from using the frameworks together, introducing StructureMap.Automocking to other developers is sometimes challenging.

When viewing a specification or test set up with the Rhino.Mocks or Moq automocking container, what is being tested is not readily apparent.  Once the concept is explained and demonstrated, these same developers seem to have no issue with maintaining the specifications/tests.

I decided to wrap the details of the container to make the intention clearer and explanation easier.  I have started using this wrapper in my projects, and have found it makes building up specifications more efficient in my daily coding.

Let me know whether this is useful to you, or how it could be made more useful.
<h4>The Examples</h4>
Let’s contrive an example.  We’ll say we have a coffee machine that grinds its own beans before brewing. However, the hopper has to have beans before starting the grind.  Here is the basic specification:
<table border="1" cellspacing="0" cellpadding="2" width="533">
<tbody>
<tr>
<td width="117" valign="top">Action/Behavior</td>
<td width="414" valign="top">Prepare coffee grounds for 12 cups of coffee</td>
</tr>
<tr>
<td rowspan="2" width="117" valign="top">Expectations</td>
<td width="414" valign="top">Should check that hopper has beans (mock returns true)</td>
</tr>
<tr>
<td width="414" valign="top">Because hopper has beans, should ask grinder to grind enough beans for 12 cups of coffee</td>
</tr>
</tbody></table>
We could start without a container, using Rhino.Mocks to build up the CoffeeMachine dependencies manually:
<pre class="brush: csharp;">[Subject(typeof(CoffeeMachine),"using vanilla Rhino.Mocks")]
public class Example01_when_preparing_coffee_grounds
{
    Establish context = () =&gt;
        {
            Grinder = MockRepository.GenerateMock&lt;IGrinder&gt;();
            Hopper = MockRepository.GenerateMock&lt;IHopper&gt;();
            Hopper.Expect(x =&gt; x.HasBeans()).Return(true);
            CoffeeMachine = new CoffeeMachine(Grinder, Hopper);
        };

    Because of = () =&gt; _coffeeMachine.PrepareCoffeeGrounds(12);

    It should_check_if_hopper_has_beans = () =&gt; Hopper.VerifyAllExpectations();
    It should_grind_coffee = () =&gt; Grinder.AssertWasCalled(x =&gt; x.Grind(12));

    static IGrinder Grinder;
    static IHopper Hopper;
    static CoffeeMachine CoffeeMachine;
}</pre>
For those of you not familiar with the MSpec style, please refer to the following posts:
<ul>
	<li><a href="http://blog.wekeroad.com/blog/make-bdd-your-bff-2/" target="_blank">Make BDD Your BFF</a></li>
	<li><a href="http://www.lostechies.com/blogs/seanbiefeld/archive/2009/08/25/step-by-step-to-using-machine-specifications-with-resharper.aspx" target="_blank">Step by Step to Using MSpec (Machine.Specifications) with ReSharper</a></li>
	<li><a href="http://elegantcode.com/2009/07/05/mspec-take-2/" target="_blank">MSpec - Take 2</a></li>
	<li><a href="http://marcinobel.com/index.php/mspec-bdd-installer/" target="_blank">MSpec BDD framework installer</a></li>
	<li><strong>Updated! </strong>From the <a href="http://blog.cwa.me.uk/2009/11/30/the-morning-brew-487/" target="_blank">Morning Brew #487</a>: BDD with MSpec and Rhino Auto Mocks, parts  <a href="http://telldontask.wordpress.com/2009/11/10/bdd-with-mspec-and-rhino-auto-mocks/" target="_blank">1</a>, <a href="http://telldontask.wordpress.com/2009/11/19/bdd-with-mspec-and-rhino-auto-mocks-part-2/" target="_blank">2</a>, and <a href="http://telldontask.wordpress.com/2009/11/29/bdd-with-mspec-and-rhino-auto-mocks-part-3/" target="_blank">3</a>
Here is the same specification using the RhinoAutoMocker&lt;T&gt; class provided by StructureMap.AutoMocking:</li>
</ul>
<pre class="brush: csharp;">[Subject(typeof(CoffeeMachine),"using RhinoAutoMocker&lt;CoffeeMachine&gt;")]
public class Example02_when_preparing_coffee_grounds
{
    Establish context = () =&gt;
        {
            CoffeeMachine = new RhinoAutoMocker&lt;CoffeeMachine&gt;();
            Grinder = CoffeeMachine.Get&lt;IGrinder&gt;();
            Hopper = CoffeeMachine.Get&lt;IHopper&gt;();
            Hopper.Expect(x =&gt; x.HasBeans()).Return(true);
        };

    Because of = () =&gt; v.ClassUnderTest.PrepareCoffeeGrounds(12);

    It should_check_if_hopper_has_beans = () =&gt; Hopper.VerifyAllExpectations();
    It should_grind_coffee = () =&gt; Grinder.AssertWasCalled(x =&gt; x.Grind(12));

    static IGrinder Grinder;
    static IHopper Hopper;
    static RhinoAutoMocker&lt;CoffeeMachine&gt; CoffeeMachine;
}</pre>
Although I think this looks cleaner, the initialization of CoffeeMachine causes some confusion. Unfortunately, a common question would be, “Is RhinoAutoMocker&lt;CoffeeMachine&gt; creating a mocked version of CoffeeMachine?” Well, not exactly.

RhinoAutoMocker is an implementation of the AutoMocker base class which uses StructureMap to fill dependencies.  The RhinoAutoMocker implementation of the container uses Rhino.Mocks to generate all of dependencies of the target class, whereas the MoqAutoMocker implementation uses Moq.  (Optionally, the target class can be partially mocked in order to further isolate behavior.)  We then retrieve the class under test (in this case, CoffeeMachine) and its dependencies (IGrinder and IHopper) from the container for use.

If you do not need to setup any expectations in the specification, there is no need to retrieve the dependency from the container.  However, in this specification, we need both dependencies.

<em>(Incidentally, I do not like the ClassUnderTest name.  I may end up changing this to Instance, ClassInstance, TargetClass, or something similar.  Suggestions?)</em>

By moving the initialization of the RhinoAutoMocker to a base class, some of the chattiness of the context can be hidden.
<ul>
<pre class="brush: csharp;">[Subject(typeof(CoffeeMachine),"using RhinoAutoMocker base")]
public class Example03_when_preparing_coffee_grounds : with_rhinoautomocker
{
    Establish context = () =&gt; Hopper.Expect(x =&gt; x.HasBeans()).Return(true);

    Because of = () =&gt; CoffeeMachine.ClassUnderTest.PrepareCoffeeGrounds(12);

    It should_check_if_hopper_has_beans = () =&gt; Hopper.VerifyAllExpectations();
    It should_grind_coffee = () =&gt; Grinder.AssertWasCalled(x =&gt; x.Grind(12));

}

[Subject("using RhinoAutoMocker&lt;T&gt;")]
public class with_rhinoautomocker
{
    protected static IGrinder Grinder;
    protected static IHopper Hopper;
    protected static RhinoAutoMocker&lt;CoffeeMachine&gt; CoffeeMachine;

    Establish context = () =&gt;
    {
        CoffeeMachine = new RhinoAutoMocker&lt;CoffeeMachine&gt;();
        Grinder = CoffeeMachine.Get&lt;IGrinder&gt;();
        Hopper = CoffeeMachine.Get&lt;IHopper&gt;();
    };
}</pre>
However, we are still initializing and accessing the class in a less than optimal manner.To make the usage of the container a little more seamless, I decided to create a wrapper and factory for the AutoMocker.  Setup of the dependencies and expectations are done through an AutoMocker wrapper object.  The instance of the class under test is accessed through a ClassUnderTest object.
<h4>The Result</h4>
The specification (and base class) now look like this:
<pre class="brush: csharp;">[Subject(typeof(CoffeeMachine),"using coffee machine base")]
public class Example05_when_preparing_coffee_grounds : with_coffee_machine
{
    Establish context = () =&gt; Hopper.Expect(x =&gt; x.HasBeans()).Return(true);

    Because of = () =&gt; ClassUnderTest.PrepareCoffeeGrounds(12);

    It should_check_if_hopper_has_beans = () =&gt; Hopper.VerifyAllExpectations();
    It should_grind_coffee = () =&gt; Grinder.AssertWasCalled(x =&gt; x.Grind(12));
}

[Subject("using SpecificationFor&lt;CoffeeMachine&gt;")]
public class with_coffee_machine : SpecificationFor&lt;CoffeeMachine&gt;
{
    protected static IGrinder Grinder;
    protected static IHopper Hopper;

    public with_coffee_machine
    {
        Grinder = AutoMocker.Get&lt;IGrinder&gt;();
        Hopper = AutoMocker.Get&lt;IHopper&gt;();
    }
}</pre>
As you can see, the base class inherits from SpecificationFor&lt;T&gt;.  The default constructor uses Rhino.Mocks(MockMode.AAA) to generate the dependencies.  It then exposes a AutoMocker object, which is just the wrapper around the AutoMocker base class.  It also exposes a ClassUnderTest object.  If I didn’t need to use the dependencies, I could make the <em>Example05_when_preparing_coffee_grounds</em> class inherit from <em>SpecificationFor&lt;CoffeeMachine&gt; </em>instead of inheriting from the base class<em>.</em>
<h4>The Code</h4>
I have included the code for the wrapper below for your review.  The code and six examples are available on my <a href="http://codeprogression.googlecode.com/svn/trunk/CodeProgression.Framework.Testing" target="_blank">Google code repository</a>. The repository also includes an example using the MoqAutoMocker.  All the examples have the same assertions, but are built up using the different techniques.
<pre class="brush: csharp;">namespace CodeProgression.Framework.Testing
{
    public abstract class SpecificationFor&lt;T&gt; where T: class
    {
        protected static ClassUnderTest&lt;T&gt; Factory;

        // UPDATE 2009-12-21:
        //   Moved initialization here
        protected static T ClassUnderTest {get {return AutoMocker.Instance;} }

        protected SpecificationFor()
        {
            AutoMocker = AutoMockFactory.CreateTarget&lt;T&gt;();

            // UPDATE 2009-12-21:
            //    Initializing here prevented injected dependencies!
            // AutoMocker.PartialMockTheClassUnderTest();
            // ClassUnderTest = AutoMocker.Instance;
        }

        protected SpecificationFor(AutoMockType type)
        {
            AutoMocker = AutoMockFactory.CreateTarget&lt;T&gt;(type);

            // UPDATE 2009-12-21:
            // Initializing here prevented injected dependencies!
            // AutoMocker.PartialMockTheClassUnderTest();
            // ClassUnderTest = AutoMocker.Instance;
        }
    }

    public static class AutoMockFactory
    {
        public static ClassUnderTest&lt;TARGETCLASS&gt; CreateTarget&lt;TARGETCLASS&gt;() where TARGETCLASS : class
        {
            return CreateTarget&lt;TARGETCLASS&gt;(AutoMockType.RhinoMocksAAA);
        }

        public static ClassUnderTest&lt;TARGETCLASS&gt; CreateTarget&lt;TARGETCLASS&gt;(AutoMockType framework) where TARGETCLASS : class
        {
            AutoMocker&lt;TARGETCLASS&gt; mocker;
            ServiceLocator serviceLocator;
            switch (framework)
            {
                case AutoMockType.RhinoMocksAAA:
                    mocker = new RhinoAutoMocker&lt;TARGETCLASS&gt;(MockMode.AAA);
                    serviceLocator = new RhinoMocksAAAServiceLocator();
                    break;
                case AutoMockType.RhinoMocksClassic:
                    mocker = new RhinoAutoMocker&lt;TARGETCLASS&gt;(MockMode.RecordAndReplay);
                    serviceLocator = new RhinoMocksClassicServiceLocator();
                    break;
                case AutoMockType.Moq:
                    mocker = new MoqAutoMocker&lt;TARGETCLASS&gt;();
                    serviceLocator = new MoqServiceLocator();
                    break;
                default:
                    throw new ArgumentOutOfRangeException("framework");
            }
            return new ClassUnderTest&lt;TARGETCLASS&gt;(mocker, serviceLocator);
        }
    }

    public enum AutoMockType
    {
        Moq,
        RhinoMocksAAA,
        RhinoMocksClassic
    }

    public class ClassUnderTest&lt;TARGETCLASS&gt; where TARGETCLASS : class
    {
        readonly IAutoMocker&lt;TARGETCLASS&gt; _mocker;
        readonly ServiceLocator _serviceLocator;

        public ClassUnderTest(IAutoMocker&lt;TARGETCLASS&gt; mocker, ServiceLocator serviceLocator)
        {
            _mocker = mocker;
            _serviceLocator = serviceLocator;
        }

        public AutoMockedContainer Container
        {
            get { return _mocker.Container; }
        }

        public TARGETCLASS Instance
        {
            get { return _mocker.ClassUnderTest; }
        }

        public void MockObjectFactory()
        {
            _mocker.MockObjectFactory();
        }

        public void PartialMockTheClassUnderTest()
        {
            _mocker.PartialMockTheClassUnderTest();
        }

        public T Get&lt;T&gt;() where T : class
        {
            return _mocker.Get&lt;T&gt;();
        }

        public void Inject(Type pluginType, object stub)
        {
            _mocker.Inject(pluginType, stub);
        }

        public void Inject&lt;T&gt;(T target)
        {
            _mocker.Inject(target);
        }

        public T AddAdditionalMockFor&lt;T&gt;() where T : class
        {
            return _mocker.AddAdditionalMockFor&lt;T&gt;();
        }

        public void UseConcreteClassFor&lt;T&gt;()
        {
            _mocker.UseConcreteClassFor&lt;T&gt;();
        }

        public T[] CreateMockArrayFor&lt;T&gt;(int count) where T : class
        {
            return _mocker.CreateMockArrayFor&lt;T&gt;(count);
        }

        public void InjectArray&lt;T&gt;(T[] stubs)
        {
            _mocker.InjectArray(stubs);
        }

        public T Mock&lt;T&gt;() where T : class
        {
            return _serviceLocator.Service&lt;T&gt;();
        }
        public object Mock(Type serviceType)
        {
            return _serviceLocator.Service(serviceType);
        }
        public T PartialMock&lt;T&gt;() where T : class
        {
            return _serviceLocator.PartialMock&lt;T&gt;();
        }
    }
}</pre>
</ul>
<script type="text/javascript">// <![CDATA[
 var cirerolGaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."); document.write(unescape("%3Cscript src='" + cirerolGaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
// ]]&gt;</script>

<script type="text/javascript">// <![CDATA[
 var cirerolPageTracker = _gat._getTracker('UA-8257866-3'); cirerolPageTracker._initData(); cirerolPageTracker._trackPageview();
// ]]&gt;</script>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/11/30/wrapping-up-the-structuremap-automocking-container/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Integration Test Brought to you by Powershell &amp; NUnit &#8211; with a Little Specification Syntax for Flavoring</title>
		<link>http://elegantcode.com/2009/10/25/integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring</link>
		<comments>http://elegantcode.com/2009/10/25/integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring/#comments</comments>
		<pubDate>Mon, 26 Oct 2009 05:00:40 +0000</pubDate>
		<dc:creator>Jason Jarrett</dc:creator>
				<category><![CDATA[Esoterica]]></category>
		<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/10/25/integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring/</guid>
		<description><![CDATA[One of the tools I’ve used the last half of a year and really enjoyed is the C# specification extension methods when writing unit test assertions. If you’re looking for a little more background on the topic, I wrote about Fluent Specification Extensions in a past blog. Recently I wanted to execute a PowerShell script [...]]]></description>
			<content:encoded><![CDATA[One of the tools I’ve used the last half of a year and really enjoyed is the C# specification extension methods when writing unit test assertions. If you’re looking for a little more background on the topic, I wrote about <a href="http://staxmanade.blogspot.com/2009/02/fluent-specification-extensions.html">Fluent Specification Extensions</a> in a past blog.

Recently I wanted to execute a PowerShell script to do some automated <a href="http://en.wikipedia.org/wiki/Functional_testing">functional testing</a>. I wanted to execute an application and apply some assertions on the output of the software(basically running a console app, parse the xml output and assert on values in the output).
<blockquote>FYI: I’m very new to PowerShell, so any suggestions on how I implemented the below are welcome…</blockquote>
I’ve seen a couple examples of writing test assertions in PowerShell out there. One example is <a href="http://www.psunit.org/">PSUnit</a>; however, this seemed a little heavy for my needs and not quite the syntactic sugar I was looking for.

Besides the syntax flavor I was desiring, another thing I wanted to do was leverage the power of NUnit.Framework’s assertion capabilities. I like the error messages generated when strings and other objects fail the assertion.
<h5>Examples of end result ShouldLookLike()…</h5>
$true.ShouldBeTrue()
$false.ShouldBeFalse()
"a".ShouldEqual("a")
"a".ShouldNotEqual("b")
<h5><strong>Step 1</strong>: Figure out how to write a C# style <a href="http://msdn.microsoft.com/en-us/library/bb383977.aspx">extension method</a> in PowerShell.</h5>
<blockquote>I found a great blog post describing how to extend any PowerShell object to add extension methods.

<a href="http://bartdesmet.net/blogs/bart/archive/2007/09/06/extension-methods-in-windows-powershell.aspx">Extension Methods in Windows PowerShell</a></blockquote>
In short, to extend types in PowerShell leveraging the <a href="http://msdn.microsoft.com/en-us/library/ms714419(VS.85).aspx">Extended Type System</a>, you need to define them in an xml file and import the method definitions into the PowerShell runtime instance.

Below is PowerShell XML definition for my NUnit Specification Extensions.
<pre class="brush: xml;">&lt;?xml version="1.0" encoding="utf-16"?&gt;
&lt;Types&gt;
    &lt;Type&gt;
        &lt;Name&gt;System.Object&lt;/Name&gt;
        &lt;Members&gt;
            &lt;ScriptMethod&gt;
                &lt;Name&gt;ShouldBeFalse&lt;/Name&gt;
                &lt;Script&gt;
                    [NUnit.Framework.Assert]::IsFalse($this)
                &lt;/Script&gt;
            &lt;/ScriptMethod&gt;
            &lt;ScriptMethod&gt;
                &lt;Name&gt;ShouldBeTrue&lt;/Name&gt;
                &lt;Script&gt;
                    [NUnit.Framework.Assert]::IsTrue($this)
                &lt;/Script&gt;
            &lt;/ScriptMethod&gt;
            &lt;ScriptMethod&gt;
                &lt;Name&gt;ShouldEqual&lt;/Name&gt;
                &lt;Script&gt;
                    [NUnit.Framework.Assert]::AreEqual($args[0], $this)
                &lt;/Script&gt;
            &lt;/ScriptMethod&gt;
            &lt;ScriptMethod&gt;
                &lt;Name&gt;ShouldNotEqual&lt;/Name&gt;
                &lt;Script&gt;
                    [NUnit.Framework.Assert]::AreNotEqual($args[0], $this)
                &lt;/Script&gt;
            &lt;/ScriptMethod&gt;
        &lt;/Members&gt;
    &lt;/Type&gt;
&lt;/Types&gt;</pre>
<h4></h4>
Take the above XML and save it to a file…
<blockquote>NOTE: the file HAS to be saved with the extension <strong>.ps1xml</strong>

Ex: NunitSpecificationPowerShellExtensions<strong>.ps1xml</strong></blockquote>
<h4></h4>
<h5>Step 2: Load the extended type definition into the PowerShell runtime.</h5>
Once you’ve saved the XML extended types to a file, you need to load it into the PowerShell runtime by executing the command below.
<blockquote>
Update-TypeData -PrependPath NunitSpecificationPowerShellExtensions.ps1xml</blockquote>
Before executing the above statement…Let’s quickly look at a System.String’s members and properties – just to show you what the extension methods look like when applied inside of the runtime.<a href="http://elegantcode.com/wp-content/uploads/2009/10/image3.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" src="http://elegantcode.com/wp-content/uploads/2009/10/image_thumb2.png" border="0" alt="image" width="586" height="479" /></a>

After executing the Update-TypeData command you’ll notice there are a number of “ScriptMethod” MemberTypes added to the object.

<a href="http://elegantcode.com/wp-content/uploads/2009/10/image4.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" src="http://elegantcode.com/wp-content/uploads/2009/10/image_thumb3.png" border="0" alt="image" width="600" height="580" /></a>

Now if you try to execute one of those newly added extension methods, you may get the following error…

PS C:\&gt; $testVar.<strong>ShouldEqual</strong>("hello world")

Exception calling "ShouldEqual" with "1" argument(s): "<strong>Unable to find type [NUnit.Framework.Assert]: make sure that the

assembly containing this type is loaded.</strong>"

At line:1 char:21

+ $testVar.ShouldEqual &lt;&lt;&lt;&lt; ("hello world")

+ CategoryInfo          : NotSpecified: (:) [], MethodInvocationException

+ FullyQualifiedErrorId : ScriptMethodRuntimeException

This is because we need to load the NUnit.Framework assembly into the runtime before we can leverage the extension methods.
<blockquote>[System.Reflection.Assembly]::LoadFrom("C:\Program Files\NUnit 2.5.2\bin\net-2.0\framework\nunit.framework.dll") | Out-Null</blockquote>
Now that the extension methods have been defined and loaded into the runtime, NUnit.Framework is loaded, we can now use the methods on any object that inherits from System.Object (which, as far as I know, is everything in PowerShell).

And now, everything you need in one script (if you have the xml extended type file saved somewhere…)
<pre>#
# Update-TypeData -prependPath C:\Code\NunitSpecificationPowerShellExtensions.ps1xml
#

[System.Reflection.Assembly]::LoadFrom("C:\Program Files\NUnit 2.5.2\bin\net-2.0\framework\nunit.framework.dll") | Out-Null

$true.ShouldBeTrue()

$false.ShouldBeFalse()

"a".ShouldEqual("a")

"a".ShouldNotEqual("b")</pre>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/10/25/integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Visual Studio Team System for Small Teams</title>
		<link>http://elegantcode.com/2010/02/19/getting-started-with-machine-specifications-mspec/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=getting-started-with-machine-specifications-mspec</link>
		<comments>http://elegantcode.com/2010/02/19/getting-started-with-machine-specifications-mspec/#comments</comments>
		<pubDate>Fri, 19 Feb 2010 21:34:17 +0000</pubDate>
		<dc:creator>Jan Van Ryswyck</dc:creator>
				<category><![CDATA[BDD]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/02/19/getting-started-with-machine-specifications-mspec/</guid>
		<description><![CDATA[Its been a while since I evaluated and evolved my approach to BDD. The way I’ve been doing BDD up until now is described in this blog post which goes way back to 2008. Everyone has kind of their own style nowadays. Below you can find the code of two context/specifications for a method named [...]]]></description>
			<content:encoded><![CDATA[<p>Its been a while since I evaluated and evolved my approach to BDD. The way I’ve been doing BDD up until now is described in <a href="http://elegantcode.com/2008/10/25/refining-contextspecification-bdd-using-rhino-mocks-35/">this blog post</a> which goes way back to 2008. Everyone has kind of their own style nowadays. Below you can find the code of two context/specifications for a method named <em>MakePreferred</em> on a <em>Customer </em>class. This simple example clarifies the style that I’ve been following up until now.</p> <style type="text/css">


.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style><style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>  <pre class="csharpcode">[TestFixture]
<span class="kwrd">public</span> <span class="kwrd">class</span> When_making_a_regular_customer_preferred
    : ContextSpecification&lt;Customer&gt;
{
    <span class="kwrd">protected</span> <span class="kwrd">override</span> Customer Create_subject_under_test()
    {
        <span class="kwrd">return</span> <span class="kwrd">new</span> Customer(<span class="kwrd">new</span>[] { _order });
    }

    <span class="kwrd">protected</span> <span class="kwrd">override</span> <span class="kwrd">void</span> Establish_context()
    {
        _order = <span class="kwrd">new</span> Order(<span class="kwrd">new</span>[] { <span class="kwrd">new</span> OrderItem(12), 
                                   <span class="kwrd">new</span> OrderItem(16) });
                                   
        _totalAmountWithoutDiscount = _order.TotalAmount;
    }

    <span class="kwrd">protected</span> <span class="kwrd">override</span> <span class="kwrd">void</span> Because()
    {
        SUT.MakePreferred();
    }

    [Test]
    <span class="kwrd">public</span> <span class="kwrd">void</span> Then_the_customer_should_be_marked_as_preferred()
    {
        SUT.IsPreferred.ShouldBeTrue();
    }

    [Test]
    <span class="kwrd">public</span> <span class="kwrd">void</span> Then_a_ten_percent_discount_should_be_applied_to_all_outstanding_orders()
    {
        _order.TotalAmount.ShouldBeEqualTo(
            _totalAmountWithoutDiscount * 0.9);
    }

    <span class="kwrd">private</span> Order _order;
    <span class="kwrd">private</span> Double _totalAmountWithoutDiscount;
}

[TestFixture]
<span class="kwrd">public</span> <span class="kwrd">class</span> When_making_a_preferred_customer_preferred
    : ContextSpecification&lt;Customer&gt;
{
    <span class="kwrd">protected</span> <span class="kwrd">override</span> Customer Create_subject_under_test()
    {
        var customer = <span class="kwrd">new</span> Customer(<span class="kwrd">new</span>[] { _order });
        customer.MakePreferred();
        <span class="kwrd">return</span> customer;
    }

    <span class="kwrd">protected</span> <span class="kwrd">override</span> <span class="kwrd">void</span> Establish_context()
    {
        _order = <span class="kwrd">new</span> Order(<span class="kwrd">new</span>[] { <span class="kwrd">new</span> OrderItem(12), 
                                   <span class="kwrd">new</span> OrderItem(16) });
        _totalAmountWithoutDiscount = _order.TotalAmount;
    }

    <span class="kwrd">protected</span> <span class="kwrd">override</span> <span class="kwrd">void</span> Because()
    {
        SUT.MakePreferred();
    }

    [Test]
    <span class="kwrd">public</span> <span class="kwrd">void</span> Then_no_additional_discount_should_be_applied_to_the_outstanding_orders()
    {
        _order.TotalAmount.ShouldNotBeEqualTo(
            _totalAmountWithoutDiscount * 0.81);
    }

    <span class="kwrd">private</span> Order _order;
    <span class="kwrd">private</span> Double _totalAmountWithoutDiscount;
}

<span class="rem">//</span>
<span class="rem">// Subject under test</span>
<span class="rem">//</span>
<span class="kwrd">public</span> <span class="kwrd">class</span> Customer
{
    <span class="kwrd">private</span> <span class="kwrd">readonly</span> List&lt;Order&gt; _orders;
    <span class="kwrd">public</span> Boolean IsPreferred { get; <span class="kwrd">private</span> set; }

    <span class="kwrd">public</span> Customer(IEnumerable&lt;Order&gt; orders)
    {
        _orders = <span class="kwrd">new</span> List&lt;Order&gt;(orders);
    }

    <span class="kwrd">public</span> <span class="kwrd">void</span> MakePreferred()
    {
        <span class="kwrd">if</span>(IsPreferred)    
            <span class="kwrd">return</span>;
    
        IsPreferred = <span class="kwrd">true</span>;
        _orders.ForEach(order =&gt; order.ApplyDiscount(10));
    }
}</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>The bottom line of this example is that preferred customers get a 10 percent discount. Customers that are already preferred do not get an additional discount or otherwise we’re out of business ;-). </p>

<p>I’ve been pretty happy with this approach so far, although sometimes there were some quirks associated with this. So it was time for me to look beyond the horizon again, trying to look for ways to improve. </p>

<p><a href="http://github.com/machine/machine.specifications">Machine.Specifications</a> or MSpec for short is something that has been on my ‘cool-things-to-learn-list’ for quite some time now. As you will see later in this post, the syntax is a bit different as one would come to expect from a context/specification framework that targets the C# programming language. Its seems to be heavily inspired by Scott Bellware’s <a href="http://code.google.com/p/specunit-net/">SpecUnit framework</a> and <a href="http://rspec.info/">RSpec</a>.</p>

<p>Lets see how to set things up first. </p>

<p>The most obvious starting point is downloading the bits and bytes. You can grab the <a href="http://github.com/machine/machine.specifications">source code</a> from GitHub and build it or you can wuss out like I did and get the latest build from the <a href="http://teamcity.codebetter.com/login.html">TeamCity.CodeBetter.com</a> builder server (you can log on as a guest and search the artifacts for a latest build).&#160; </p>

<p>When you’re heavily addicted to <a href="http://www.testdriven.net/">TestDriven.NET</a> like I am, then its possible to keep using this wonderful Visual Studio add-in for running MSpec context/specifications. Just create a directory named <em>Machine.Specifications</em> in {$Program_Files}\TestDriven.NET 2.0 and copy the following files:</p>

<ul>
  <li>Machine.Specifications.dll</li>

  <li>Machine.Specifications.TDNetRunner.dll</li>

  <li>InstallTDNetRunner.bat</li>
</ul>

<ul>Run the InstallTDNetRunner.bat file and you’re able to run all MSpec context/specifications using TestDriven.NET.</ul>

<p>I also strongly encourage you to install the plugin for the Resharper test runner (if only to prevent some Resharper warnings later on). First step is to add a directory named <em>Plugins</em> to the <em>Bin</em> directory of Resharper ({$Program_Files}\JetBrains\ReSharper\v4.5\Bin\). Then create a directory named <em>Machine.Specifications</em> in the <em>Plugins</em> directory you just created and copy the following files:</p>

<ul>
  <li>Machine.Specifications.dll</li>

  <li>Machine.Specifications.ReSharperRunner.4.5.dll</li>

  <li>InstallResharperRunner.4.5.bat</li>
</ul>

<p>Run the InstallResharperRunner.4.5.bat file and you’re also able to run MSpec context/specifications using the Resharper test runner.</p>

<p>I’m not going to put this off any longer. Lets look at the code of the context/specifications shown earlier but completely revamped using the MSpec syntax:</p>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<pre class="csharpcode">[Subject(<span class="str">&quot;Making a customer preferred&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_a_regular_customer_is_made_preferred 
{
    Establish context = () =&gt;
    {
        _order = <span class="kwrd">new</span> Order(<span class="kwrd">new</span>[] { <span class="kwrd">new</span> OrderItem(12), 
                                   <span class="kwrd">new</span> OrderItem(16) });
        _totalAmountWithoutDiscount = _order.TotalAmount;

        SUT = <span class="kwrd">new</span> Customer(<span class="kwrd">new</span>[] { _order });
    };

    Because of = () =&gt; 
        SUT.MakePreferred();

    It should_mark_the_customer_as_preferred = () =&gt;
        SUT.IsPreferred.ShouldBeTrue();
        
    It should_apply_a_ten_percent_discount_to_all_outstanding_orders = () =&gt;
        _order.TotalAmount.ShouldEqual(_totalAmountWithoutDiscount * 0.9);      

    <span class="kwrd">private</span> <span class="kwrd">static</span> Customer SUT;
    
    <span class="kwrd">private</span> <span class="kwrd">static</span> Order _order;
    <span class="kwrd">private</span> <span class="kwrd">static</span> Double _totalAmountWithoutDiscount;
}

[Subject(<span class="str">&quot;Making a customer preferred&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_a_preferred_customer_is_made_preferred
{
    Establish context = () =&gt;
    {
        _order = <span class="kwrd">new</span> Order(<span class="kwrd">new</span>[] { <span class="kwrd">new</span> OrderItem(12), 
                                   <span class="kwrd">new</span> OrderItem(16) });
        _totalAmountWithoutDiscount = _order.TotalAmount;

        SUT = <span class="kwrd">new</span> Customer(<span class="kwrd">new</span>[] { _order });
        SUT.MakePreferred();
    };

    Because of = () =&gt;
        SUT.MakePreferred();

    It should_apply_no_additional_discount_to_the_outstanding_orders = () =&gt; 
        _order.TotalAmount.ShouldNotEqual(_totalAmountWithoutDiscount * 0.81);

    <span class="kwrd">private</span> <span class="kwrd">static</span> Customer SUT;

    <span class="kwrd">private</span> <span class="kwrd">static</span> Order _order;
    <span class="kwrd">private</span> <span class="kwrd">static</span> Double _totalAmountWithoutDiscount;
}</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>I warned you about the syntax, didn’t I :-). It only took me a couple of seconds to get used to this syntax but now I’m completely hooked. Instead of using methods and attributes, MSpec utilizes delegates and anonymous methods. But there’s more. </p>

<p>When using <a href="http://www.nunit.com/index.php">NUnit</a> for writing context/ specifications, the <em>Establish_context</em> and <em>Because</em> methods of the example shown earlier is executed before every observation (test). With MSpec, the <em>Establish</em> and <em>Because</em> anonymous methods are executed only once for every context no matter how many observations a particular context class contains. Big difference? Well, at first glance not but on second hand it does make <a href="http://elegantcode.com/2008/12/30/dont-sell-out-on-the-context-dude/">selling out on the context</a> a bit more difficult as it will probably blow up in your face sooner than later. You can force MSpec to execute the <em>Establish</em> and <em>Because</em> anonymous methods before every observation by applying the <em>SetupForEachSpecification</em> attribute to the context class, but I strongly encourage you to stay away from that unless absolutely needed.</p>

<p>Also notice that the fields in the contexts are now all static. This is needed so that the anonymous methods can access those.&#160;&#160;&#160;&#160;&#160; </p>

<p>Running these context/specifications using TestDriven.NET yields the following output in the output window of Visual Studio:</p>

<blockquote>
  <p><font face="Arial">Making a customer preferred, when a regular customer is made preferred
      <br />» should mark the customer as preferred

      <br />» should apply a ten percent discount to all outstanding orders</font></p>

  <p><font face="Arial">Making a customer preferred, when a preferred customer is made preferred
      <br />» should apply no additional discount to the outstanding orders</font></p>
</blockquote>

<p>What’s not to like? Well, the only downside so far is that Resharper was giving me some warnings about classes and fields not being used etc. … . Many of those warnings disappeared by registering the MSpec plugin for the Resharper test runner as I explained earlier.</p>

<p>So far, so good. I’ve got two more posts coming up on MSpec, so stay tuned.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/02/19/getting-started-with-machine-specifications-mspec/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Elegant Code &#187; Unit Testing</title>
	<atom:link href="http://elegantcode.com/category/unit-testing/feed/" rel="self" type="application/rss+xml" />
	<link>http://elegantcode.com</link>
	<description></description>
	<lastBuildDate>Tue, 15 May 2012 10:00:00 +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>AutoTest.NET</title>
		<link>http://elegantcode.com/2010/11/30/autotest-net/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=autotest-net</link>
		<comments>http://elegantcode.com/2010/11/30/autotest-net/#comments</comments>
		<pubDate>Tue, 30 Nov 2010 11:00:00 +0000</pubDate>
		<dc:creator>Jan Van Ryswyck</dc:creator>
				<category><![CDATA[TDD]]></category>
		<category><![CDATA[Tools and Utilities]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/11/30/autotest-net/</guid>
		<description><![CDATA[I just want to quickly point out a tool that I’ve been playing with for a couple of days now, named AutoTest.NET. Its an open-source tool that originates from a popular tool in the Ruby community called ZenTest, which basically runs all your valuable unit tests when you save your source files or when you [...]]]></description>
			<content:encoded><![CDATA[<p>I just want to quickly point out a tool that I’ve been playing with for a couple of days now, named <a href="https://github.com/acken/AutoTest.Net" target="_blank">AutoTest.NET</a>. Its an open-source tool that originates from a popular tool in the Ruby community called <a href="http://www.zenspider.com/ZSS/Products/ZenTest/" target="_blank">ZenTest</a>, which basically runs all your valuable unit tests when you save your source files or when you build your code. It enables you to get feedback about your changes as soon as possible.</p>  <p>The project started out a couple of years ago on <a href="http://code.google.com/p/autotestnet/" target="_blank">Google code</a> and was first initiated by <a href="http://averyblog.com/" target="_blank">James Avery</a>. Contribution stopped at some point until recently where <a href="http://ackenpacken.blogspot.com/" target="_blank">Svein Arne Ackenhausen</a> forked the source code and <a href="https://github.com/acken/AutoTest.Net" target="_blank">put it on GitHub</a>. Now it runs both for .NET as well as Mono, with NUnit, MSTest and xUnit as the currently supported unit test frameworks. </p>  <p>Here’s a screenshot from the feedback window when all tests pass:</p>  <p><a href="http://elegantcode.com/wp-content/uploads/2010/11/Success.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="Success" border="0" alt="Success" src="http://elegantcode.com/wp-content/uploads/2010/11/Success_thumb.png" width="540" height="189" /></a> </p>  <p>And here you can see the same window after I broke one of my unit tests:</p>  <p><a href="http://elegantcode.com/wp-content/uploads/2010/11/Failure.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="Failure" border="0" alt="Failure" src="http://elegantcode.com/wp-content/uploads/2010/11/Failure_thumb.png" width="538" height="319" /></a> </p>  <p>Here you can see which particular unit test has been broken and by clicking the specified link you end up at the right source file in Visual Studio. </p>  <p>I encourage you to pick up this small tool and learn how it can facilitate your TDD flow. Take a look at <a href="https://github.com/acken/AutoTest.Net/wiki/Get-started!" target="_blank">this page</a> in order to get up-and-running in no time. Also don’t forget to provide the owner(s) of this project with some feedback that you might have. Svein has been very helpful over the last week answering all my stupid questions and remarks (and the Nobel price for this year’s most patient person goes to … ;-) ). </p>  <p>I would definitely like to see this tool becoming more popular, so go check it out.&#160;&#160; </p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/11/30/autotest-net/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>If Self-Documenting Code is the What, Unit Tests are the Why</title>
		<link>http://elegantcode.com/2010/04/25/if-self-documenting-code-is-the-what-unit-tests-are-the-why/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=if-self-documenting-code-is-the-what-unit-tests-are-the-why</link>
		<comments>http://elegantcode.com/2010/04/25/if-self-documenting-code-is-the-what-unit-tests-are-the-why/#comments</comments>
		<pubDate>Sun, 25 Apr 2010 19:09:04 +0000</pubDate>
		<dc:creator>John Sonmez</dc:creator>
				<category><![CDATA[Agile]]></category>
		<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Craftsmanship]]></category>
		<category><![CDATA[Documentation]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/04/25/if-self-documenting-code-is-the-what-unit-tests-are-the-why/</guid>
		<description><![CDATA[It is not enough to just write code that is clean and self-documenting.  Eliminating comments and replacing them with clear variable and method names, will tell the reader of your code clearly what it is doing, but it will not properly express why it is doing it. If you recall from my original post on [...]]]></description>
			<content:encoded><![CDATA[It is not enough to just write code that is clean and self-documenting.  <a href="http://elegantcode.com/2010/04/18/eliminating-comments-the-road-to-clarity/">Eliminating comments</a> and replacing them with clear variable and method names, will tell the reader of your code clearly what it is doing, but it will not properly express why it is doing it.

If you recall from my <a href="http://elegantcode.com/2010/04/09/what-does-elegant-code-mean-to-me/">original post</a> on Elegant code, I stated that elegant code is:
<blockquote>Something that is simple yet effective, delivered with grace.</blockquote>
By writing self-documenting code we are hopefully able to achieve some of the aspects of simplicity and grace, but it tells us nothing about the effectiveness of the code.
<h2>Bringing the dead to life</h2>
<a href="http://elegantcode.com/wp-content/uploads/2010/04/zombies.jpg"><img style="border-right-width: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto" title="zombies" src="http://elegantcode.com/wp-content/uploads/2010/04/zombies_thumb.jpg" border="0" alt="zombies" width="441" height="295" /></a>

Throwing out comments is a debatable topic.  <a href="http://www.reddit.com/r/programming/comments/bsutx/">It raises quite a bit of controversy</a>, as you can see from some of the comments on my post about the subject.  The reason, perhaps, that so many people are so staunchly opposed to the idea, is because they are worried, and rightly so, that throwing out comments will reduce the documentation of what the code is doing.

Think about that for a second.  Is documentation of what the code is doing important?  It better be.  What we are trying to accomplish by writing self-documenting code instead of comments, is to take the vessel, which is the code itself, and make that same vessel be the documentation of what the code does.  It is by doing this that we creating a living representation of the functionality of the code.  Comments are akin to a dead representation of the functionality of the code because they do not change automatically with the code.

I diverge to talk about comments so that I can draw a parallel to another form of documentation which is valuable and should be considered necessary.  That other set of documentation is requirements.  Have you ever written requirements documents?  Have you ever captured requirements from the customer and put them into UML diagrams, or perhaps plopped them into some templated Word document, which is never updated again, and no one reads, because no one trusts it is correct?  Wouldn’t it be great if we would replace that dead document or set of documents, with a living one?

The good news is we can, and some of us have.  And I fully expect this recommendation will be just as controversial, because <strong>I am suggesting that we don’t have to write low level specifications of the system at all, instead we can write good unit tests. </strong>When we do this, we are taking a dead form of document and bringing it to life.
<h2>Unit tests tell us why and how our code is effective</h2>
If
<pre class="csharpcode">i = 5;  // Widget count defaults to five.</pre>
is replaced with
<pre class="csharpcode">widgetCount = DEFAULT_WIDGET_COUNT;</pre>
<!--.csharpcode, .csharpcode pre { 	font-size: small; 	color: black; 	font-family: consolas, "Courier New", courier, monospace; 	background-color: #ffffff; 	/*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt  { 	background-color: #f4f4f4; 	width: 100%; 	margin: 0em; } .csharpcode .lnum { color: #606060; } -->

then
<blockquote><span style="background-color: #ffffff;">1.1.5 When a new widget is created, the widget count should be increased by one.</span></blockquote>
is replaced with
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">void</span> When_NewWidgetIsCreated_Then_WidgetCountIsIncreasedByOne()
{
     WidgetFactory.Count = 3;
     WidgetFactory.CreateNew();
     assertEquals(4, WidgetFactory.Count);
}</pre>
The unit test is replacing the low level requirement, which is somewhat open to interpretation and untied to the code, with an absolute and completely tied-to-the-code, specific requirement.

The unit test is telling us why our code is built the way it is.  It is telling us what requirement that particular structure of code is trying to address.  <strong>It is telling us what end result that code is trying to accomplish and what the expectations are on the results of a given condition.</strong>

The unit test is telling us how the code is to be used in order to achieve its result.  It is serving as a living reference to the syntax and use of the code we built.  <strong>Instead of providing instructions on how to use our API, we are providing a living example, and proof that it will indeed work.</strong> Examples are often much more effective than instructions anyway.
<h2>What exactly are we replacing?</h2>
At this point we are not trying to replace all the documentation of the system (at this point).

With self-documenting code, we sought to eliminate comments, and replace them with good variable and method names.

With unit tests, we seek to eliminate technical documentation and requirements of the system, that is targeted at a developer or technical audience.

We are NOT trying to eliminate high level specifications of the system, or use cases. <strong>Unit tests DO NOT replace that kind of documentation! </strong>We will talk about replacing that kind of documentation when we talk about automated functional or system tests.

Simply put, any kind of documentation that you would give to a developer so they understand how the system works and how to use the code or APIs, can be easily replaced by writing good unit tests.

Our simple goal is to replace the “dead” documentation (meaning that it does not update automatically with the thing it is documenting), with “living” documentation in the form of unit tests.

One last point.  I want to be clear that I am not saying that having unit tests automatically results in the ability to replace technical documentation.  Just like having long-named methods and variables doesn’t automatically replace the need for comments.  It is a matter of the quality of the unit tests that are written, just as it is a matter of the quality of the self-documenting code.
<h5>As always, you can subscribe to this <a href="http://feeds2.feedburner.com/ElegantCode">RSS feed</a> to follow my posts on elegant code.  Feel free to check out my main personal blog at <a href="http://simpleprogrammer.com">http://simpleprogrammer.com</a>, which has a wider range of posts, updated 2-3 times a week.  Also, you can follow me on twitter <a href="http://twitter.com/jsonmez">here</a>.</h5>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/04/25/if-self-documenting-code-is-the-what-unit-tests-are-the-why/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Behaviors with MSpec</title>
		<link>http://elegantcode.com/2010/02/26/behaviors-with-mspec/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=behaviors-with-mspec</link>
		<comments>http://elegantcode.com/2010/02/26/behaviors-with-mspec/#comments</comments>
		<pubDate>Fri, 26 Feb 2010 23:33:28 +0000</pubDate>
		<dc:creator>Jan Van Ryswyck</dc:creator>
				<category><![CDATA[BDD]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/02/26/behaviors-with-mspec/</guid>
		<description><![CDATA[In my previous posts, I showed the syntax for context/specifications using Machine.Specifications (or MSpec for short) and how to use an auto mocking container in conjunction with this excellent Behavior-Driven Development (BDD) framework. For this post, I want to show you one of the nice features of MSpec called behaviors. Suppose we have to create [...]]]></description>
			<content:encoded><![CDATA[<p>In my previous posts, I showed the <a href="http://elegantcode.com/2010/02/19/getting-started-with-machine-specifications-mspec/">syntax for context/specifications</a> using <a href="http://github.com/machine/machine.specifications">Machine.Specifications</a> (or MSpec for short) and <a href="http://elegantcode.com/2010/02/23/mspec-and-auto-mocking">how to use an auto mocking container</a> in conjunction with this excellent Behavior-Driven Development (BDD) framework. For this post, I want to show you one of the nice features of MSpec called <em>behaviors</em>.</p>  <p>Suppose we have to create some sort of specification that validates the format of an e-mail address. We typically use some regular expression in order to ensure that a specified e-mail address is properly formatted.</p>  <pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">class</span> EmailSpecification
{
    <span class="kwrd">private</span> <span class="kwrd">const</span> String EmailRegexPattern = <span class="str">@&quot;.. SOME_REGEX_PATTERN ...&quot;</span>;

    <span class="kwrd">public</span> Boolean IsSatisfiedBy(String candidate)
    {
        var regex = <span class="kwrd">new</span> Regex(EmailRegexPattern);
        <span class="kwrd">return</span> regex.IsMatch(candidate);
    }
}</pre>
<style type="text/css">

.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>I guess this is pretty common and straightforward. One way to provide some unit tests for this particular piece of code is to check a whole number of e-mail addresses that either pass or fail the specification. The following example shows only a couple of scenarios:</p>

<pre class="csharpcode">[TestFixture]
<span class="kwrd">public</span> <span class="kwrd">class</span> When_validating_an_email
    : ContextSpecification&lt;EmailSpecification&gt;
{
    <span class="kwrd">protected</span> <span class="kwrd">override</span> EmailSpecification Create_subject_under_test()
    {
        <span class="kwrd">return</span> <span class="kwrd">new</span> EmailSpecification();
    }

    [Test]
    <span class="kwrd">public</span> <span class="kwrd">void</span> ShouldBeSatisfied()
    {
        Assert.That(SUT.IsSatisfiedBy(<span class="str">&quot;one2@three.com&quot;</span>));
        Assert.That(SUT.IsSatisfiedBy(<span class="str">&quot;one@two3.com&quot;</span>));
    }

    [Test]
    <span class="kwrd">public</span> <span class="kwrd">void</span> ShouldNotBeSatisfied()
    {
        Assert.That(SUT.IsSatisfiedBy(<span class="str">&quot;one_two.com&quot;</span>), Is.False);
        Assert.That(SUT.IsSatisfiedBy(<span class="str">&quot;one_two@&quot;</span>), Is.False);
    }
}</pre>
<style type="text/css">

.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>A slightly more concise approach for these kind of unit tests can be accomplished by utilizing a feature of any decent unit test framework called <em>row tests. </em>With this approach we can, at the very least, reduce the number of asserts we have to write for each unit test.<em>&#160;</em></p>

<pre class="csharpcode">[TestFixture]
<span class="kwrd">public</span> <span class="kwrd">class</span> When_validating_an_email__approach_2
    : ContextSpecification&lt;EmailSpecification&gt;
{
    <span class="kwrd">protected</span> <span class="kwrd">override</span> EmailSpecification Create_subject_under_test()
    {
        <span class="kwrd">return</span> <span class="kwrd">new</span> EmailSpecification();
    }

    [RowTest]
    [Row(<span class="str">&quot;one2@three.com&quot;</span>)]
    [Row(<span class="str">&quot;one@two3.com&quot;</span>)]
    <span class="kwrd">public</span> <span class="kwrd">void</span> ShouldBeSatisfied(String email)
    {
        Assert.That(SUT.IsSatisfiedBy(email));
    }

    [RowTest]
    [Row(<span class="str">&quot;one_two.com&quot;</span>)]
    [Row(<span class="str">&quot;one_two@&quot;</span>)]
    <span class="kwrd">public</span> <span class="kwrd">void</span> ShouldNotBeSatisfied(String email)
    {
        Assert.That(SUT.IsSatisfiedBy(email), Is.False);
    }
}</pre>
<style type="text/css">

.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>Notice that I explicitly called both of these approaches <em>unit tests</em> as they don’t have much to do with BDD in my opinion. I’m not saying that using regular unit tests is a bad thing, but with&#160; behavior-driven development context is king. So these unit tests are perfect examples of ‘<a href="http://elegantcode.com/2008/12/30/dont-sell-out-on-the-context-dude/">context betrayal</a>’ when following the BDD approach. </p>

<p>Lets see what MSpec can bring to the table for these kind of scenarios:</p>

<pre class="csharpcode">[Subject(<span class="kwrd">typeof</span>(EmailSpecification), <span class="str">&quot;is satisfied&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_validating_an_email_address_with_a_number_in_the_local_part
    : email_specification_specs
{
    Establish context = () =&gt;
        EmailAddress = <span class="str">&quot;one2@three.com&quot;</span>;

    Behaves_like&lt;SatisfiedSpecificationBehavior&gt; a_satisfied_specification;
}

[Subject(<span class="kwrd">typeof</span>(EmailSpecification), <span class="str">&quot;is satisfied&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_validating_an_email_address_with_a_number_in_the_domain_name
    : email_specification_specs
{
    Establish context = () =&gt;
        EmailAddress = <span class="str">&quot;one@two3.com&quot;</span>;

    Behaves_like&lt;SatisfiedSpecificationBehavior&gt; a_satisfied_specification;
}

[Subject(<span class="kwrd">typeof</span>(EmailSpecification), <span class="str">&quot;is satisfied&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_validating_an_email_address_without_an_At_sign
    : email_specification_specs
{
    Establish context = () =&gt;
        EmailAddress = <span class="str">&quot;one_two.com&quot;</span>;

    Behaves_like&lt;UnsatisfiedSpecificationBehavior&gt; an_unsatisfied_specification;
}

[Subject(<span class="kwrd">typeof</span>(EmailSpecification), <span class="str">&quot;is satisfied&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_validating_an_email_address_without_a_domain
    : email_specification_specs
{
    Establish context = () =&gt;
        EmailAddress = <span class="str">&quot;one_two@&quot;</span>;

    Behaves_like&lt;UnsatisfiedSpecificationBehavior&gt; an_unsatisfied_specification;
}</pre>
<style type="text/css">

.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>In order to escape ‘context betrayal’, we’ve split up every context into a separate context/specification. In order to reduce the amount of effort caused by duplicate code, we stripped the context setup to the bare minimum (just a particular e-mail address in this case). The observations are isolated into MSpec behaviors which provides a very readable description of their outcome. Lets take a look at what is needed in order to get these <em>behaviors</em> to work.</p>

<p>But first lets take at look at the abstract base class that we’ve used for the context/specifications we’ve just shown.</p>

<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">abstract</span> <span class="kwrd">class</span> email_specification_specs
{
    Establish context = () =&gt;
    {
        SUT = <span class="kwrd">new</span> EmailSpecification();
    };

    Because of = () =&gt;
        Result = SUT.IsSatisfiedBy(EmailAddress);

    <span class="kwrd">protected</span> <span class="kwrd">static</span> Boolean Result;
    <span class="kwrd">protected</span> <span class="kwrd">static</span> String EmailAddress { get; set; }
    <span class="kwrd">protected</span> <span class="kwrd">static</span> EmailSpecification SUT { get; set; }
}</pre>

<p><style type="text/css">

.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style></p>

<p>&#160;</p>

<p>We abstracted as much as possible into this base class in order to remove duplication in the context/specifications. The creation of the subject-under-test and the calling of its <em>IsSatisfiedBy</em> method, but the important one is the declaration of the <em>Result</em> field. This field contains the outcome of the <em>IsSatisfiedBy</em> method. Finally, lets have a look at the behaviors themselves:</p>

<pre class="csharpcode">[Behaviors]
<span class="kwrd">public</span> <span class="kwrd">class</span> SatisfiedSpecificationBehavior
{
    <span class="kwrd">protected</span> <span class="kwrd">static</span> Boolean Result;
    
    It should_satisfy_the_specification = () =&gt;
        Result.ShouldBeTrue();
}

[Behaviors]
<span class="kwrd">public</span> <span class="kwrd">class</span> UnsatisfiedSpecificationBehavior
{
    <span class="kwrd">protected</span> <span class="kwrd">static</span> Boolean Result;

    It should_not_satisfy_the_specification = () =&gt;
        Result.ShouldBeFalse();
}</pre>
<style type="text/css">

.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>In order to create an MSpec behavior, we just have to create a separate class that we decorate with the <em>Behaviors</em> attribute. Also notice that we have the same declaration of the <em>Result</em> field. MSpec ensures that this field gets initialized with the value of the other <em>Result</em> field that is set in the base class of the context/specifications. Note that you don’t necessarily need to put this field in a base class. You can have that field in every context/specification if you’d like (not sure why) as long as the names match with the fields used in the defined behaviors.</p>

<p>I personally like the way how the MSpec contributors tried to solve testing the same logic with different input patterns and the syntax they provided to back this up.&#160;&#160; </p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/02/26/behaviors-with-mspec/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>MSpec and Auto Mocking</title>
		<link>http://elegantcode.com/2010/02/23/mspec-and-auto-mocking/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=mspec-and-auto-mocking</link>
		<comments>http://elegantcode.com/2010/02/23/mspec-and-auto-mocking/#comments</comments>
		<pubDate>Tue, 23 Feb 2010 20:38:54 +0000</pubDate>
		<dc:creator>Jan Van Ryswyck</dc:creator>
				<category><![CDATA[BDD]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/02/23/mspec-and-auto-mocking/</guid>
		<description><![CDATA[In my previous post, I explained how to get started with Machine.Specifications (or MSpec for short) and showed you how the syntax for context/specifications looks like when using this BDD framework. For this post, I want to show you how to use an auto mocking container (we’ll be using the one provided by StructureMap off [...]]]></description>
			<content:encoded><![CDATA[<p>In my <a href="http://elegantcode.com/2010/02/19/getting-started-with-machine-specifications-mspec/">previous post</a>, I explained how to get started with <a href="http://github.com/machine/machine.specifications">Machine.Specifications</a> (or MSpec for short) and showed you how the syntax for context/specifications looks like when using this BDD framework. For this post, I want to show you how to use an <a href="http://vanryswyckjan.blogspot.com/2008/01/automocking-container.html">auto mocking container</a> (we’ll be using the one provided by StructureMap off course).</p>  <p>We’ll use the same example as the one used in the previous post, but now we’ll deal with the message handler that makes a particular customer preferred.</p> <style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>  <pre class="csharpcode"><span class="rem">//</span>
<span class="rem">// Subject under test</span>
<span class="rem">//</span>
<span class="kwrd">public</span> <span class="kwrd">class</span> MakeCustomerPreferredMessageHandler
{
    <span class="kwrd">private</span> <span class="kwrd">readonly</span> ICustomerRepository&lt;ICanMakeCustomerPreferred&gt; _repository;

    <span class="kwrd">public</span> MakeCustomerPreferredMessageHandler(
        ICustomerRepository&lt;ICanMakeCustomerPreferred&gt; repository)
    {
        _repository = repository;
    }

    <span class="kwrd">public</span> <span class="kwrd">void</span> Handle(MakeCustomerPreferredMessage message)
    {
        var customer = _repository.Get(message.CustomerId);
        <span class="kwrd">if</span>(<span class="kwrd">null</span> == customer)
            <span class="kwrd">throw</span> <span class="kwrd">new</span> InvalidOperationException(
                <span class="str">&quot;No customer for specified identifier&quot;</span>);
        
        customer.MakePreferred();
        _repository.Save(customer);
    }
}</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>The <em>Customer</em> class implements a ‘<a href="http://martinfowler.com/bliki/RoleInterface.html">role interface’</a> called <em>ICanMakeCustomerPreferred</em>. We retrieve a customer from the repository and make it preferred. We throw an exception in case the customer cannot be found in the data store.</p>

<p>Here are the context/specifications for this easy example:</p>

<pre class="csharpcode">[Subject(<span class="str">&quot;Making a customer preferred&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_making_a_customer_preferred
    : context_specification&lt;MakeCustomerPreferredMessageHandler&gt;
{
    Establish context = () =&gt;
    {
        _message = <span class="kwrd">new</span> MakeCustomerPreferredMessage { CustomerId = 6412 };

        Repository.Stub(repository =&gt; repository.Get(_message.CustomerId))
            .Return(Customer);
    };

    Because of = () =&gt; 
        SUT.Handle(_message);
    
    It should_mark_the_customer_as_preferred = () =&gt;
        Customer.AssertWasCalled(customer =&gt; customer.MakePreferred());

    It should_save_the_customer_in_the_repository = () =&gt;
        Repository.AssertWasCalled(repository =&gt; repository.Save(Customer));

    <span class="kwrd">private</span> <span class="kwrd">static</span> ICanMakeCustomerPreferred Customer
    {
        get { <span class="kwrd">return</span> Dependency&lt;ICanMakeCustomerPreferred&gt;(); }
    }

    <span class="kwrd">private</span> <span class="kwrd">static</span> ICustomerRepository&lt;ICanMakeCustomerPreferred&gt; Repository
    {
        get { <span class="kwrd">return</span> Dependency&lt;ICustomerRepository&lt;ICanMakeCustomerPreferred&gt;&gt;(); }
    }

    <span class="kwrd">private</span> <span class="kwrd">static</span> MakeCustomerPreferredMessage _message;
}

[Subject(<span class="str">&quot;Making a customer preferred&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_making_an_unexisting_customer_preferred
    : context_specification&lt;MakeCustomerPreferredMessageHandler&gt;
{
    Establish context = () =&gt;   
    {
        _message = <span class="kwrd">new</span> MakeCustomerPreferredMessage() { CustomerId = 61544 };

        Dependency&lt;ICustomerRepository&lt;ICanMakeCustomerPreferred&gt;&gt;()
            .Stub(repository =&gt; repository.Get(_message.CustomerId))
            .Return(<span class="kwrd">null</span>);
    };

    Because of = () =&gt;
        _resultingException = Catch.Exception(() =&gt; SUT.Handle(_message));

    It should_result_in_an_error = () =&gt;
        _resultingException.ShouldBeOfType&lt;InvalidOperationException&gt;();

    <span class="kwrd">private</span> <span class="kwrd">static</span> MakeCustomerPreferredMessage _message;
    <span class="kwrd">private</span> <span class="kwrd">static</span> Exception _resultingException;
}</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>I want to point out that all fields and properties are made static. This is needed so that the anonymous methods can access them. I’m also using a base class for these specifications which I’ll show next. This base class uses an auto mocking container for providing the requested mocks and stubs through the <em>Dependency</em> and <em>Stub</em> methods. </p>

<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">abstract</span> <span class="kwrd">class</span> context_specification&lt;TSubjectUnderTest&gt;
    <span class="kwrd">where</span> TSubjectUnderTest : <span class="kwrd">class</span>
{
    <span class="kwrd">private</span> <span class="kwrd">static</span> IAutoMockingContainer&lt;TSubjectUnderTest&gt; _autoMockingContainer;
    <span class="kwrd">protected</span> <span class="kwrd">static</span> TSubjectUnderTest SUT { get; set; }

    Establish context = () =&gt;
    {
        _autoMockingContainer = <span class="kwrd">new</span> StructureMapAMC&lt;TSubjectUnderTest&gt;();
        SUT = _autoMockingContainer.Create();     
    };
    
    Cleanup stuff = () =&gt; 
    {
        SUT = <span class="kwrd">null</span>;
        _autoMockingContainer = <span class="kwrd">null</span>;
    };

    <span class="kwrd">protected</span> <span class="kwrd">static</span> TDependency Dependency&lt;TDependency&gt;()
        <span class="kwrd">where</span> TDependency : <span class="kwrd">class</span>
    {
        <span class="kwrd">return</span> _autoMockingContainer.GetMock&lt;TDependency&gt;();
    }

    <span class="kwrd">protected</span> <span class="kwrd">static</span> TStub Stub&lt;TStub&gt;()
        <span class="kwrd">where</span> TStub : <span class="kwrd">class</span>
    {
        <span class="kwrd">return</span> _autoMockingContainer.GetStub&lt;TStub&gt;();
    }
}

<span class="kwrd">public</span> <span class="kwrd">interface</span> IAutoMockingContainer&lt;TSubject&gt;
    <span class="kwrd">where</span> TSubject : <span class="kwrd">class</span>
{
    TSubject Create();
    TMock GetMock&lt;TMock&gt;() <span class="kwrd">where</span> TMock : <span class="kwrd">class</span>;
    TStub GetStub&lt;TStub&gt;() <span class="kwrd">where</span> TStub : <span class="kwrd">class</span>;
}

<span class="kwrd">public</span> <span class="kwrd">class</span> StructureMapAMC&lt;TSubject&gt; 
    : IAutoMockingContainer&lt;TSubject&gt;
    <span class="kwrd">where</span> TSubject : <span class="kwrd">class</span>
{
    <span class="kwrd">private</span> <span class="kwrd">readonly</span> RhinoAutoMocker&lt;TSubject&gt; _rhinoAutoMocker;

    <span class="kwrd">public</span> StructureMapAMC()
    {
        _rhinoAutoMocker = 
            <span class="kwrd">new</span> RhinoAutoMocker&lt;TSubject&gt;(MockMode.AAA);
    }

    <span class="kwrd">public</span> TSubject Create()
    {
        <span class="kwrd">return</span> _rhinoAutoMocker.ClassUnderTest;
    }

    <span class="kwrd">public</span> TMock GetMock&lt;TMock&gt;() 
        <span class="kwrd">where</span> TMock : <span class="kwrd">class</span>
    {
        <span class="kwrd">return</span> GetDependency&lt;TMock&gt;();
    }

    <span class="kwrd">public</span> TStub GetStub&lt;TStub&gt;() 
        <span class="kwrd">where</span> TStub : <span class="kwrd">class</span>
    {
        <span class="kwrd">return</span> GetDependency&lt;TStub&gt;();
    }

    <span class="kwrd">private</span> TDependency GetDependency&lt;TDependency&gt;() 
        <span class="kwrd">where</span> TDependency : <span class="kwrd">class</span>
    {
        <span class="kwrd">return</span> _rhinoAutoMocker.Get&lt;TDependency&gt;();
    }
}</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>Notice that I’m using the <em>Establish</em> and <em>Cleanup</em> delegates in the <em>context_specification</em> base class. This doesn’t prevent that these can be used again in derived context/specifications. MSpec ensures that the anonymous methods are called in the right order. This means that the <em>Establish</em> method of the base class is called before the <em>Establish</em> method of the derived context/specifications.&#160;&#160;&#160;&#160; </p>

<p>Absolutely no rocket science here, but I figured it might come in handy when you need it. For the next post I’ll try to demonstrate how to deal with reusable behaviors.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/02/23/mspec-and-auto-mocking/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Getting Started With Machine.Specifications (MSpec)</title>
		<link>http://elegantcode.com/2010/02/19/getting-started-with-machine-specifications-mspec/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=getting-started-with-machine-specifications-mspec</link>
		<comments>http://elegantcode.com/2010/02/19/getting-started-with-machine-specifications-mspec/#comments</comments>
		<pubDate>Fri, 19 Feb 2010 21:34:17 +0000</pubDate>
		<dc:creator>Jan Van Ryswyck</dc:creator>
				<category><![CDATA[BDD]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/02/19/getting-started-with-machine-specifications-mspec/</guid>
		<description><![CDATA[Its been a while since I evaluated and evolved my approach to BDD. The way I’ve been doing BDD up until now is described in this blog post which goes way back to 2008. Everyone has kind of their own style nowadays. Below you can find the code of two context/specifications for a method named [...]]]></description>
			<content:encoded><![CDATA[<p>Its been a while since I evaluated and evolved my approach to BDD. The way I’ve been doing BDD up until now is described in <a href="http://elegantcode.com/2008/10/25/refining-contextspecification-bdd-using-rhino-mocks-35/">this blog post</a> which goes way back to 2008. Everyone has kind of their own style nowadays. Below you can find the code of two context/specifications for a method named <em>MakePreferred</em> on a <em>Customer </em>class. This simple example clarifies the style that I’ve been following up until now.</p> <style type="text/css">


.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style><style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>  <pre class="csharpcode">[TestFixture]
<span class="kwrd">public</span> <span class="kwrd">class</span> When_making_a_regular_customer_preferred
    : ContextSpecification&lt;Customer&gt;
{
    <span class="kwrd">protected</span> <span class="kwrd">override</span> Customer Create_subject_under_test()
    {
        <span class="kwrd">return</span> <span class="kwrd">new</span> Customer(<span class="kwrd">new</span>[] { _order });
    }

    <span class="kwrd">protected</span> <span class="kwrd">override</span> <span class="kwrd">void</span> Establish_context()
    {
        _order = <span class="kwrd">new</span> Order(<span class="kwrd">new</span>[] { <span class="kwrd">new</span> OrderItem(12), 
                                   <span class="kwrd">new</span> OrderItem(16) });
                                   
        _totalAmountWithoutDiscount = _order.TotalAmount;
    }

    <span class="kwrd">protected</span> <span class="kwrd">override</span> <span class="kwrd">void</span> Because()
    {
        SUT.MakePreferred();
    }

    [Test]
    <span class="kwrd">public</span> <span class="kwrd">void</span> Then_the_customer_should_be_marked_as_preferred()
    {
        SUT.IsPreferred.ShouldBeTrue();
    }

    [Test]
    <span class="kwrd">public</span> <span class="kwrd">void</span> Then_a_ten_percent_discount_should_be_applied_to_all_outstanding_orders()
    {
        _order.TotalAmount.ShouldBeEqualTo(
            _totalAmountWithoutDiscount * 0.9);
    }

    <span class="kwrd">private</span> Order _order;
    <span class="kwrd">private</span> Double _totalAmountWithoutDiscount;
}

[TestFixture]
<span class="kwrd">public</span> <span class="kwrd">class</span> When_making_a_preferred_customer_preferred
    : ContextSpecification&lt;Customer&gt;
{
    <span class="kwrd">protected</span> <span class="kwrd">override</span> Customer Create_subject_under_test()
    {
        var customer = <span class="kwrd">new</span> Customer(<span class="kwrd">new</span>[] { _order });
        customer.MakePreferred();
        <span class="kwrd">return</span> customer;
    }

    <span class="kwrd">protected</span> <span class="kwrd">override</span> <span class="kwrd">void</span> Establish_context()
    {
        _order = <span class="kwrd">new</span> Order(<span class="kwrd">new</span>[] { <span class="kwrd">new</span> OrderItem(12), 
                                   <span class="kwrd">new</span> OrderItem(16) });
        _totalAmountWithoutDiscount = _order.TotalAmount;
    }

    <span class="kwrd">protected</span> <span class="kwrd">override</span> <span class="kwrd">void</span> Because()
    {
        SUT.MakePreferred();
    }

    [Test]
    <span class="kwrd">public</span> <span class="kwrd">void</span> Then_no_additional_discount_should_be_applied_to_the_outstanding_orders()
    {
        _order.TotalAmount.ShouldNotBeEqualTo(
            _totalAmountWithoutDiscount * 0.81);
    }

    <span class="kwrd">private</span> Order _order;
    <span class="kwrd">private</span> Double _totalAmountWithoutDiscount;
}

<span class="rem">//</span>
<span class="rem">// Subject under test</span>
<span class="rem">//</span>
<span class="kwrd">public</span> <span class="kwrd">class</span> Customer
{
    <span class="kwrd">private</span> <span class="kwrd">readonly</span> List&lt;Order&gt; _orders;
    <span class="kwrd">public</span> Boolean IsPreferred { get; <span class="kwrd">private</span> set; }

    <span class="kwrd">public</span> Customer(IEnumerable&lt;Order&gt; orders)
    {
        _orders = <span class="kwrd">new</span> List&lt;Order&gt;(orders);
    }

    <span class="kwrd">public</span> <span class="kwrd">void</span> MakePreferred()
    {
        <span class="kwrd">if</span>(IsPreferred)    
            <span class="kwrd">return</span>;
    
        IsPreferred = <span class="kwrd">true</span>;
        _orders.ForEach(order =&gt; order.ApplyDiscount(10));
    }
}</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>The bottom line of this example is that preferred customers get a 10 percent discount. Customers that are already preferred do not get an additional discount or otherwise we’re out of business ;-). </p>

<p>I’ve been pretty happy with this approach so far, although sometimes there were some quirks associated with this. So it was time for me to look beyond the horizon again, trying to look for ways to improve. </p>

<p><a href="http://github.com/machine/machine.specifications">Machine.Specifications</a> or MSpec for short is something that has been on my ‘cool-things-to-learn-list’ for quite some time now. As you will see later in this post, the syntax is a bit different as one would come to expect from a context/specification framework that targets the C# programming language. Its seems to be heavily inspired by Scott Bellware’s <a href="http://code.google.com/p/specunit-net/">SpecUnit framework</a> and <a href="http://rspec.info/">RSpec</a>.</p>

<p>Lets see how to set things up first. </p>

<p>The most obvious starting point is downloading the bits and bytes. You can grab the <a href="http://github.com/machine/machine.specifications">source code</a> from GitHub and build it or you can wuss out like I did and get the latest build from the <a href="http://teamcity.codebetter.com/login.html">TeamCity.CodeBetter.com</a> builder server (you can log on as a guest and search the artifacts for a latest build).&#160; </p>

<p>When you’re heavily addicted to <a href="http://www.testdriven.net/">TestDriven.NET</a> like I am, then its possible to keep using this wonderful Visual Studio add-in for running MSpec context/specifications. Just create a directory named <em>Machine.Specifications</em> in {$Program_Files}\TestDriven.NET 2.0 and copy the following files:</p>

<ul>
  <li>Machine.Specifications.dll</li>

  <li>Machine.Specifications.TDNetRunner.dll</li>

  <li>InstallTDNetRunner.bat</li>
</ul>

<ul>Run the InstallTDNetRunner.bat file and you’re able to run all MSpec context/specifications using TestDriven.NET.</ul>

<p>I also strongly encourage you to install the plugin for the Resharper test runner (if only to prevent some Resharper warnings later on). First step is to add a directory named <em>Plugins</em> to the <em>Bin</em> directory of Resharper ({$Program_Files}\JetBrains\ReSharper\v4.5\Bin\). Then create a directory named <em>Machine.Specifications</em> in the <em>Plugins</em> directory you just created and copy the following files:</p>

<ul>
  <li>Machine.Specifications.dll</li>

  <li>Machine.Specifications.ReSharperRunner.4.5.dll</li>

  <li>InstallResharperRunner.4.5.bat</li>
</ul>

<p>Run the InstallResharperRunner.4.5.bat file and you’re also able to run MSpec context/specifications using the Resharper test runner.</p>

<p>I’m not going to put this off any longer. Lets look at the code of the context/specifications shown earlier but completely revamped using the MSpec syntax:</p>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<pre class="csharpcode">[Subject(<span class="str">&quot;Making a customer preferred&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_a_regular_customer_is_made_preferred 
{
    Establish context = () =&gt;
    {
        _order = <span class="kwrd">new</span> Order(<span class="kwrd">new</span>[] { <span class="kwrd">new</span> OrderItem(12), 
                                   <span class="kwrd">new</span> OrderItem(16) });
        _totalAmountWithoutDiscount = _order.TotalAmount;

        SUT = <span class="kwrd">new</span> Customer(<span class="kwrd">new</span>[] { _order });
    };

    Because of = () =&gt; 
        SUT.MakePreferred();

    It should_mark_the_customer_as_preferred = () =&gt;
        SUT.IsPreferred.ShouldBeTrue();
        
    It should_apply_a_ten_percent_discount_to_all_outstanding_orders = () =&gt;
        _order.TotalAmount.ShouldEqual(_totalAmountWithoutDiscount * 0.9);      

    <span class="kwrd">private</span> <span class="kwrd">static</span> Customer SUT;
    
    <span class="kwrd">private</span> <span class="kwrd">static</span> Order _order;
    <span class="kwrd">private</span> <span class="kwrd">static</span> Double _totalAmountWithoutDiscount;
}

[Subject(<span class="str">&quot;Making a customer preferred&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_a_preferred_customer_is_made_preferred
{
    Establish context = () =&gt;
    {
        _order = <span class="kwrd">new</span> Order(<span class="kwrd">new</span>[] { <span class="kwrd">new</span> OrderItem(12), 
                                   <span class="kwrd">new</span> OrderItem(16) });
        _totalAmountWithoutDiscount = _order.TotalAmount;

        SUT = <span class="kwrd">new</span> Customer(<span class="kwrd">new</span>[] { _order });
        SUT.MakePreferred();
    };

    Because of = () =&gt;
        SUT.MakePreferred();

    It should_apply_no_additional_discount_to_the_outstanding_orders = () =&gt; 
        _order.TotalAmount.ShouldNotEqual(_totalAmountWithoutDiscount * 0.81);

    <span class="kwrd">private</span> <span class="kwrd">static</span> Customer SUT;

    <span class="kwrd">private</span> <span class="kwrd">static</span> Order _order;
    <span class="kwrd">private</span> <span class="kwrd">static</span> Double _totalAmountWithoutDiscount;
}</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>I warned you about the syntax, didn’t I :-). It only took me a couple of seconds to get used to this syntax but now I’m completely hooked. Instead of using methods and attributes, MSpec utilizes delegates and anonymous methods. But there’s more. </p>

<p>When using <a href="http://www.nunit.com/index.php">NUnit</a> for writing context/ specifications, the <em>Establish_context</em> and <em>Because</em> methods of the example shown earlier is executed before every observation (test). With MSpec, the <em>Establish</em> and <em>Because</em> anonymous methods are executed only once for every context no matter how many observations a particular context class contains. Big difference? Well, at first glance not but on second hand it does make <a href="http://elegantcode.com/2008/12/30/dont-sell-out-on-the-context-dude/">selling out on the context</a> a bit more difficult as it will probably blow up in your face sooner than later. You can force MSpec to execute the <em>Establish</em> and <em>Because</em> anonymous methods before every observation by applying the <em>SetupForEachSpecification</em> attribute to the context class, but I strongly encourage you to stay away from that unless absolutely needed.</p>

<p>Also notice that the fields in the contexts are now all static. This is needed so that the anonymous methods can access those.&#160;&#160;&#160;&#160;&#160; </p>

<p>Running these context/specifications using TestDriven.NET yields the following output in the output window of Visual Studio:</p>

<blockquote>
  <p><font face="Arial">Making a customer preferred, when a regular customer is made preferred
      <br />» should mark the customer as preferred

      <br />» should apply a ten percent discount to all outstanding orders</font></p>

  <p><font face="Arial">Making a customer preferred, when a preferred customer is made preferred
      <br />» should apply no additional discount to the outstanding orders</font></p>
</blockquote>

<p>What’s not to like? Well, the only downside so far is that Resharper was giving me some warnings about classes and fields not being used etc. … . Many of those warnings disappeared by registering the MSpec plugin for the Resharper test runner as I explained earlier.</p>

<p>So far, so good. I’ve got two more posts coming up on MSpec, so stay tuned.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/02/19/getting-started-with-machine-specifications-mspec/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Unity/Moq &#8211; AutoMocker or AutoMockingContainer</title>
		<link>http://elegantcode.com/2010/01/03/unitymoq-automocker-or-automockingcontainer/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=unitymoq-automocker-or-automockingcontainer</link>
		<comments>http://elegantcode.com/2010/01/03/unitymoq-automocker-or-automockingcontainer/#comments</comments>
		<pubDate>Sun, 03 Jan 2010 16:52:33 +0000</pubDate>
		<dc:creator>Jason Jarrett</dc:creator>
				<category><![CDATA[TDD]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Tools and Utilities]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/01/03/unitymoq-automocker-or-automockingcontainer/</guid>
		<description><![CDATA[What is an Auto Mocking Container? This post started to get a little long, so I won’t re-explain the concept. Joshua Flanagan wrote a nice overview at his Los Techies blog: Auto mocking Explained. My post is mainly here to describe the Unity version of an automocking container I threw together. In Jan 2009 I [...]]]></description>
			<content:encoded><![CDATA[<h4>What is an Auto Mocking Container?</h4>  <p>This post started to get a little long, so I won’t re-explain the concept.</p>  <p><a href="http://www.lostechies.com/blogs/joshuaflanagan/default.aspx">Joshua Flanagan</a> wrote a nice overview at his <a href="http://www.lostechies.com/">Los Techies</a> blog: <a href="http://www.lostechies.com/blogs/joshuaflanagan/archive/2009/02/03/auto-mocking-explained.aspx"><strong>Auto mocking Explained</strong></a>.</p>  <p>My post is mainly here to describe the Unity version of an automocking container I threw together.</p>  <h4>In Jan 2009 I blogged about my initial version of the Unity AutoMocker - Why am I blogging about it again?</h4>  <p>I originally wrote the AutoMocker for the Unity container a year ago (Jan 2009, in Silverlight), and finally got around to placing the code up in the <a href="http://code.google.com/p/moq-contrib/">moq-contrib</a> project in June of 2009.</p>  <p>I’m writing another post today in hopes to:</p>  <ol>   <li>Get some feedback on how this little snippet of code should continue. </li>    <li>Give a little more how-to/example code </li>    <li>Describe some updates I made since I originally created it.&#160; </li> </ol>  <h4>Where can I get it?</h4>  <p><strong>This is one part where I’d appreciate some feedback.</strong></p>  <p>I have two slightly different versions out there (currently).</p>  <p>I have one version at the <a href="http://code.google.com/p/elegantcode/source/browse/#svn/trunk/Coders/JasonJarrett/UnityAutoMocker">ElegantCode</a> repository where I was working on it, and the other I threw up at <a href="http://code.google.com/p/moq-contrib/">moq-contrib</a>.</p>  <p>The core of the UnityAutoMockContainer is the same in both places, it’s how the tests are separated out that differ.</p>  <p>In the <a href="http://code.google.com/p/elegantcode/source/browse/#svn/trunk/Coders/JasonJarrett/UnityAutoMocker">ElegantCode repository</a> it’s an all in one self contained single file (that you can copy into your own test project(s)). You can then setup a single test in your own testing framework that runs all internal automocker tests (in case you need to modify it yourself, and don’t want to break any existing functionality). EX: test</p>  <pre class="brush: csharp;">[Test]
public void Should_run_all_UnityAutoMockContainer_internal_tests()
{
    Moq.AutoMocking.SelfTesting.UnityAutoMockContainerFixture
        .RunAllTests(Console.WriteLine);
}</pre>

<p>I kind of like this format as it makes it easy to port between test libraries. Can’t say I like having the tests in the same file as the core, but it certainly is not a large chunk of code (so far) so it’s relatively small to maintain and definitely easier to manage as a single .cs file than another assembly (which would have to be version dependent on both Unity and Moq).</p>

<p>The <a href="http://code.google.com/p/moq-contrib/">moq-contrib</a> is definitely where I think this helper should end up (and it is there). I just happened to break the tests out into the Silverlight test project and the core is alone in a file. </p>

<p>It’s current state isn’t as easy to copy to a test library (Silverlight/Desktop/Unity 1.2/Unity 2.0) as the one at <a href="http://elegantcode.com/">ElegantCode</a>. <strong>What does anyone think?</strong> Should I put them all together in one file?</p>

<p>However it ends up (1. all in one file or two (1 test) (1 core)) it will continue to be maintained on the <a href="http://code.google.com/p/moq-contrib/">moq-contrib</a> project.</p>

<h4>What is the high level API of the container?</h4>

<p>It’s pretty simple, (currently) there are four methods on the container.</p>

<p><strong>Two for registering items with the container</strong>. Say you want to register an already created instance, or say you want to map an interface to a concrete class and _not_ have the container generate mocks automatically for special cases. </p>

<p>And <strong>two for pulling items out of the container</strong>. Whether you want a instance of T or a Mock&lt;T&gt;, it gives you ways to retrieve both.</p>

<blockquote>
  <p><a href="http://elegantcode.com/wp-content/uploads/2010/01/image.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://elegantcode.com/wp-content/uploads/2010/01/image_thumb.png" width="396" height="106" /></a> </p>
</blockquote>

<h4>How can I setup my own registrations with the container? </h4>

<p>Say I don’t want to have the container generate mocks for specific items and I want to supply specific configuration to the UnityContainer.</p>

<blockquote>
  <p>public UnityAutoMockContainer RegisterInstance&lt;TService&gt;(TService instance)</p>

  <p>public UnityAutoMockContainer Register&lt;TService, TImplementation&gt;() 
    <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; where TImplementation : TService</p>
</blockquote>

<p><strong>Note</strong>: both of these registration methods return the container itself so you can fluently stack registration. <strong>EX:</strong></p>

<pre class="brush: csharp;">AutoMockContainer
    .Register&lt;IServiceA, ServiceA&gt;()
    .Register&lt;IServiceB, ServiceB&gt;();</pre>

<p><strong>Let me know</strong>: I haven’t tested or played around with how this automocking container deals with any container specific xml configuration… So although I don’t think you should probably have that in a test assembly (stuff happens). Let me know if there are any issues.</p>

<h4>How do I get items out of the container?</h4>

<p>First is the Resolve&lt;T&gt;(). It will pull an item T out of the container. (Creating it if not already existing)</p>

<blockquote>
  <p>public T Resolve&lt;T&gt;()</p>
</blockquote>

<p>When T is an interface Resolve&lt;T&gt; (unless you setup registration specifically with the container) should return basically “(new Mock&lt;T&gt;()).Object”</p>

<p>When T is a concrete Class, the container should return an instance of T and any of it’s dependencies will be satisfied by mocks. (Note that T will not be any sort of mocked instance of T, unless you used the GetMock&lt;T&gt; as described below first)</p>

<blockquote>
  <p>public Mock&lt;T&gt; GetMock&lt;T&gt;() where T : class</p>
</blockquote>

<p>When T is an interface GetMock&lt;T&gt; should return basically “(new Mock&lt;T&gt;())” </p>

<p>When T is a concrete Class, the container should return a new Mock&lt;T&gt;() and any of it’s dependencies will be satisfied by mocks.</p>

<h4>How do I use the UnityAutoMockContainer?</h4>

<p>It’s pretty basic, you first create an instance of the UnityAutoMockContainer, and from there you can ask it for mocks of an (Interface, Class, or Abstract Class).</p>

<p>If you request an instance of a concrete class, or abstract class, the UnityAutoMockContainer will stuff mocks in for any constructor dependencies of your concrete class (if it can). You can then request from the container those same dependencies one at a time and either apply mocking setups or verifications.</p>

<blockquote>
  <p><strong>NOTE:</strong> Anything the container creates will live as a singleton instance in the container. So any other requests from the container will always return the originally created instance. Therefore, each distinct scenario in a test suite should have their own instances of the container.</p>
</blockquote>

<p>Below his an example of how you can leverage the container in some tests. Given this base fixture class…</p>

<pre class="brush: csharp;">public class FixtureBase
{
    private readonly UnityAutoMockContainer _autoMockContainer = new UnityAutoMockContainer();

    protected UnityAutoMockContainer AutoMockContainer
    {
        get { return _autoMockContainer; }
    }

    [TestFixtureSetUp]
    public void SetupContext_ALL()
    {
        Before_all_tests();
        Because();
    }

    [TestFixtureTearDown]
    public void TearDownContext_ALL()
    {
        After_all_tests();
    }

    protected virtual void Before_all_tests()
    {
    }

    protected virtual void Because()
    {
    }

    protected virtual void After_all_tests()
    {
    }
}</pre>

<p>If I were given the following system to test.</p>

<pre class="brush: csharp;">public interface IServiceA { void RunA(); }
public interface IServiceB { void RunB(); }

public class TestComponent
{
    public TestComponent(IServiceA serviceA, IServiceB serviceB)
    {
        ServiceA = serviceA;
        ServiceB = serviceB;
    }

    public IServiceA ServiceA { get; private set; }
    public IServiceB ServiceB { get; private set; }

    public void RunAll()
    {
        if (!HowDidItGo())
            return;
        ServiceA.RunA();
        ServiceB.RunB();
    }

    public virtual bool HowDidItGo()
    {
        // some really nasty untestable code
        return true;
    }
}</pre>

<p>The below example demonstrates simply verifying some behavior on the mocked dependencies of the system under test.</p>

<pre class="brush: csharp;">[TestFixture]
public class Example__how_to_pull_items_from_the_UnityAutoMockContainer_when_verifying_behavior_after_an_action_was_taken 
    : FixtureBase
{
    private TestComponent _testComponent;

    protected override void Before_all_tests()
    {
        base.Before_all_tests();
        _testComponent = AutoMockContainer.Resolve&lt;TestComponent&gt;();
    }

    protected override void Because()
    {
        _testComponent.RunAll();
    }

    [Test]
    public void Should_run_ServiceA_RunA()
    {
        AutoMockContainer
            .GetMock&lt;IServiceA&gt;()
            .Verify(v =&gt; v.RunA(), Times.Once());
    }

    [Test]
    public void Should_run_ServiceB_RunB()
    {
        AutoMockContainer
            .GetMock&lt;IServiceB&gt;()
            .Verify(v =&gt; v.RunB(), Times.Once());
    }
}</pre>

<p>Next, you may have noticed that the system under test had a complicated internal method (that may not necessarily be testable). You can use the AutoMocker to create the system under test as a Mock itself, so we can override some of the behavior. Here’s how you could quickly do that. </p>

<blockquote>
  <p><strong>Aside</strong>: I’m not saying this is a good practice or aids in good component design, just saying it’s possible</p>
</blockquote>

<pre class="brush: csharp;">[TestFixture]
public class Example__how_to_use_the_UnityAutoMockContainer_to_override_a_method_on_the_SystemUnderTest_to_test_a_certain_behavior
    : FixtureBase
{

    private TestComponent _testComponent;

    protected override void Before_all_tests()
    {
        base.Before_all_tests();
        var mockTestComponent = AutoMockContainer.GetMock&lt;TestComponent&gt;();

        mockTestComponent
            .Setup(s =&gt; s.HowDidItGo())
            .Returns(false);

        _testComponent = mockTestComponent.Object;
    }

    protected override void Because()
    {
        _testComponent.RunAll();
    }

    [Test]
    public void Should_run_ServiceA_RunA()
    {
        AutoMockContainer
            .GetMock&lt;IServiceA&gt;()
            .Verify(v =&gt; v.RunA(), Times.Never());
    }

    [Test]
    public void Should_run_ServiceB_RunB()
    {
        AutoMockContainer
            .GetMock&lt;IServiceB&gt;()
            .Verify(v =&gt; v.RunB(), Times.Never());
    }
}</pre>

<p>&#160;</p>

<p>It’s amazing how much redundant test setup code this little helper has saved me in my tests. I hope others can find some use with this as well.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/01/03/unitymoq-automocker-or-automockingcontainer/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>StatLight &#8211; Goes Open Source</title>
		<link>http://elegantcode.com/2009/12/10/statlight-goes-open-source/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=statlight-goes-open-source</link>
		<comments>http://elegantcode.com/2009/12/10/statlight-goes-open-source/#comments</comments>
		<pubDate>Fri, 11 Dec 2009 03:26:55 +0000</pubDate>
		<dc:creator>Jason Jarrett</dc:creator>
				<category><![CDATA[Esoterica]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[TDD]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Tools and Utilities]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/12/10/statlight-goes-open-source/</guid>
		<description><![CDATA[Although I made a very minor attempt at making StatLight a “for-sale” product, I knew when I started that open-source was most likely going to be my long term path for StatLight. What is it? (Silverlight Testing Automation Tool) StatLight is a tool developed for automating the setup, running, and gathering results of Silverlight unit [...]]]></description>
			<content:encoded><![CDATA[Although I made a very minor attempt at making <a href="http://statlight.net" target="_blank">StatLight</a> a “for-sale” product, I knew when I started that open-source was most likely going to be my long term path for <a href="http://statlight.net" target="_blank">StatLight</a>.
<h5>What is it? (Silverlight Testing Automation Tool)</h5>
StatLight is a tool developed for automating the setup, running, and gathering results of Silverlight unit tests. StatLight helps to speed up the feedback cycles while practicing<a href="http://en.wikipedia.org/wiki/Test-driven_development"> TDD</a>/<a href="http://en.wikipedia.org/wiki/Behavior_Driven_Development">BDD</a>/(insert your test style here) during Silverlight development.
<h5>Where can I get StatLight?</h5>
<a href="http://StatLight.CodePlex.com">http://StatLight.CodePlex.com</a>
<h4>Happy Coding !!!</h4>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/12/10/statlight-goes-open-source/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Wrapping up the StructureMap Automocking Container</title>
		<link>http://elegantcode.com/2009/11/30/wrapping-up-the-structuremap-automocking-container/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=wrapping-up-the-structuremap-automocking-container</link>
		<comments>http://elegantcode.com/2009/11/30/wrapping-up-the-structuremap-automocking-container/#comments</comments>
		<pubDate>Mon, 30 Nov 2009 07:21:43 +0000</pubDate>
		<dc:creator>Richard Cirerol</dc:creator>
				<category><![CDATA[TDD]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Unit Testing]]></category>
		<category><![CDATA[StructureMap; Automocking; MSpec;]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/11/30/wrapping-up-the-structuremap-automocking-container/</guid>
		<description><![CDATA[<p><font color="#804040"><strong>UPDATE</strong>: I apologize…the original wrapper did not allow injected dependencies.&#160; I have fixed this bug and updated the sample.</font></p> I have been using StructureMap.AutoMocking with MSpec (Machine.Specifications) and Rhino.Mocks for a few months now.  Although I am very comfortable with the patterns that emerge from using the frameworks together, introducing StructureMap.Automocking to other developers is sometimes challenging. I decided to wrap the details of the container to make the intention clearer and explanation easier.  I have started using this wrapper in my projects, and have found it makes building up specifications more efficient in my daily coding.]]></description>
			<content:encoded><![CDATA[<span style="color: #804040;"><strong>UPDATE</strong>: I apologize…the original wrapper did not allow injected dependencies.  I have fixed this bug and updated the sample.</span>

I have been using StructureMap.AutoMocking with MSpec (Machine.Specifications) and Rhino.Mocks for a few months now.  Although I am very comfortable with the patterns that emerge from using the frameworks together, introducing StructureMap.Automocking to other developers is sometimes challenging.

When viewing a specification or test set up with the Rhino.Mocks or Moq automocking container, what is being tested is not readily apparent.  Once the concept is explained and demonstrated, these same developers seem to have no issue with maintaining the specifications/tests.

I decided to wrap the details of the container to make the intention clearer and explanation easier.  I have started using this wrapper in my projects, and have found it makes building up specifications more efficient in my daily coding.

Let me know whether this is useful to you, or how it could be made more useful.
<h4>The Examples</h4>
Let’s contrive an example.  We’ll say we have a coffee machine that grinds its own beans before brewing. However, the hopper has to have beans before starting the grind.  Here is the basic specification:
<table border="1" cellspacing="0" cellpadding="2" width="533">
<tbody>
<tr>
<td width="117" valign="top">Action/Behavior</td>
<td width="414" valign="top">Prepare coffee grounds for 12 cups of coffee</td>
</tr>
<tr>
<td rowspan="2" width="117" valign="top">Expectations</td>
<td width="414" valign="top">Should check that hopper has beans (mock returns true)</td>
</tr>
<tr>
<td width="414" valign="top">Because hopper has beans, should ask grinder to grind enough beans for 12 cups of coffee</td>
</tr>
</tbody></table>
We could start without a container, using Rhino.Mocks to build up the CoffeeMachine dependencies manually:
<pre class="brush: csharp;">[Subject(typeof(CoffeeMachine),"using vanilla Rhino.Mocks")]
public class Example01_when_preparing_coffee_grounds
{
    Establish context = () =&gt;
        {
            Grinder = MockRepository.GenerateMock&lt;IGrinder&gt;();
            Hopper = MockRepository.GenerateMock&lt;IHopper&gt;();
            Hopper.Expect(x =&gt; x.HasBeans()).Return(true);
            CoffeeMachine = new CoffeeMachine(Grinder, Hopper);
        };

    Because of = () =&gt; _coffeeMachine.PrepareCoffeeGrounds(12);

    It should_check_if_hopper_has_beans = () =&gt; Hopper.VerifyAllExpectations();
    It should_grind_coffee = () =&gt; Grinder.AssertWasCalled(x =&gt; x.Grind(12));

    static IGrinder Grinder;
    static IHopper Hopper;
    static CoffeeMachine CoffeeMachine;
}</pre>
For those of you not familiar with the MSpec style, please refer to the following posts:
<ul>
	<li><a href="http://blog.wekeroad.com/blog/make-bdd-your-bff-2/" target="_blank">Make BDD Your BFF</a></li>
	<li><a href="http://www.lostechies.com/blogs/seanbiefeld/archive/2009/08/25/step-by-step-to-using-machine-specifications-with-resharper.aspx" target="_blank">Step by Step to Using MSpec (Machine.Specifications) with ReSharper</a></li>
	<li><a href="http://elegantcode.com/2009/07/05/mspec-take-2/" target="_blank">MSpec - Take 2</a></li>
	<li><a href="http://marcinobel.com/index.php/mspec-bdd-installer/" target="_blank">MSpec BDD framework installer</a></li>
	<li><strong>Updated! </strong>From the <a href="http://blog.cwa.me.uk/2009/11/30/the-morning-brew-487/" target="_blank">Morning Brew #487</a>: BDD with MSpec and Rhino Auto Mocks, parts  <a href="http://telldontask.wordpress.com/2009/11/10/bdd-with-mspec-and-rhino-auto-mocks/" target="_blank">1</a>, <a href="http://telldontask.wordpress.com/2009/11/19/bdd-with-mspec-and-rhino-auto-mocks-part-2/" target="_blank">2</a>, and <a href="http://telldontask.wordpress.com/2009/11/29/bdd-with-mspec-and-rhino-auto-mocks-part-3/" target="_blank">3</a>
Here is the same specification using the RhinoAutoMocker&lt;T&gt; class provided by StructureMap.AutoMocking:</li>
</ul>
<pre class="brush: csharp;">[Subject(typeof(CoffeeMachine),"using RhinoAutoMocker&lt;CoffeeMachine&gt;")]
public class Example02_when_preparing_coffee_grounds
{
    Establish context = () =&gt;
        {
            CoffeeMachine = new RhinoAutoMocker&lt;CoffeeMachine&gt;();
            Grinder = CoffeeMachine.Get&lt;IGrinder&gt;();
            Hopper = CoffeeMachine.Get&lt;IHopper&gt;();
            Hopper.Expect(x =&gt; x.HasBeans()).Return(true);
        };

    Because of = () =&gt; v.ClassUnderTest.PrepareCoffeeGrounds(12);

    It should_check_if_hopper_has_beans = () =&gt; Hopper.VerifyAllExpectations();
    It should_grind_coffee = () =&gt; Grinder.AssertWasCalled(x =&gt; x.Grind(12));

    static IGrinder Grinder;
    static IHopper Hopper;
    static RhinoAutoMocker&lt;CoffeeMachine&gt; CoffeeMachine;
}</pre>
Although I think this looks cleaner, the initialization of CoffeeMachine causes some confusion. Unfortunately, a common question would be, “Is RhinoAutoMocker&lt;CoffeeMachine&gt; creating a mocked version of CoffeeMachine?” Well, not exactly.

RhinoAutoMocker is an implementation of the AutoMocker base class which uses StructureMap to fill dependencies.  The RhinoAutoMocker implementation of the container uses Rhino.Mocks to generate all of dependencies of the target class, whereas the MoqAutoMocker implementation uses Moq.  (Optionally, the target class can be partially mocked in order to further isolate behavior.)  We then retrieve the class under test (in this case, CoffeeMachine) and its dependencies (IGrinder and IHopper) from the container for use.

If you do not need to setup any expectations in the specification, there is no need to retrieve the dependency from the container.  However, in this specification, we need both dependencies.

<em>(Incidentally, I do not like the ClassUnderTest name.  I may end up changing this to Instance, ClassInstance, TargetClass, or something similar.  Suggestions?)</em>

By moving the initialization of the RhinoAutoMocker to a base class, some of the chattiness of the context can be hidden.
<ul>
<pre class="brush: csharp;">[Subject(typeof(CoffeeMachine),"using RhinoAutoMocker base")]
public class Example03_when_preparing_coffee_grounds : with_rhinoautomocker
{
    Establish context = () =&gt; Hopper.Expect(x =&gt; x.HasBeans()).Return(true);

    Because of = () =&gt; CoffeeMachine.ClassUnderTest.PrepareCoffeeGrounds(12);

    It should_check_if_hopper_has_beans = () =&gt; Hopper.VerifyAllExpectations();
    It should_grind_coffee = () =&gt; Grinder.AssertWasCalled(x =&gt; x.Grind(12));

}

[Subject("using RhinoAutoMocker&lt;T&gt;")]
public class with_rhinoautomocker
{
    protected static IGrinder Grinder;
    protected static IHopper Hopper;
    protected static RhinoAutoMocker&lt;CoffeeMachine&gt; CoffeeMachine;

    Establish context = () =&gt;
    {
        CoffeeMachine = new RhinoAutoMocker&lt;CoffeeMachine&gt;();
        Grinder = CoffeeMachine.Get&lt;IGrinder&gt;();
        Hopper = CoffeeMachine.Get&lt;IHopper&gt;();
    };
}</pre>
However, we are still initializing and accessing the class in a less than optimal manner.To make the usage of the container a little more seamless, I decided to create a wrapper and factory for the AutoMocker.  Setup of the dependencies and expectations are done through an AutoMocker wrapper object.  The instance of the class under test is accessed through a ClassUnderTest object.
<h4>The Result</h4>
The specification (and base class) now look like this:
<pre class="brush: csharp;">[Subject(typeof(CoffeeMachine),"using coffee machine base")]
public class Example05_when_preparing_coffee_grounds : with_coffee_machine
{
    Establish context = () =&gt; Hopper.Expect(x =&gt; x.HasBeans()).Return(true);

    Because of = () =&gt; ClassUnderTest.PrepareCoffeeGrounds(12);

    It should_check_if_hopper_has_beans = () =&gt; Hopper.VerifyAllExpectations();
    It should_grind_coffee = () =&gt; Grinder.AssertWasCalled(x =&gt; x.Grind(12));
}

[Subject("using SpecificationFor&lt;CoffeeMachine&gt;")]
public class with_coffee_machine : SpecificationFor&lt;CoffeeMachine&gt;
{
    protected static IGrinder Grinder;
    protected static IHopper Hopper;

    public with_coffee_machine
    {
        Grinder = AutoMocker.Get&lt;IGrinder&gt;();
        Hopper = AutoMocker.Get&lt;IHopper&gt;();
    }
}</pre>
As you can see, the base class inherits from SpecificationFor&lt;T&gt;.  The default constructor uses Rhino.Mocks(MockMode.AAA) to generate the dependencies.  It then exposes a AutoMocker object, which is just the wrapper around the AutoMocker base class.  It also exposes a ClassUnderTest object.  If I didn’t need to use the dependencies, I could make the <em>Example05_when_preparing_coffee_grounds</em> class inherit from <em>SpecificationFor&lt;CoffeeMachine&gt; </em>instead of inheriting from the base class<em>.</em>
<h4>The Code</h4>
I have included the code for the wrapper below for your review.  The code and six examples are available on my <a href="http://codeprogression.googlecode.com/svn/trunk/CodeProgression.Framework.Testing" target="_blank">Google code repository</a>. The repository also includes an example using the MoqAutoMocker.  All the examples have the same assertions, but are built up using the different techniques.
<pre class="brush: csharp;">namespace CodeProgression.Framework.Testing
{
    public abstract class SpecificationFor&lt;T&gt; where T: class
    {
        protected static ClassUnderTest&lt;T&gt; Factory;

        // UPDATE 2009-12-21:
        //   Moved initialization here
        protected static T ClassUnderTest {get {return AutoMocker.Instance;} }

        protected SpecificationFor()
        {
            AutoMocker = AutoMockFactory.CreateTarget&lt;T&gt;();

            // UPDATE 2009-12-21:
            //    Initializing here prevented injected dependencies!
            // AutoMocker.PartialMockTheClassUnderTest();
            // ClassUnderTest = AutoMocker.Instance;
        }

        protected SpecificationFor(AutoMockType type)
        {
            AutoMocker = AutoMockFactory.CreateTarget&lt;T&gt;(type);

            // UPDATE 2009-12-21:
            // Initializing here prevented injected dependencies!
            // AutoMocker.PartialMockTheClassUnderTest();
            // ClassUnderTest = AutoMocker.Instance;
        }
    }

    public static class AutoMockFactory
    {
        public static ClassUnderTest&lt;TARGETCLASS&gt; CreateTarget&lt;TARGETCLASS&gt;() where TARGETCLASS : class
        {
            return CreateTarget&lt;TARGETCLASS&gt;(AutoMockType.RhinoMocksAAA);
        }

        public static ClassUnderTest&lt;TARGETCLASS&gt; CreateTarget&lt;TARGETCLASS&gt;(AutoMockType framework) where TARGETCLASS : class
        {
            AutoMocker&lt;TARGETCLASS&gt; mocker;
            ServiceLocator serviceLocator;
            switch (framework)
            {
                case AutoMockType.RhinoMocksAAA:
                    mocker = new RhinoAutoMocker&lt;TARGETCLASS&gt;(MockMode.AAA);
                    serviceLocator = new RhinoMocksAAAServiceLocator();
                    break;
                case AutoMockType.RhinoMocksClassic:
                    mocker = new RhinoAutoMocker&lt;TARGETCLASS&gt;(MockMode.RecordAndReplay);
                    serviceLocator = new RhinoMocksClassicServiceLocator();
                    break;
                case AutoMockType.Moq:
                    mocker = new MoqAutoMocker&lt;TARGETCLASS&gt;();
                    serviceLocator = new MoqServiceLocator();
                    break;
                default:
                    throw new ArgumentOutOfRangeException("framework");
            }
            return new ClassUnderTest&lt;TARGETCLASS&gt;(mocker, serviceLocator);
        }
    }

    public enum AutoMockType
    {
        Moq,
        RhinoMocksAAA,
        RhinoMocksClassic
    }

    public class ClassUnderTest&lt;TARGETCLASS&gt; where TARGETCLASS : class
    {
        readonly IAutoMocker&lt;TARGETCLASS&gt; _mocker;
        readonly ServiceLocator _serviceLocator;

        public ClassUnderTest(IAutoMocker&lt;TARGETCLASS&gt; mocker, ServiceLocator serviceLocator)
        {
            _mocker = mocker;
            _serviceLocator = serviceLocator;
        }

        public AutoMockedContainer Container
        {
            get { return _mocker.Container; }
        }

        public TARGETCLASS Instance
        {
            get { return _mocker.ClassUnderTest; }
        }

        public void MockObjectFactory()
        {
            _mocker.MockObjectFactory();
        }

        public void PartialMockTheClassUnderTest()
        {
            _mocker.PartialMockTheClassUnderTest();
        }

        public T Get&lt;T&gt;() where T : class
        {
            return _mocker.Get&lt;T&gt;();
        }

        public void Inject(Type pluginType, object stub)
        {
            _mocker.Inject(pluginType, stub);
        }

        public void Inject&lt;T&gt;(T target)
        {
            _mocker.Inject(target);
        }

        public T AddAdditionalMockFor&lt;T&gt;() where T : class
        {
            return _mocker.AddAdditionalMockFor&lt;T&gt;();
        }

        public void UseConcreteClassFor&lt;T&gt;()
        {
            _mocker.UseConcreteClassFor&lt;T&gt;();
        }

        public T[] CreateMockArrayFor&lt;T&gt;(int count) where T : class
        {
            return _mocker.CreateMockArrayFor&lt;T&gt;(count);
        }

        public void InjectArray&lt;T&gt;(T[] stubs)
        {
            _mocker.InjectArray(stubs);
        }

        public T Mock&lt;T&gt;() where T : class
        {
            return _serviceLocator.Service&lt;T&gt;();
        }
        public object Mock(Type serviceType)
        {
            return _serviceLocator.Service(serviceType);
        }
        public T PartialMock&lt;T&gt;() where T : class
        {
            return _serviceLocator.PartialMock&lt;T&gt;();
        }
    }
}</pre>
</ul>
<script type="text/javascript">// <![CDATA[
 var cirerolGaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."); document.write(unescape("%3Cscript src='" + cirerolGaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
// ]]&gt;</script>

<script type="text/javascript">// <![CDATA[
 var cirerolPageTracker = _gat._getTracker('UA-8257866-3'); cirerolPageTracker._initData(); cirerolPageTracker._trackPageview();
// ]]&gt;</script>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/11/30/wrapping-up-the-structuremap-automocking-container/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Integration Test Brought to you by Powershell &amp; NUnit &#8211; with a Little Specification Syntax for Flavoring</title>
		<link>http://elegantcode.com/2009/10/25/integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring</link>
		<comments>http://elegantcode.com/2009/10/25/integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring/#comments</comments>
		<pubDate>Mon, 26 Oct 2009 05:00:40 +0000</pubDate>
		<dc:creator>Jason Jarrett</dc:creator>
				<category><![CDATA[Esoterica]]></category>
		<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/10/25/integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring/</guid>
		<description><![CDATA[One of the tools I’ve used the last half of a year and really enjoyed is the C# specification extension methods when writing unit test assertions. If you’re looking for a little more background on the topic, I wrote about Fluent Specification Extensions in a past blog. Recently I wanted to execute a PowerShell script [...]]]></description>
			<content:encoded><![CDATA[One of the tools I’ve used the last half of a year and really enjoyed is the C# specification extension methods when writing unit test assertions. If you’re looking for a little more background on the topic, I wrote about <a href="http://staxmanade.blogspot.com/2009/02/fluent-specification-extensions.html">Fluent Specification Extensions</a> in a past blog.

Recently I wanted to execute a PowerShell script to do some automated <a href="http://en.wikipedia.org/wiki/Functional_testing">functional testing</a>. I wanted to execute an application and apply some assertions on the output of the software(basically running a console app, parse the xml output and assert on values in the output).
<blockquote>FYI: I’m very new to PowerShell, so any suggestions on how I implemented the below are welcome…</blockquote>
I’ve seen a couple examples of writing test assertions in PowerShell out there. One example is <a href="http://www.psunit.org/">PSUnit</a>; however, this seemed a little heavy for my needs and not quite the syntactic sugar I was looking for.

Besides the syntax flavor I was desiring, another thing I wanted to do was leverage the power of NUnit.Framework’s assertion capabilities. I like the error messages generated when strings and other objects fail the assertion.
<h5>Examples of end result ShouldLookLike()…</h5>
$true.ShouldBeTrue()
$false.ShouldBeFalse()
"a".ShouldEqual("a")
"a".ShouldNotEqual("b")
<h5><strong>Step 1</strong>: Figure out how to write a C# style <a href="http://msdn.microsoft.com/en-us/library/bb383977.aspx">extension method</a> in PowerShell.</h5>
<blockquote>I found a great blog post describing how to extend any PowerShell object to add extension methods.

<a href="http://bartdesmet.net/blogs/bart/archive/2007/09/06/extension-methods-in-windows-powershell.aspx">Extension Methods in Windows PowerShell</a></blockquote>
In short, to extend types in PowerShell leveraging the <a href="http://msdn.microsoft.com/en-us/library/ms714419(VS.85).aspx">Extended Type System</a>, you need to define them in an xml file and import the method definitions into the PowerShell runtime instance.

Below is PowerShell XML definition for my NUnit Specification Extensions.
<pre class="brush: xml;">&lt;?xml version="1.0" encoding="utf-16"?&gt;
&lt;Types&gt;
    &lt;Type&gt;
        &lt;Name&gt;System.Object&lt;/Name&gt;
        &lt;Members&gt;
            &lt;ScriptMethod&gt;
                &lt;Name&gt;ShouldBeFalse&lt;/Name&gt;
                &lt;Script&gt;
                    [NUnit.Framework.Assert]::IsFalse($this)
                &lt;/Script&gt;
            &lt;/ScriptMethod&gt;
            &lt;ScriptMethod&gt;
                &lt;Name&gt;ShouldBeTrue&lt;/Name&gt;
                &lt;Script&gt;
                    [NUnit.Framework.Assert]::IsTrue($this)
                &lt;/Script&gt;
            &lt;/ScriptMethod&gt;
            &lt;ScriptMethod&gt;
                &lt;Name&gt;ShouldEqual&lt;/Name&gt;
                &lt;Script&gt;
                    [NUnit.Framework.Assert]::AreEqual($args[0], $this)
                &lt;/Script&gt;
            &lt;/ScriptMethod&gt;
            &lt;ScriptMethod&gt;
                &lt;Name&gt;ShouldNotEqual&lt;/Name&gt;
                &lt;Script&gt;
                    [NUnit.Framework.Assert]::AreNotEqual($args[0], $this)
                &lt;/Script&gt;
            &lt;/ScriptMethod&gt;
        &lt;/Members&gt;
    &lt;/Type&gt;
&lt;/Types&gt;</pre>
<h4></h4>
Take the above XML and save it to a file…
<blockquote>NOTE: the file HAS to be saved with the extension <strong>.ps1xml</strong>

Ex: NunitSpecificationPowerShellExtensions<strong>.ps1xml</strong></blockquote>
<h4></h4>
<h5>Step 2: Load the extended type definition into the PowerShell runtime.</h5>
Once you’ve saved the XML extended types to a file, you need to load it into the PowerShell runtime by executing the command below.
<blockquote>
Update-TypeData -PrependPath NunitSpecificationPowerShellExtensions.ps1xml</blockquote>
Before executing the above statement…Let’s quickly look at a System.String’s members and properties – just to show you what the extension methods look like when applied inside of the runtime.<a href="http://elegantcode.com/wp-content/uploads/2009/10/image3.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" src="http://elegantcode.com/wp-content/uploads/2009/10/image_thumb2.png" border="0" alt="image" width="586" height="479" /></a>

After executing the Update-TypeData command you’ll notice there are a number of “ScriptMethod” MemberTypes added to the object.

<a href="http://elegantcode.com/wp-content/uploads/2009/10/image4.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" src="http://elegantcode.com/wp-content/uploads/2009/10/image_thumb3.png" border="0" alt="image" width="600" height="580" /></a>

Now if you try to execute one of those newly added extension methods, you may get the following error…

PS C:\&gt; $testVar.<strong>ShouldEqual</strong>("hello world")

Exception calling "ShouldEqual" with "1" argument(s): "<strong>Unable to find type [NUnit.Framework.Assert]: make sure that the

assembly containing this type is loaded.</strong>"

At line:1 char:21

+ $testVar.ShouldEqual &lt;&lt;&lt;&lt; ("hello world")

+ CategoryInfo          : NotSpecified: (:) [], MethodInvocationException

+ FullyQualifiedErrorId : ScriptMethodRuntimeException

This is because we need to load the NUnit.Framework assembly into the runtime before we can leverage the extension methods.
<blockquote>[System.Reflection.Assembly]::LoadFrom("C:\Program Files\NUnit 2.5.2\bin\net-2.0\framework\nunit.framework.dll") | Out-Null</blockquote>
Now that the extension methods have been defined and loaded into the runtime, NUnit.Framework is loaded, we can now use the methods on any object that inherits from System.Object (which, as far as I know, is everything in PowerShell).

And now, everything you need in one script (if you have the xml extended type file saved somewhere…)
<pre>#
# Update-TypeData -prependPath C:\Code\NunitSpecificationPowerShellExtensions.ps1xml
#

[System.Reflection.Assembly]::LoadFrom("C:\Program Files\NUnit 2.5.2\bin\net-2.0\framework\nunit.framework.dll") | Out-Null

$true.ShouldBeTrue()

$false.ShouldBeFalse()

"a".ShouldEqual("a")

"a".ShouldNotEqual("b")</pre>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/10/25/integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Visual Studio Team System for Small Teams</title>
		<link>http://elegantcode.com/2010/01/03/unitymoq-automocker-or-automockingcontainer/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=unitymoq-automocker-or-automockingcontainer</link>
		<comments>http://elegantcode.com/2010/01/03/unitymoq-automocker-or-automockingcontainer/#comments</comments>
		<pubDate>Sun, 03 Jan 2010 16:52:33 +0000</pubDate>
		<dc:creator>Jason Jarrett</dc:creator>
				<category><![CDATA[TDD]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Tools and Utilities]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/01/03/unitymoq-automocker-or-automockingcontainer/</guid>
		<description><![CDATA[What is an Auto Mocking Container? This post started to get a little long, so I won’t re-explain the concept. Joshua Flanagan wrote a nice overview at his Los Techies blog: Auto mocking Explained. My post is mainly here to describe the Unity version of an automocking container I threw together. In Jan 2009 I [...]]]></description>
			<content:encoded><![CDATA[<h4>What is an Auto Mocking Container?</h4>  <p>This post started to get a little long, so I won’t re-explain the concept.</p>  <p><a href="http://www.lostechies.com/blogs/joshuaflanagan/default.aspx">Joshua Flanagan</a> wrote a nice overview at his <a href="http://www.lostechies.com/">Los Techies</a> blog: <a href="http://www.lostechies.com/blogs/joshuaflanagan/archive/2009/02/03/auto-mocking-explained.aspx"><strong>Auto mocking Explained</strong></a>.</p>  <p>My post is mainly here to describe the Unity version of an automocking container I threw together.</p>  <h4>In Jan 2009 I blogged about my initial version of the Unity AutoMocker - Why am I blogging about it again?</h4>  <p>I originally wrote the AutoMocker for the Unity container a year ago (Jan 2009, in Silverlight), and finally got around to placing the code up in the <a href="http://code.google.com/p/moq-contrib/">moq-contrib</a> project in June of 2009.</p>  <p>I’m writing another post today in hopes to:</p>  <ol>   <li>Get some feedback on how this little snippet of code should continue. </li>    <li>Give a little more how-to/example code </li>    <li>Describe some updates I made since I originally created it.&#160; </li> </ol>  <h4>Where can I get it?</h4>  <p><strong>This is one part where I’d appreciate some feedback.</strong></p>  <p>I have two slightly different versions out there (currently).</p>  <p>I have one version at the <a href="http://code.google.com/p/elegantcode/source/browse/#svn/trunk/Coders/JasonJarrett/UnityAutoMocker">ElegantCode</a> repository where I was working on it, and the other I threw up at <a href="http://code.google.com/p/moq-contrib/">moq-contrib</a>.</p>  <p>The core of the UnityAutoMockContainer is the same in both places, it’s how the tests are separated out that differ.</p>  <p>In the <a href="http://code.google.com/p/elegantcode/source/browse/#svn/trunk/Coders/JasonJarrett/UnityAutoMocker">ElegantCode repository</a> it’s an all in one self contained single file (that you can copy into your own test project(s)). You can then setup a single test in your own testing framework that runs all internal automocker tests (in case you need to modify it yourself, and don’t want to break any existing functionality). EX: test</p>  <pre class="brush: csharp;">[Test]
public void Should_run_all_UnityAutoMockContainer_internal_tests()
{
    Moq.AutoMocking.SelfTesting.UnityAutoMockContainerFixture
        .RunAllTests(Console.WriteLine);
}</pre>

<p>I kind of like this format as it makes it easy to port between test libraries. Can’t say I like having the tests in the same file as the core, but it certainly is not a large chunk of code (so far) so it’s relatively small to maintain and definitely easier to manage as a single .cs file than another assembly (which would have to be version dependent on both Unity and Moq).</p>

<p>The <a href="http://code.google.com/p/moq-contrib/">moq-contrib</a> is definitely where I think this helper should end up (and it is there). I just happened to break the tests out into the Silverlight test project and the core is alone in a file. </p>

<p>It’s current state isn’t as easy to copy to a test library (Silverlight/Desktop/Unity 1.2/Unity 2.0) as the one at <a href="http://elegantcode.com/">ElegantCode</a>. <strong>What does anyone think?</strong> Should I put them all together in one file?</p>

<p>However it ends up (1. all in one file or two (1 test) (1 core)) it will continue to be maintained on the <a href="http://code.google.com/p/moq-contrib/">moq-contrib</a> project.</p>

<h4>What is the high level API of the container?</h4>

<p>It’s pretty simple, (currently) there are four methods on the container.</p>

<p><strong>Two for registering items with the container</strong>. Say you want to register an already created instance, or say you want to map an interface to a concrete class and _not_ have the container generate mocks automatically for special cases. </p>

<p>And <strong>two for pulling items out of the container</strong>. Whether you want a instance of T or a Mock&lt;T&gt;, it gives you ways to retrieve both.</p>

<blockquote>
  <p><a href="http://elegantcode.com/wp-content/uploads/2010/01/image.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://elegantcode.com/wp-content/uploads/2010/01/image_thumb.png" width="396" height="106" /></a> </p>
</blockquote>

<h4>How can I setup my own registrations with the container? </h4>

<p>Say I don’t want to have the container generate mocks for specific items and I want to supply specific configuration to the UnityContainer.</p>

<blockquote>
  <p>public UnityAutoMockContainer RegisterInstance&lt;TService&gt;(TService instance)</p>

  <p>public UnityAutoMockContainer Register&lt;TService, TImplementation&gt;() 
    <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; where TImplementation : TService</p>
</blockquote>

<p><strong>Note</strong>: both of these registration methods return the container itself so you can fluently stack registration. <strong>EX:</strong></p>

<pre class="brush: csharp;">AutoMockContainer
    .Register&lt;IServiceA, ServiceA&gt;()
    .Register&lt;IServiceB, ServiceB&gt;();</pre>

<p><strong>Let me know</strong>: I haven’t tested or played around with how this automocking container deals with any container specific xml configuration… So although I don’t think you should probably have that in a test assembly (stuff happens). Let me know if there are any issues.</p>

<h4>How do I get items out of the container?</h4>

<p>First is the Resolve&lt;T&gt;(). It will pull an item T out of the container. (Creating it if not already existing)</p>

<blockquote>
  <p>public T Resolve&lt;T&gt;()</p>
</blockquote>

<p>When T is an interface Resolve&lt;T&gt; (unless you setup registration specifically with the container) should return basically “(new Mock&lt;T&gt;()).Object”</p>

<p>When T is a concrete Class, the container should return an instance of T and any of it’s dependencies will be satisfied by mocks. (Note that T will not be any sort of mocked instance of T, unless you used the GetMock&lt;T&gt; as described below first)</p>

<blockquote>
  <p>public Mock&lt;T&gt; GetMock&lt;T&gt;() where T : class</p>
</blockquote>

<p>When T is an interface GetMock&lt;T&gt; should return basically “(new Mock&lt;T&gt;())” </p>

<p>When T is a concrete Class, the container should return a new Mock&lt;T&gt;() and any of it’s dependencies will be satisfied by mocks.</p>

<h4>How do I use the UnityAutoMockContainer?</h4>

<p>It’s pretty basic, you first create an instance of the UnityAutoMockContainer, and from there you can ask it for mocks of an (Interface, Class, or Abstract Class).</p>

<p>If you request an instance of a concrete class, or abstract class, the UnityAutoMockContainer will stuff mocks in for any constructor dependencies of your concrete class (if it can). You can then request from the container those same dependencies one at a time and either apply mocking setups or verifications.</p>

<blockquote>
  <p><strong>NOTE:</strong> Anything the container creates will live as a singleton instance in the container. So any other requests from the container will always return the originally created instance. Therefore, each distinct scenario in a test suite should have their own instances of the container.</p>
</blockquote>

<p>Below his an example of how you can leverage the container in some tests. Given this base fixture class…</p>

<pre class="brush: csharp;">public class FixtureBase
{
    private readonly UnityAutoMockContainer _autoMockContainer = new UnityAutoMockContainer();

    protected UnityAutoMockContainer AutoMockContainer
    {
        get { return _autoMockContainer; }
    }

    [TestFixtureSetUp]
    public void SetupContext_ALL()
    {
        Before_all_tests();
        Because();
    }

    [TestFixtureTearDown]
    public void TearDownContext_ALL()
    {
        After_all_tests();
    }

    protected virtual void Before_all_tests()
    {
    }

    protected virtual void Because()
    {
    }

    protected virtual void After_all_tests()
    {
    }
}</pre>

<p>If I were given the following system to test.</p>

<pre class="brush: csharp;">public interface IServiceA { void RunA(); }
public interface IServiceB { void RunB(); }

public class TestComponent
{
    public TestComponent(IServiceA serviceA, IServiceB serviceB)
    {
        ServiceA = serviceA;
        ServiceB = serviceB;
    }

    public IServiceA ServiceA { get; private set; }
    public IServiceB ServiceB { get; private set; }

    public void RunAll()
    {
        if (!HowDidItGo())
            return;
        ServiceA.RunA();
        ServiceB.RunB();
    }

    public virtual bool HowDidItGo()
    {
        // some really nasty untestable code
        return true;
    }
}</pre>

<p>The below example demonstrates simply verifying some behavior on the mocked dependencies of the system under test.</p>

<pre class="brush: csharp;">[TestFixture]
public class Example__how_to_pull_items_from_the_UnityAutoMockContainer_when_verifying_behavior_after_an_action_was_taken 
    : FixtureBase
{
    private TestComponent _testComponent;

    protected override void Before_all_tests()
    {
        base.Before_all_tests();
        _testComponent = AutoMockContainer.Resolve&lt;TestComponent&gt;();
    }

    protected override void Because()
    {
        _testComponent.RunAll();
    }

    [Test]
    public void Should_run_ServiceA_RunA()
    {
        AutoMockContainer
            .GetMock&lt;IServiceA&gt;()
            .Verify(v =&gt; v.RunA(), Times.Once());
    }

    [Test]
    public void Should_run_ServiceB_RunB()
    {
        AutoMockContainer
            .GetMock&lt;IServiceB&gt;()
            .Verify(v =&gt; v.RunB(), Times.Once());
    }
}</pre>

<p>Next, you may have noticed that the system under test had a complicated internal method (that may not necessarily be testable). You can use the AutoMocker to create the system under test as a Mock itself, so we can override some of the behavior. Here’s how you could quickly do that. </p>

<blockquote>
  <p><strong>Aside</strong>: I’m not saying this is a good practice or aids in good component design, just saying it’s possible</p>
</blockquote>

<pre class="brush: csharp;">[TestFixture]
public class Example__how_to_use_the_UnityAutoMockContainer_to_override_a_method_on_the_SystemUnderTest_to_test_a_certain_behavior
    : FixtureBase
{

    private TestComponent _testComponent;

    protected override void Before_all_tests()
    {
        base.Before_all_tests();
        var mockTestComponent = AutoMockContainer.GetMock&lt;TestComponent&gt;();

        mockTestComponent
            .Setup(s =&gt; s.HowDidItGo())
            .Returns(false);

        _testComponent = mockTestComponent.Object;
    }

    protected override void Because()
    {
        _testComponent.RunAll();
    }

    [Test]
    public void Should_run_ServiceA_RunA()
    {
        AutoMockContainer
            .GetMock&lt;IServiceA&gt;()
            .Verify(v =&gt; v.RunA(), Times.Never());
    }

    [Test]
    public void Should_run_ServiceB_RunB()
    {
        AutoMockContainer
            .GetMock&lt;IServiceB&gt;()
            .Verify(v =&gt; v.RunB(), Times.Never());
    }
}</pre>

<p>&#160;</p>

<p>It’s amazing how much redundant test setup code this little helper has saved me in my tests. I hope others can find some use with this as well.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/01/03/unitymoq-automocker-or-automockingcontainer/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Elegant Code &#187; Unit Testing</title>
	<atom:link href="http://elegantcode.com/category/unit-testing/feed/" rel="self" type="application/rss+xml" />
	<link>http://elegantcode.com</link>
	<description></description>
	<lastBuildDate>Tue, 15 May 2012 10:00:00 +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>AutoTest.NET</title>
		<link>http://elegantcode.com/2010/11/30/autotest-net/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=autotest-net</link>
		<comments>http://elegantcode.com/2010/11/30/autotest-net/#comments</comments>
		<pubDate>Tue, 30 Nov 2010 11:00:00 +0000</pubDate>
		<dc:creator>Jan Van Ryswyck</dc:creator>
				<category><![CDATA[TDD]]></category>
		<category><![CDATA[Tools and Utilities]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/11/30/autotest-net/</guid>
		<description><![CDATA[I just want to quickly point out a tool that I’ve been playing with for a couple of days now, named AutoTest.NET. Its an open-source tool that originates from a popular tool in the Ruby community called ZenTest, which basically runs all your valuable unit tests when you save your source files or when you [...]]]></description>
			<content:encoded><![CDATA[<p>I just want to quickly point out a tool that I’ve been playing with for a couple of days now, named <a href="https://github.com/acken/AutoTest.Net" target="_blank">AutoTest.NET</a>. Its an open-source tool that originates from a popular tool in the Ruby community called <a href="http://www.zenspider.com/ZSS/Products/ZenTest/" target="_blank">ZenTest</a>, which basically runs all your valuable unit tests when you save your source files or when you build your code. It enables you to get feedback about your changes as soon as possible.</p>  <p>The project started out a couple of years ago on <a href="http://code.google.com/p/autotestnet/" target="_blank">Google code</a> and was first initiated by <a href="http://averyblog.com/" target="_blank">James Avery</a>. Contribution stopped at some point until recently where <a href="http://ackenpacken.blogspot.com/" target="_blank">Svein Arne Ackenhausen</a> forked the source code and <a href="https://github.com/acken/AutoTest.Net" target="_blank">put it on GitHub</a>. Now it runs both for .NET as well as Mono, with NUnit, MSTest and xUnit as the currently supported unit test frameworks. </p>  <p>Here’s a screenshot from the feedback window when all tests pass:</p>  <p><a href="http://elegantcode.com/wp-content/uploads/2010/11/Success.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="Success" border="0" alt="Success" src="http://elegantcode.com/wp-content/uploads/2010/11/Success_thumb.png" width="540" height="189" /></a> </p>  <p>And here you can see the same window after I broke one of my unit tests:</p>  <p><a href="http://elegantcode.com/wp-content/uploads/2010/11/Failure.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="Failure" border="0" alt="Failure" src="http://elegantcode.com/wp-content/uploads/2010/11/Failure_thumb.png" width="538" height="319" /></a> </p>  <p>Here you can see which particular unit test has been broken and by clicking the specified link you end up at the right source file in Visual Studio. </p>  <p>I encourage you to pick up this small tool and learn how it can facilitate your TDD flow. Take a look at <a href="https://github.com/acken/AutoTest.Net/wiki/Get-started!" target="_blank">this page</a> in order to get up-and-running in no time. Also don’t forget to provide the owner(s) of this project with some feedback that you might have. Svein has been very helpful over the last week answering all my stupid questions and remarks (and the Nobel price for this year’s most patient person goes to … ;-) ). </p>  <p>I would definitely like to see this tool becoming more popular, so go check it out.&#160;&#160; </p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/11/30/autotest-net/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>If Self-Documenting Code is the What, Unit Tests are the Why</title>
		<link>http://elegantcode.com/2010/04/25/if-self-documenting-code-is-the-what-unit-tests-are-the-why/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=if-self-documenting-code-is-the-what-unit-tests-are-the-why</link>
		<comments>http://elegantcode.com/2010/04/25/if-self-documenting-code-is-the-what-unit-tests-are-the-why/#comments</comments>
		<pubDate>Sun, 25 Apr 2010 19:09:04 +0000</pubDate>
		<dc:creator>John Sonmez</dc:creator>
				<category><![CDATA[Agile]]></category>
		<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Craftsmanship]]></category>
		<category><![CDATA[Documentation]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/04/25/if-self-documenting-code-is-the-what-unit-tests-are-the-why/</guid>
		<description><![CDATA[It is not enough to just write code that is clean and self-documenting.  Eliminating comments and replacing them with clear variable and method names, will tell the reader of your code clearly what it is doing, but it will not properly express why it is doing it. If you recall from my original post on [...]]]></description>
			<content:encoded><![CDATA[It is not enough to just write code that is clean and self-documenting.  <a href="http://elegantcode.com/2010/04/18/eliminating-comments-the-road-to-clarity/">Eliminating comments</a> and replacing them with clear variable and method names, will tell the reader of your code clearly what it is doing, but it will not properly express why it is doing it.

If you recall from my <a href="http://elegantcode.com/2010/04/09/what-does-elegant-code-mean-to-me/">original post</a> on Elegant code, I stated that elegant code is:
<blockquote>Something that is simple yet effective, delivered with grace.</blockquote>
By writing self-documenting code we are hopefully able to achieve some of the aspects of simplicity and grace, but it tells us nothing about the effectiveness of the code.
<h2>Bringing the dead to life</h2>
<a href="http://elegantcode.com/wp-content/uploads/2010/04/zombies.jpg"><img style="border-right-width: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto" title="zombies" src="http://elegantcode.com/wp-content/uploads/2010/04/zombies_thumb.jpg" border="0" alt="zombies" width="441" height="295" /></a>

Throwing out comments is a debatable topic.  <a href="http://www.reddit.com/r/programming/comments/bsutx/">It raises quite a bit of controversy</a>, as you can see from some of the comments on my post about the subject.  The reason, perhaps, that so many people are so staunchly opposed to the idea, is because they are worried, and rightly so, that throwing out comments will reduce the documentation of what the code is doing.

Think about that for a second.  Is documentation of what the code is doing important?  It better be.  What we are trying to accomplish by writing self-documenting code instead of comments, is to take the vessel, which is the code itself, and make that same vessel be the documentation of what the code does.  It is by doing this that we creating a living representation of the functionality of the code.  Comments are akin to a dead representation of the functionality of the code because they do not change automatically with the code.

I diverge to talk about comments so that I can draw a parallel to another form of documentation which is valuable and should be considered necessary.  That other set of documentation is requirements.  Have you ever written requirements documents?  Have you ever captured requirements from the customer and put them into UML diagrams, or perhaps plopped them into some templated Word document, which is never updated again, and no one reads, because no one trusts it is correct?  Wouldn’t it be great if we would replace that dead document or set of documents, with a living one?

The good news is we can, and some of us have.  And I fully expect this recommendation will be just as controversial, because <strong>I am suggesting that we don’t have to write low level specifications of the system at all, instead we can write good unit tests. </strong>When we do this, we are taking a dead form of document and bringing it to life.
<h2>Unit tests tell us why and how our code is effective</h2>
If
<pre class="csharpcode">i = 5;  // Widget count defaults to five.</pre>
is replaced with
<pre class="csharpcode">widgetCount = DEFAULT_WIDGET_COUNT;</pre>
<!--.csharpcode, .csharpcode pre { 	font-size: small; 	color: black; 	font-family: consolas, "Courier New", courier, monospace; 	background-color: #ffffff; 	/*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt  { 	background-color: #f4f4f4; 	width: 100%; 	margin: 0em; } .csharpcode .lnum { color: #606060; } -->

then
<blockquote><span style="background-color: #ffffff;">1.1.5 When a new widget is created, the widget count should be increased by one.</span></blockquote>
is replaced with
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">void</span> When_NewWidgetIsCreated_Then_WidgetCountIsIncreasedByOne()
{
     WidgetFactory.Count = 3;
     WidgetFactory.CreateNew();
     assertEquals(4, WidgetFactory.Count);
}</pre>
The unit test is replacing the low level requirement, which is somewhat open to interpretation and untied to the code, with an absolute and completely tied-to-the-code, specific requirement.

The unit test is telling us why our code is built the way it is.  It is telling us what requirement that particular structure of code is trying to address.  <strong>It is telling us what end result that code is trying to accomplish and what the expectations are on the results of a given condition.</strong>

The unit test is telling us how the code is to be used in order to achieve its result.  It is serving as a living reference to the syntax and use of the code we built.  <strong>Instead of providing instructions on how to use our API, we are providing a living example, and proof that it will indeed work.</strong> Examples are often much more effective than instructions anyway.
<h2>What exactly are we replacing?</h2>
At this point we are not trying to replace all the documentation of the system (at this point).

With self-documenting code, we sought to eliminate comments, and replace them with good variable and method names.

With unit tests, we seek to eliminate technical documentation and requirements of the system, that is targeted at a developer or technical audience.

We are NOT trying to eliminate high level specifications of the system, or use cases. <strong>Unit tests DO NOT replace that kind of documentation! </strong>We will talk about replacing that kind of documentation when we talk about automated functional or system tests.

Simply put, any kind of documentation that you would give to a developer so they understand how the system works and how to use the code or APIs, can be easily replaced by writing good unit tests.

Our simple goal is to replace the “dead” documentation (meaning that it does not update automatically with the thing it is documenting), with “living” documentation in the form of unit tests.

One last point.  I want to be clear that I am not saying that having unit tests automatically results in the ability to replace technical documentation.  Just like having long-named methods and variables doesn’t automatically replace the need for comments.  It is a matter of the quality of the unit tests that are written, just as it is a matter of the quality of the self-documenting code.
<h5>As always, you can subscribe to this <a href="http://feeds2.feedburner.com/ElegantCode">RSS feed</a> to follow my posts on elegant code.  Feel free to check out my main personal blog at <a href="http://simpleprogrammer.com">http://simpleprogrammer.com</a>, which has a wider range of posts, updated 2-3 times a week.  Also, you can follow me on twitter <a href="http://twitter.com/jsonmez">here</a>.</h5>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/04/25/if-self-documenting-code-is-the-what-unit-tests-are-the-why/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Behaviors with MSpec</title>
		<link>http://elegantcode.com/2010/02/26/behaviors-with-mspec/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=behaviors-with-mspec</link>
		<comments>http://elegantcode.com/2010/02/26/behaviors-with-mspec/#comments</comments>
		<pubDate>Fri, 26 Feb 2010 23:33:28 +0000</pubDate>
		<dc:creator>Jan Van Ryswyck</dc:creator>
				<category><![CDATA[BDD]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/02/26/behaviors-with-mspec/</guid>
		<description><![CDATA[In my previous posts, I showed the syntax for context/specifications using Machine.Specifications (or MSpec for short) and how to use an auto mocking container in conjunction with this excellent Behavior-Driven Development (BDD) framework. For this post, I want to show you one of the nice features of MSpec called behaviors. Suppose we have to create [...]]]></description>
			<content:encoded><![CDATA[<p>In my previous posts, I showed the <a href="http://elegantcode.com/2010/02/19/getting-started-with-machine-specifications-mspec/">syntax for context/specifications</a> using <a href="http://github.com/machine/machine.specifications">Machine.Specifications</a> (or MSpec for short) and <a href="http://elegantcode.com/2010/02/23/mspec-and-auto-mocking">how to use an auto mocking container</a> in conjunction with this excellent Behavior-Driven Development (BDD) framework. For this post, I want to show you one of the nice features of MSpec called <em>behaviors</em>.</p>  <p>Suppose we have to create some sort of specification that validates the format of an e-mail address. We typically use some regular expression in order to ensure that a specified e-mail address is properly formatted.</p>  <pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">class</span> EmailSpecification
{
    <span class="kwrd">private</span> <span class="kwrd">const</span> String EmailRegexPattern = <span class="str">@&quot;.. SOME_REGEX_PATTERN ...&quot;</span>;

    <span class="kwrd">public</span> Boolean IsSatisfiedBy(String candidate)
    {
        var regex = <span class="kwrd">new</span> Regex(EmailRegexPattern);
        <span class="kwrd">return</span> regex.IsMatch(candidate);
    }
}</pre>
<style type="text/css">

.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>I guess this is pretty common and straightforward. One way to provide some unit tests for this particular piece of code is to check a whole number of e-mail addresses that either pass or fail the specification. The following example shows only a couple of scenarios:</p>

<pre class="csharpcode">[TestFixture]
<span class="kwrd">public</span> <span class="kwrd">class</span> When_validating_an_email
    : ContextSpecification&lt;EmailSpecification&gt;
{
    <span class="kwrd">protected</span> <span class="kwrd">override</span> EmailSpecification Create_subject_under_test()
    {
        <span class="kwrd">return</span> <span class="kwrd">new</span> EmailSpecification();
    }

    [Test]
    <span class="kwrd">public</span> <span class="kwrd">void</span> ShouldBeSatisfied()
    {
        Assert.That(SUT.IsSatisfiedBy(<span class="str">&quot;one2@three.com&quot;</span>));
        Assert.That(SUT.IsSatisfiedBy(<span class="str">&quot;one@two3.com&quot;</span>));
    }

    [Test]
    <span class="kwrd">public</span> <span class="kwrd">void</span> ShouldNotBeSatisfied()
    {
        Assert.That(SUT.IsSatisfiedBy(<span class="str">&quot;one_two.com&quot;</span>), Is.False);
        Assert.That(SUT.IsSatisfiedBy(<span class="str">&quot;one_two@&quot;</span>), Is.False);
    }
}</pre>
<style type="text/css">

.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>A slightly more concise approach for these kind of unit tests can be accomplished by utilizing a feature of any decent unit test framework called <em>row tests. </em>With this approach we can, at the very least, reduce the number of asserts we have to write for each unit test.<em>&#160;</em></p>

<pre class="csharpcode">[TestFixture]
<span class="kwrd">public</span> <span class="kwrd">class</span> When_validating_an_email__approach_2
    : ContextSpecification&lt;EmailSpecification&gt;
{
    <span class="kwrd">protected</span> <span class="kwrd">override</span> EmailSpecification Create_subject_under_test()
    {
        <span class="kwrd">return</span> <span class="kwrd">new</span> EmailSpecification();
    }

    [RowTest]
    [Row(<span class="str">&quot;one2@three.com&quot;</span>)]
    [Row(<span class="str">&quot;one@two3.com&quot;</span>)]
    <span class="kwrd">public</span> <span class="kwrd">void</span> ShouldBeSatisfied(String email)
    {
        Assert.That(SUT.IsSatisfiedBy(email));
    }

    [RowTest]
    [Row(<span class="str">&quot;one_two.com&quot;</span>)]
    [Row(<span class="str">&quot;one_two@&quot;</span>)]
    <span class="kwrd">public</span> <span class="kwrd">void</span> ShouldNotBeSatisfied(String email)
    {
        Assert.That(SUT.IsSatisfiedBy(email), Is.False);
    }
}</pre>
<style type="text/css">

.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>Notice that I explicitly called both of these approaches <em>unit tests</em> as they don’t have much to do with BDD in my opinion. I’m not saying that using regular unit tests is a bad thing, but with&#160; behavior-driven development context is king. So these unit tests are perfect examples of ‘<a href="http://elegantcode.com/2008/12/30/dont-sell-out-on-the-context-dude/">context betrayal</a>’ when following the BDD approach. </p>

<p>Lets see what MSpec can bring to the table for these kind of scenarios:</p>

<pre class="csharpcode">[Subject(<span class="kwrd">typeof</span>(EmailSpecification), <span class="str">&quot;is satisfied&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_validating_an_email_address_with_a_number_in_the_local_part
    : email_specification_specs
{
    Establish context = () =&gt;
        EmailAddress = <span class="str">&quot;one2@three.com&quot;</span>;

    Behaves_like&lt;SatisfiedSpecificationBehavior&gt; a_satisfied_specification;
}

[Subject(<span class="kwrd">typeof</span>(EmailSpecification), <span class="str">&quot;is satisfied&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_validating_an_email_address_with_a_number_in_the_domain_name
    : email_specification_specs
{
    Establish context = () =&gt;
        EmailAddress = <span class="str">&quot;one@two3.com&quot;</span>;

    Behaves_like&lt;SatisfiedSpecificationBehavior&gt; a_satisfied_specification;
}

[Subject(<span class="kwrd">typeof</span>(EmailSpecification), <span class="str">&quot;is satisfied&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_validating_an_email_address_without_an_At_sign
    : email_specification_specs
{
    Establish context = () =&gt;
        EmailAddress = <span class="str">&quot;one_two.com&quot;</span>;

    Behaves_like&lt;UnsatisfiedSpecificationBehavior&gt; an_unsatisfied_specification;
}

[Subject(<span class="kwrd">typeof</span>(EmailSpecification), <span class="str">&quot;is satisfied&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_validating_an_email_address_without_a_domain
    : email_specification_specs
{
    Establish context = () =&gt;
        EmailAddress = <span class="str">&quot;one_two@&quot;</span>;

    Behaves_like&lt;UnsatisfiedSpecificationBehavior&gt; an_unsatisfied_specification;
}</pre>
<style type="text/css">

.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>In order to escape ‘context betrayal’, we’ve split up every context into a separate context/specification. In order to reduce the amount of effort caused by duplicate code, we stripped the context setup to the bare minimum (just a particular e-mail address in this case). The observations are isolated into MSpec behaviors which provides a very readable description of their outcome. Lets take a look at what is needed in order to get these <em>behaviors</em> to work.</p>

<p>But first lets take at look at the abstract base class that we’ve used for the context/specifications we’ve just shown.</p>

<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">abstract</span> <span class="kwrd">class</span> email_specification_specs
{
    Establish context = () =&gt;
    {
        SUT = <span class="kwrd">new</span> EmailSpecification();
    };

    Because of = () =&gt;
        Result = SUT.IsSatisfiedBy(EmailAddress);

    <span class="kwrd">protected</span> <span class="kwrd">static</span> Boolean Result;
    <span class="kwrd">protected</span> <span class="kwrd">static</span> String EmailAddress { get; set; }
    <span class="kwrd">protected</span> <span class="kwrd">static</span> EmailSpecification SUT { get; set; }
}</pre>

<p><style type="text/css">

.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style></p>

<p>&#160;</p>

<p>We abstracted as much as possible into this base class in order to remove duplication in the context/specifications. The creation of the subject-under-test and the calling of its <em>IsSatisfiedBy</em> method, but the important one is the declaration of the <em>Result</em> field. This field contains the outcome of the <em>IsSatisfiedBy</em> method. Finally, lets have a look at the behaviors themselves:</p>

<pre class="csharpcode">[Behaviors]
<span class="kwrd">public</span> <span class="kwrd">class</span> SatisfiedSpecificationBehavior
{
    <span class="kwrd">protected</span> <span class="kwrd">static</span> Boolean Result;
    
    It should_satisfy_the_specification = () =&gt;
        Result.ShouldBeTrue();
}

[Behaviors]
<span class="kwrd">public</span> <span class="kwrd">class</span> UnsatisfiedSpecificationBehavior
{
    <span class="kwrd">protected</span> <span class="kwrd">static</span> Boolean Result;

    It should_not_satisfy_the_specification = () =&gt;
        Result.ShouldBeFalse();
}</pre>
<style type="text/css">

.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>In order to create an MSpec behavior, we just have to create a separate class that we decorate with the <em>Behaviors</em> attribute. Also notice that we have the same declaration of the <em>Result</em> field. MSpec ensures that this field gets initialized with the value of the other <em>Result</em> field that is set in the base class of the context/specifications. Note that you don’t necessarily need to put this field in a base class. You can have that field in every context/specification if you’d like (not sure why) as long as the names match with the fields used in the defined behaviors.</p>

<p>I personally like the way how the MSpec contributors tried to solve testing the same logic with different input patterns and the syntax they provided to back this up.&#160;&#160; </p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/02/26/behaviors-with-mspec/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>MSpec and Auto Mocking</title>
		<link>http://elegantcode.com/2010/02/23/mspec-and-auto-mocking/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=mspec-and-auto-mocking</link>
		<comments>http://elegantcode.com/2010/02/23/mspec-and-auto-mocking/#comments</comments>
		<pubDate>Tue, 23 Feb 2010 20:38:54 +0000</pubDate>
		<dc:creator>Jan Van Ryswyck</dc:creator>
				<category><![CDATA[BDD]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/02/23/mspec-and-auto-mocking/</guid>
		<description><![CDATA[In my previous post, I explained how to get started with Machine.Specifications (or MSpec for short) and showed you how the syntax for context/specifications looks like when using this BDD framework. For this post, I want to show you how to use an auto mocking container (we’ll be using the one provided by StructureMap off [...]]]></description>
			<content:encoded><![CDATA[<p>In my <a href="http://elegantcode.com/2010/02/19/getting-started-with-machine-specifications-mspec/">previous post</a>, I explained how to get started with <a href="http://github.com/machine/machine.specifications">Machine.Specifications</a> (or MSpec for short) and showed you how the syntax for context/specifications looks like when using this BDD framework. For this post, I want to show you how to use an <a href="http://vanryswyckjan.blogspot.com/2008/01/automocking-container.html">auto mocking container</a> (we’ll be using the one provided by StructureMap off course).</p>  <p>We’ll use the same example as the one used in the previous post, but now we’ll deal with the message handler that makes a particular customer preferred.</p> <style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>  <pre class="csharpcode"><span class="rem">//</span>
<span class="rem">// Subject under test</span>
<span class="rem">//</span>
<span class="kwrd">public</span> <span class="kwrd">class</span> MakeCustomerPreferredMessageHandler
{
    <span class="kwrd">private</span> <span class="kwrd">readonly</span> ICustomerRepository&lt;ICanMakeCustomerPreferred&gt; _repository;

    <span class="kwrd">public</span> MakeCustomerPreferredMessageHandler(
        ICustomerRepository&lt;ICanMakeCustomerPreferred&gt; repository)
    {
        _repository = repository;
    }

    <span class="kwrd">public</span> <span class="kwrd">void</span> Handle(MakeCustomerPreferredMessage message)
    {
        var customer = _repository.Get(message.CustomerId);
        <span class="kwrd">if</span>(<span class="kwrd">null</span> == customer)
            <span class="kwrd">throw</span> <span class="kwrd">new</span> InvalidOperationException(
                <span class="str">&quot;No customer for specified identifier&quot;</span>);
        
        customer.MakePreferred();
        _repository.Save(customer);
    }
}</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>The <em>Customer</em> class implements a ‘<a href="http://martinfowler.com/bliki/RoleInterface.html">role interface’</a> called <em>ICanMakeCustomerPreferred</em>. We retrieve a customer from the repository and make it preferred. We throw an exception in case the customer cannot be found in the data store.</p>

<p>Here are the context/specifications for this easy example:</p>

<pre class="csharpcode">[Subject(<span class="str">&quot;Making a customer preferred&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_making_a_customer_preferred
    : context_specification&lt;MakeCustomerPreferredMessageHandler&gt;
{
    Establish context = () =&gt;
    {
        _message = <span class="kwrd">new</span> MakeCustomerPreferredMessage { CustomerId = 6412 };

        Repository.Stub(repository =&gt; repository.Get(_message.CustomerId))
            .Return(Customer);
    };

    Because of = () =&gt; 
        SUT.Handle(_message);
    
    It should_mark_the_customer_as_preferred = () =&gt;
        Customer.AssertWasCalled(customer =&gt; customer.MakePreferred());

    It should_save_the_customer_in_the_repository = () =&gt;
        Repository.AssertWasCalled(repository =&gt; repository.Save(Customer));

    <span class="kwrd">private</span> <span class="kwrd">static</span> ICanMakeCustomerPreferred Customer
    {
        get { <span class="kwrd">return</span> Dependency&lt;ICanMakeCustomerPreferred&gt;(); }
    }

    <span class="kwrd">private</span> <span class="kwrd">static</span> ICustomerRepository&lt;ICanMakeCustomerPreferred&gt; Repository
    {
        get { <span class="kwrd">return</span> Dependency&lt;ICustomerRepository&lt;ICanMakeCustomerPreferred&gt;&gt;(); }
    }

    <span class="kwrd">private</span> <span class="kwrd">static</span> MakeCustomerPreferredMessage _message;
}

[Subject(<span class="str">&quot;Making a customer preferred&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_making_an_unexisting_customer_preferred
    : context_specification&lt;MakeCustomerPreferredMessageHandler&gt;
{
    Establish context = () =&gt;   
    {
        _message = <span class="kwrd">new</span> MakeCustomerPreferredMessage() { CustomerId = 61544 };

        Dependency&lt;ICustomerRepository&lt;ICanMakeCustomerPreferred&gt;&gt;()
            .Stub(repository =&gt; repository.Get(_message.CustomerId))
            .Return(<span class="kwrd">null</span>);
    };

    Because of = () =&gt;
        _resultingException = Catch.Exception(() =&gt; SUT.Handle(_message));

    It should_result_in_an_error = () =&gt;
        _resultingException.ShouldBeOfType&lt;InvalidOperationException&gt;();

    <span class="kwrd">private</span> <span class="kwrd">static</span> MakeCustomerPreferredMessage _message;
    <span class="kwrd">private</span> <span class="kwrd">static</span> Exception _resultingException;
}</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>I want to point out that all fields and properties are made static. This is needed so that the anonymous methods can access them. I’m also using a base class for these specifications which I’ll show next. This base class uses an auto mocking container for providing the requested mocks and stubs through the <em>Dependency</em> and <em>Stub</em> methods. </p>

<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">abstract</span> <span class="kwrd">class</span> context_specification&lt;TSubjectUnderTest&gt;
    <span class="kwrd">where</span> TSubjectUnderTest : <span class="kwrd">class</span>
{
    <span class="kwrd">private</span> <span class="kwrd">static</span> IAutoMockingContainer&lt;TSubjectUnderTest&gt; _autoMockingContainer;
    <span class="kwrd">protected</span> <span class="kwrd">static</span> TSubjectUnderTest SUT { get; set; }

    Establish context = () =&gt;
    {
        _autoMockingContainer = <span class="kwrd">new</span> StructureMapAMC&lt;TSubjectUnderTest&gt;();
        SUT = _autoMockingContainer.Create();     
    };
    
    Cleanup stuff = () =&gt; 
    {
        SUT = <span class="kwrd">null</span>;
        _autoMockingContainer = <span class="kwrd">null</span>;
    };

    <span class="kwrd">protected</span> <span class="kwrd">static</span> TDependency Dependency&lt;TDependency&gt;()
        <span class="kwrd">where</span> TDependency : <span class="kwrd">class</span>
    {
        <span class="kwrd">return</span> _autoMockingContainer.GetMock&lt;TDependency&gt;();
    }

    <span class="kwrd">protected</span> <span class="kwrd">static</span> TStub Stub&lt;TStub&gt;()
        <span class="kwrd">where</span> TStub : <span class="kwrd">class</span>
    {
        <span class="kwrd">return</span> _autoMockingContainer.GetStub&lt;TStub&gt;();
    }
}

<span class="kwrd">public</span> <span class="kwrd">interface</span> IAutoMockingContainer&lt;TSubject&gt;
    <span class="kwrd">where</span> TSubject : <span class="kwrd">class</span>
{
    TSubject Create();
    TMock GetMock&lt;TMock&gt;() <span class="kwrd">where</span> TMock : <span class="kwrd">class</span>;
    TStub GetStub&lt;TStub&gt;() <span class="kwrd">where</span> TStub : <span class="kwrd">class</span>;
}

<span class="kwrd">public</span> <span class="kwrd">class</span> StructureMapAMC&lt;TSubject&gt; 
    : IAutoMockingContainer&lt;TSubject&gt;
    <span class="kwrd">where</span> TSubject : <span class="kwrd">class</span>
{
    <span class="kwrd">private</span> <span class="kwrd">readonly</span> RhinoAutoMocker&lt;TSubject&gt; _rhinoAutoMocker;

    <span class="kwrd">public</span> StructureMapAMC()
    {
        _rhinoAutoMocker = 
            <span class="kwrd">new</span> RhinoAutoMocker&lt;TSubject&gt;(MockMode.AAA);
    }

    <span class="kwrd">public</span> TSubject Create()
    {
        <span class="kwrd">return</span> _rhinoAutoMocker.ClassUnderTest;
    }

    <span class="kwrd">public</span> TMock GetMock&lt;TMock&gt;() 
        <span class="kwrd">where</span> TMock : <span class="kwrd">class</span>
    {
        <span class="kwrd">return</span> GetDependency&lt;TMock&gt;();
    }

    <span class="kwrd">public</span> TStub GetStub&lt;TStub&gt;() 
        <span class="kwrd">where</span> TStub : <span class="kwrd">class</span>
    {
        <span class="kwrd">return</span> GetDependency&lt;TStub&gt;();
    }

    <span class="kwrd">private</span> TDependency GetDependency&lt;TDependency&gt;() 
        <span class="kwrd">where</span> TDependency : <span class="kwrd">class</span>
    {
        <span class="kwrd">return</span> _rhinoAutoMocker.Get&lt;TDependency&gt;();
    }
}</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>Notice that I’m using the <em>Establish</em> and <em>Cleanup</em> delegates in the <em>context_specification</em> base class. This doesn’t prevent that these can be used again in derived context/specifications. MSpec ensures that the anonymous methods are called in the right order. This means that the <em>Establish</em> method of the base class is called before the <em>Establish</em> method of the derived context/specifications.&#160;&#160;&#160;&#160; </p>

<p>Absolutely no rocket science here, but I figured it might come in handy when you need it. For the next post I’ll try to demonstrate how to deal with reusable behaviors.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/02/23/mspec-and-auto-mocking/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Getting Started With Machine.Specifications (MSpec)</title>
		<link>http://elegantcode.com/2010/02/19/getting-started-with-machine-specifications-mspec/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=getting-started-with-machine-specifications-mspec</link>
		<comments>http://elegantcode.com/2010/02/19/getting-started-with-machine-specifications-mspec/#comments</comments>
		<pubDate>Fri, 19 Feb 2010 21:34:17 +0000</pubDate>
		<dc:creator>Jan Van Ryswyck</dc:creator>
				<category><![CDATA[BDD]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/02/19/getting-started-with-machine-specifications-mspec/</guid>
		<description><![CDATA[Its been a while since I evaluated and evolved my approach to BDD. The way I’ve been doing BDD up until now is described in this blog post which goes way back to 2008. Everyone has kind of their own style nowadays. Below you can find the code of two context/specifications for a method named [...]]]></description>
			<content:encoded><![CDATA[<p>Its been a while since I evaluated and evolved my approach to BDD. The way I’ve been doing BDD up until now is described in <a href="http://elegantcode.com/2008/10/25/refining-contextspecification-bdd-using-rhino-mocks-35/">this blog post</a> which goes way back to 2008. Everyone has kind of their own style nowadays. Below you can find the code of two context/specifications for a method named <em>MakePreferred</em> on a <em>Customer </em>class. This simple example clarifies the style that I’ve been following up until now.</p> <style type="text/css">


.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style><style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>  <pre class="csharpcode">[TestFixture]
<span class="kwrd">public</span> <span class="kwrd">class</span> When_making_a_regular_customer_preferred
    : ContextSpecification&lt;Customer&gt;
{
    <span class="kwrd">protected</span> <span class="kwrd">override</span> Customer Create_subject_under_test()
    {
        <span class="kwrd">return</span> <span class="kwrd">new</span> Customer(<span class="kwrd">new</span>[] { _order });
    }

    <span class="kwrd">protected</span> <span class="kwrd">override</span> <span class="kwrd">void</span> Establish_context()
    {
        _order = <span class="kwrd">new</span> Order(<span class="kwrd">new</span>[] { <span class="kwrd">new</span> OrderItem(12), 
                                   <span class="kwrd">new</span> OrderItem(16) });
                                   
        _totalAmountWithoutDiscount = _order.TotalAmount;
    }

    <span class="kwrd">protected</span> <span class="kwrd">override</span> <span class="kwrd">void</span> Because()
    {
        SUT.MakePreferred();
    }

    [Test]
    <span class="kwrd">public</span> <span class="kwrd">void</span> Then_the_customer_should_be_marked_as_preferred()
    {
        SUT.IsPreferred.ShouldBeTrue();
    }

    [Test]
    <span class="kwrd">public</span> <span class="kwrd">void</span> Then_a_ten_percent_discount_should_be_applied_to_all_outstanding_orders()
    {
        _order.TotalAmount.ShouldBeEqualTo(
            _totalAmountWithoutDiscount * 0.9);
    }

    <span class="kwrd">private</span> Order _order;
    <span class="kwrd">private</span> Double _totalAmountWithoutDiscount;
}

[TestFixture]
<span class="kwrd">public</span> <span class="kwrd">class</span> When_making_a_preferred_customer_preferred
    : ContextSpecification&lt;Customer&gt;
{
    <span class="kwrd">protected</span> <span class="kwrd">override</span> Customer Create_subject_under_test()
    {
        var customer = <span class="kwrd">new</span> Customer(<span class="kwrd">new</span>[] { _order });
        customer.MakePreferred();
        <span class="kwrd">return</span> customer;
    }

    <span class="kwrd">protected</span> <span class="kwrd">override</span> <span class="kwrd">void</span> Establish_context()
    {
        _order = <span class="kwrd">new</span> Order(<span class="kwrd">new</span>[] { <span class="kwrd">new</span> OrderItem(12), 
                                   <span class="kwrd">new</span> OrderItem(16) });
        _totalAmountWithoutDiscount = _order.TotalAmount;
    }

    <span class="kwrd">protected</span> <span class="kwrd">override</span> <span class="kwrd">void</span> Because()
    {
        SUT.MakePreferred();
    }

    [Test]
    <span class="kwrd">public</span> <span class="kwrd">void</span> Then_no_additional_discount_should_be_applied_to_the_outstanding_orders()
    {
        _order.TotalAmount.ShouldNotBeEqualTo(
            _totalAmountWithoutDiscount * 0.81);
    }

    <span class="kwrd">private</span> Order _order;
    <span class="kwrd">private</span> Double _totalAmountWithoutDiscount;
}

<span class="rem">//</span>
<span class="rem">// Subject under test</span>
<span class="rem">//</span>
<span class="kwrd">public</span> <span class="kwrd">class</span> Customer
{
    <span class="kwrd">private</span> <span class="kwrd">readonly</span> List&lt;Order&gt; _orders;
    <span class="kwrd">public</span> Boolean IsPreferred { get; <span class="kwrd">private</span> set; }

    <span class="kwrd">public</span> Customer(IEnumerable&lt;Order&gt; orders)
    {
        _orders = <span class="kwrd">new</span> List&lt;Order&gt;(orders);
    }

    <span class="kwrd">public</span> <span class="kwrd">void</span> MakePreferred()
    {
        <span class="kwrd">if</span>(IsPreferred)    
            <span class="kwrd">return</span>;
    
        IsPreferred = <span class="kwrd">true</span>;
        _orders.ForEach(order =&gt; order.ApplyDiscount(10));
    }
}</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>The bottom line of this example is that preferred customers get a 10 percent discount. Customers that are already preferred do not get an additional discount or otherwise we’re out of business ;-). </p>

<p>I’ve been pretty happy with this approach so far, although sometimes there were some quirks associated with this. So it was time for me to look beyond the horizon again, trying to look for ways to improve. </p>

<p><a href="http://github.com/machine/machine.specifications">Machine.Specifications</a> or MSpec for short is something that has been on my ‘cool-things-to-learn-list’ for quite some time now. As you will see later in this post, the syntax is a bit different as one would come to expect from a context/specification framework that targets the C# programming language. Its seems to be heavily inspired by Scott Bellware’s <a href="http://code.google.com/p/specunit-net/">SpecUnit framework</a> and <a href="http://rspec.info/">RSpec</a>.</p>

<p>Lets see how to set things up first. </p>

<p>The most obvious starting point is downloading the bits and bytes. You can grab the <a href="http://github.com/machine/machine.specifications">source code</a> from GitHub and build it or you can wuss out like I did and get the latest build from the <a href="http://teamcity.codebetter.com/login.html">TeamCity.CodeBetter.com</a> builder server (you can log on as a guest and search the artifacts for a latest build).&#160; </p>

<p>When you’re heavily addicted to <a href="http://www.testdriven.net/">TestDriven.NET</a> like I am, then its possible to keep using this wonderful Visual Studio add-in for running MSpec context/specifications. Just create a directory named <em>Machine.Specifications</em> in {$Program_Files}\TestDriven.NET 2.0 and copy the following files:</p>

<ul>
  <li>Machine.Specifications.dll</li>

  <li>Machine.Specifications.TDNetRunner.dll</li>

  <li>InstallTDNetRunner.bat</li>
</ul>

<ul>Run the InstallTDNetRunner.bat file and you’re able to run all MSpec context/specifications using TestDriven.NET.</ul>

<p>I also strongly encourage you to install the plugin for the Resharper test runner (if only to prevent some Resharper warnings later on). First step is to add a directory named <em>Plugins</em> to the <em>Bin</em> directory of Resharper ({$Program_Files}\JetBrains\ReSharper\v4.5\Bin\). Then create a directory named <em>Machine.Specifications</em> in the <em>Plugins</em> directory you just created and copy the following files:</p>

<ul>
  <li>Machine.Specifications.dll</li>

  <li>Machine.Specifications.ReSharperRunner.4.5.dll</li>

  <li>InstallResharperRunner.4.5.bat</li>
</ul>

<p>Run the InstallResharperRunner.4.5.bat file and you’re also able to run MSpec context/specifications using the Resharper test runner.</p>

<p>I’m not going to put this off any longer. Lets look at the code of the context/specifications shown earlier but completely revamped using the MSpec syntax:</p>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<pre class="csharpcode">[Subject(<span class="str">&quot;Making a customer preferred&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_a_regular_customer_is_made_preferred 
{
    Establish context = () =&gt;
    {
        _order = <span class="kwrd">new</span> Order(<span class="kwrd">new</span>[] { <span class="kwrd">new</span> OrderItem(12), 
                                   <span class="kwrd">new</span> OrderItem(16) });
        _totalAmountWithoutDiscount = _order.TotalAmount;

        SUT = <span class="kwrd">new</span> Customer(<span class="kwrd">new</span>[] { _order });
    };

    Because of = () =&gt; 
        SUT.MakePreferred();

    It should_mark_the_customer_as_preferred = () =&gt;
        SUT.IsPreferred.ShouldBeTrue();
        
    It should_apply_a_ten_percent_discount_to_all_outstanding_orders = () =&gt;
        _order.TotalAmount.ShouldEqual(_totalAmountWithoutDiscount * 0.9);      

    <span class="kwrd">private</span> <span class="kwrd">static</span> Customer SUT;
    
    <span class="kwrd">private</span> <span class="kwrd">static</span> Order _order;
    <span class="kwrd">private</span> <span class="kwrd">static</span> Double _totalAmountWithoutDiscount;
}

[Subject(<span class="str">&quot;Making a customer preferred&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_a_preferred_customer_is_made_preferred
{
    Establish context = () =&gt;
    {
        _order = <span class="kwrd">new</span> Order(<span class="kwrd">new</span>[] { <span class="kwrd">new</span> OrderItem(12), 
                                   <span class="kwrd">new</span> OrderItem(16) });
        _totalAmountWithoutDiscount = _order.TotalAmount;

        SUT = <span class="kwrd">new</span> Customer(<span class="kwrd">new</span>[] { _order });
        SUT.MakePreferred();
    };

    Because of = () =&gt;
        SUT.MakePreferred();

    It should_apply_no_additional_discount_to_the_outstanding_orders = () =&gt; 
        _order.TotalAmount.ShouldNotEqual(_totalAmountWithoutDiscount * 0.81);

    <span class="kwrd">private</span> <span class="kwrd">static</span> Customer SUT;

    <span class="kwrd">private</span> <span class="kwrd">static</span> Order _order;
    <span class="kwrd">private</span> <span class="kwrd">static</span> Double _totalAmountWithoutDiscount;
}</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>I warned you about the syntax, didn’t I :-). It only took me a couple of seconds to get used to this syntax but now I’m completely hooked. Instead of using methods and attributes, MSpec utilizes delegates and anonymous methods. But there’s more. </p>

<p>When using <a href="http://www.nunit.com/index.php">NUnit</a> for writing context/ specifications, the <em>Establish_context</em> and <em>Because</em> methods of the example shown earlier is executed before every observation (test). With MSpec, the <em>Establish</em> and <em>Because</em> anonymous methods are executed only once for every context no matter how many observations a particular context class contains. Big difference? Well, at first glance not but on second hand it does make <a href="http://elegantcode.com/2008/12/30/dont-sell-out-on-the-context-dude/">selling out on the context</a> a bit more difficult as it will probably blow up in your face sooner than later. You can force MSpec to execute the <em>Establish</em> and <em>Because</em> anonymous methods before every observation by applying the <em>SetupForEachSpecification</em> attribute to the context class, but I strongly encourage you to stay away from that unless absolutely needed.</p>

<p>Also notice that the fields in the contexts are now all static. This is needed so that the anonymous methods can access those.&#160;&#160;&#160;&#160;&#160; </p>

<p>Running these context/specifications using TestDriven.NET yields the following output in the output window of Visual Studio:</p>

<blockquote>
  <p><font face="Arial">Making a customer preferred, when a regular customer is made preferred
      <br />» should mark the customer as preferred

      <br />» should apply a ten percent discount to all outstanding orders</font></p>

  <p><font face="Arial">Making a customer preferred, when a preferred customer is made preferred
      <br />» should apply no additional discount to the outstanding orders</font></p>
</blockquote>

<p>What’s not to like? Well, the only downside so far is that Resharper was giving me some warnings about classes and fields not being used etc. … . Many of those warnings disappeared by registering the MSpec plugin for the Resharper test runner as I explained earlier.</p>

<p>So far, so good. I’ve got two more posts coming up on MSpec, so stay tuned.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/02/19/getting-started-with-machine-specifications-mspec/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Unity/Moq &#8211; AutoMocker or AutoMockingContainer</title>
		<link>http://elegantcode.com/2010/01/03/unitymoq-automocker-or-automockingcontainer/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=unitymoq-automocker-or-automockingcontainer</link>
		<comments>http://elegantcode.com/2010/01/03/unitymoq-automocker-or-automockingcontainer/#comments</comments>
		<pubDate>Sun, 03 Jan 2010 16:52:33 +0000</pubDate>
		<dc:creator>Jason Jarrett</dc:creator>
				<category><![CDATA[TDD]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Tools and Utilities]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/01/03/unitymoq-automocker-or-automockingcontainer/</guid>
		<description><![CDATA[What is an Auto Mocking Container? This post started to get a little long, so I won’t re-explain the concept. Joshua Flanagan wrote a nice overview at his Los Techies blog: Auto mocking Explained. My post is mainly here to describe the Unity version of an automocking container I threw together. In Jan 2009 I [...]]]></description>
			<content:encoded><![CDATA[<h4>What is an Auto Mocking Container?</h4>  <p>This post started to get a little long, so I won’t re-explain the concept.</p>  <p><a href="http://www.lostechies.com/blogs/joshuaflanagan/default.aspx">Joshua Flanagan</a> wrote a nice overview at his <a href="http://www.lostechies.com/">Los Techies</a> blog: <a href="http://www.lostechies.com/blogs/joshuaflanagan/archive/2009/02/03/auto-mocking-explained.aspx"><strong>Auto mocking Explained</strong></a>.</p>  <p>My post is mainly here to describe the Unity version of an automocking container I threw together.</p>  <h4>In Jan 2009 I blogged about my initial version of the Unity AutoMocker - Why am I blogging about it again?</h4>  <p>I originally wrote the AutoMocker for the Unity container a year ago (Jan 2009, in Silverlight), and finally got around to placing the code up in the <a href="http://code.google.com/p/moq-contrib/">moq-contrib</a> project in June of 2009.</p>  <p>I’m writing another post today in hopes to:</p>  <ol>   <li>Get some feedback on how this little snippet of code should continue. </li>    <li>Give a little more how-to/example code </li>    <li>Describe some updates I made since I originally created it.&#160; </li> </ol>  <h4>Where can I get it?</h4>  <p><strong>This is one part where I’d appreciate some feedback.</strong></p>  <p>I have two slightly different versions out there (currently).</p>  <p>I have one version at the <a href="http://code.google.com/p/elegantcode/source/browse/#svn/trunk/Coders/JasonJarrett/UnityAutoMocker">ElegantCode</a> repository where I was working on it, and the other I threw up at <a href="http://code.google.com/p/moq-contrib/">moq-contrib</a>.</p>  <p>The core of the UnityAutoMockContainer is the same in both places, it’s how the tests are separated out that differ.</p>  <p>In the <a href="http://code.google.com/p/elegantcode/source/browse/#svn/trunk/Coders/JasonJarrett/UnityAutoMocker">ElegantCode repository</a> it’s an all in one self contained single file (that you can copy into your own test project(s)). You can then setup a single test in your own testing framework that runs all internal automocker tests (in case you need to modify it yourself, and don’t want to break any existing functionality). EX: test</p>  <pre class="brush: csharp;">[Test]
public void Should_run_all_UnityAutoMockContainer_internal_tests()
{
    Moq.AutoMocking.SelfTesting.UnityAutoMockContainerFixture
        .RunAllTests(Console.WriteLine);
}</pre>

<p>I kind of like this format as it makes it easy to port between test libraries. Can’t say I like having the tests in the same file as the core, but it certainly is not a large chunk of code (so far) so it’s relatively small to maintain and definitely easier to manage as a single .cs file than another assembly (which would have to be version dependent on both Unity and Moq).</p>

<p>The <a href="http://code.google.com/p/moq-contrib/">moq-contrib</a> is definitely where I think this helper should end up (and it is there). I just happened to break the tests out into the Silverlight test project and the core is alone in a file. </p>

<p>It’s current state isn’t as easy to copy to a test library (Silverlight/Desktop/Unity 1.2/Unity 2.0) as the one at <a href="http://elegantcode.com/">ElegantCode</a>. <strong>What does anyone think?</strong> Should I put them all together in one file?</p>

<p>However it ends up (1. all in one file or two (1 test) (1 core)) it will continue to be maintained on the <a href="http://code.google.com/p/moq-contrib/">moq-contrib</a> project.</p>

<h4>What is the high level API of the container?</h4>

<p>It’s pretty simple, (currently) there are four methods on the container.</p>

<p><strong>Two for registering items with the container</strong>. Say you want to register an already created instance, or say you want to map an interface to a concrete class and _not_ have the container generate mocks automatically for special cases. </p>

<p>And <strong>two for pulling items out of the container</strong>. Whether you want a instance of T or a Mock&lt;T&gt;, it gives you ways to retrieve both.</p>

<blockquote>
  <p><a href="http://elegantcode.com/wp-content/uploads/2010/01/image.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://elegantcode.com/wp-content/uploads/2010/01/image_thumb.png" width="396" height="106" /></a> </p>
</blockquote>

<h4>How can I setup my own registrations with the container? </h4>

<p>Say I don’t want to have the container generate mocks for specific items and I want to supply specific configuration to the UnityContainer.</p>

<blockquote>
  <p>public UnityAutoMockContainer RegisterInstance&lt;TService&gt;(TService instance)</p>

  <p>public UnityAutoMockContainer Register&lt;TService, TImplementation&gt;() 
    <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; where TImplementation : TService</p>
</blockquote>

<p><strong>Note</strong>: both of these registration methods return the container itself so you can fluently stack registration. <strong>EX:</strong></p>

<pre class="brush: csharp;">AutoMockContainer
    .Register&lt;IServiceA, ServiceA&gt;()
    .Register&lt;IServiceB, ServiceB&gt;();</pre>

<p><strong>Let me know</strong>: I haven’t tested or played around with how this automocking container deals with any container specific xml configuration… So although I don’t think you should probably have that in a test assembly (stuff happens). Let me know if there are any issues.</p>

<h4>How do I get items out of the container?</h4>

<p>First is the Resolve&lt;T&gt;(). It will pull an item T out of the container. (Creating it if not already existing)</p>

<blockquote>
  <p>public T Resolve&lt;T&gt;()</p>
</blockquote>

<p>When T is an interface Resolve&lt;T&gt; (unless you setup registration specifically with the container) should return basically “(new Mock&lt;T&gt;()).Object”</p>

<p>When T is a concrete Class, the container should return an instance of T and any of it’s dependencies will be satisfied by mocks. (Note that T will not be any sort of mocked instance of T, unless you used the GetMock&lt;T&gt; as described below first)</p>

<blockquote>
  <p>public Mock&lt;T&gt; GetMock&lt;T&gt;() where T : class</p>
</blockquote>

<p>When T is an interface GetMock&lt;T&gt; should return basically “(new Mock&lt;T&gt;())” </p>

<p>When T is a concrete Class, the container should return a new Mock&lt;T&gt;() and any of it’s dependencies will be satisfied by mocks.</p>

<h4>How do I use the UnityAutoMockContainer?</h4>

<p>It’s pretty basic, you first create an instance of the UnityAutoMockContainer, and from there you can ask it for mocks of an (Interface, Class, or Abstract Class).</p>

<p>If you request an instance of a concrete class, or abstract class, the UnityAutoMockContainer will stuff mocks in for any constructor dependencies of your concrete class (if it can). You can then request from the container those same dependencies one at a time and either apply mocking setups or verifications.</p>

<blockquote>
  <p><strong>NOTE:</strong> Anything the container creates will live as a singleton instance in the container. So any other requests from the container will always return the originally created instance. Therefore, each distinct scenario in a test suite should have their own instances of the container.</p>
</blockquote>

<p>Below his an example of how you can leverage the container in some tests. Given this base fixture class…</p>

<pre class="brush: csharp;">public class FixtureBase
{
    private readonly UnityAutoMockContainer _autoMockContainer = new UnityAutoMockContainer();

    protected UnityAutoMockContainer AutoMockContainer
    {
        get { return _autoMockContainer; }
    }

    [TestFixtureSetUp]
    public void SetupContext_ALL()
    {
        Before_all_tests();
        Because();
    }

    [TestFixtureTearDown]
    public void TearDownContext_ALL()
    {
        After_all_tests();
    }

    protected virtual void Before_all_tests()
    {
    }

    protected virtual void Because()
    {
    }

    protected virtual void After_all_tests()
    {
    }
}</pre>

<p>If I were given the following system to test.</p>

<pre class="brush: csharp;">public interface IServiceA { void RunA(); }
public interface IServiceB { void RunB(); }

public class TestComponent
{
    public TestComponent(IServiceA serviceA, IServiceB serviceB)
    {
        ServiceA = serviceA;
        ServiceB = serviceB;
    }

    public IServiceA ServiceA { get; private set; }
    public IServiceB ServiceB { get; private set; }

    public void RunAll()
    {
        if (!HowDidItGo())
            return;
        ServiceA.RunA();
        ServiceB.RunB();
    }

    public virtual bool HowDidItGo()
    {
        // some really nasty untestable code
        return true;
    }
}</pre>

<p>The below example demonstrates simply verifying some behavior on the mocked dependencies of the system under test.</p>

<pre class="brush: csharp;">[TestFixture]
public class Example__how_to_pull_items_from_the_UnityAutoMockContainer_when_verifying_behavior_after_an_action_was_taken 
    : FixtureBase
{
    private TestComponent _testComponent;

    protected override void Before_all_tests()
    {
        base.Before_all_tests();
        _testComponent = AutoMockContainer.Resolve&lt;TestComponent&gt;();
    }

    protected override void Because()
    {
        _testComponent.RunAll();
    }

    [Test]
    public void Should_run_ServiceA_RunA()
    {
        AutoMockContainer
            .GetMock&lt;IServiceA&gt;()
            .Verify(v =&gt; v.RunA(), Times.Once());
    }

    [Test]
    public void Should_run_ServiceB_RunB()
    {
        AutoMockContainer
            .GetMock&lt;IServiceB&gt;()
            .Verify(v =&gt; v.RunB(), Times.Once());
    }
}</pre>

<p>Next, you may have noticed that the system under test had a complicated internal method (that may not necessarily be testable). You can use the AutoMocker to create the system under test as a Mock itself, so we can override some of the behavior. Here’s how you could quickly do that. </p>

<blockquote>
  <p><strong>Aside</strong>: I’m not saying this is a good practice or aids in good component design, just saying it’s possible</p>
</blockquote>

<pre class="brush: csharp;">[TestFixture]
public class Example__how_to_use_the_UnityAutoMockContainer_to_override_a_method_on_the_SystemUnderTest_to_test_a_certain_behavior
    : FixtureBase
{

    private TestComponent _testComponent;

    protected override void Before_all_tests()
    {
        base.Before_all_tests();
        var mockTestComponent = AutoMockContainer.GetMock&lt;TestComponent&gt;();

        mockTestComponent
            .Setup(s =&gt; s.HowDidItGo())
            .Returns(false);

        _testComponent = mockTestComponent.Object;
    }

    protected override void Because()
    {
        _testComponent.RunAll();
    }

    [Test]
    public void Should_run_ServiceA_RunA()
    {
        AutoMockContainer
            .GetMock&lt;IServiceA&gt;()
            .Verify(v =&gt; v.RunA(), Times.Never());
    }

    [Test]
    public void Should_run_ServiceB_RunB()
    {
        AutoMockContainer
            .GetMock&lt;IServiceB&gt;()
            .Verify(v =&gt; v.RunB(), Times.Never());
    }
}</pre>

<p>&#160;</p>

<p>It’s amazing how much redundant test setup code this little helper has saved me in my tests. I hope others can find some use with this as well.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/01/03/unitymoq-automocker-or-automockingcontainer/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>StatLight &#8211; Goes Open Source</title>
		<link>http://elegantcode.com/2009/12/10/statlight-goes-open-source/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=statlight-goes-open-source</link>
		<comments>http://elegantcode.com/2009/12/10/statlight-goes-open-source/#comments</comments>
		<pubDate>Fri, 11 Dec 2009 03:26:55 +0000</pubDate>
		<dc:creator>Jason Jarrett</dc:creator>
				<category><![CDATA[Esoterica]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[TDD]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Tools and Utilities]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/12/10/statlight-goes-open-source/</guid>
		<description><![CDATA[Although I made a very minor attempt at making StatLight a “for-sale” product, I knew when I started that open-source was most likely going to be my long term path for StatLight. What is it? (Silverlight Testing Automation Tool) StatLight is a tool developed for automating the setup, running, and gathering results of Silverlight unit [...]]]></description>
			<content:encoded><![CDATA[Although I made a very minor attempt at making <a href="http://statlight.net" target="_blank">StatLight</a> a “for-sale” product, I knew when I started that open-source was most likely going to be my long term path for <a href="http://statlight.net" target="_blank">StatLight</a>.
<h5>What is it? (Silverlight Testing Automation Tool)</h5>
StatLight is a tool developed for automating the setup, running, and gathering results of Silverlight unit tests. StatLight helps to speed up the feedback cycles while practicing<a href="http://en.wikipedia.org/wiki/Test-driven_development"> TDD</a>/<a href="http://en.wikipedia.org/wiki/Behavior_Driven_Development">BDD</a>/(insert your test style here) during Silverlight development.
<h5>Where can I get StatLight?</h5>
<a href="http://StatLight.CodePlex.com">http://StatLight.CodePlex.com</a>
<h4>Happy Coding !!!</h4>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/12/10/statlight-goes-open-source/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Wrapping up the StructureMap Automocking Container</title>
		<link>http://elegantcode.com/2009/11/30/wrapping-up-the-structuremap-automocking-container/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=wrapping-up-the-structuremap-automocking-container</link>
		<comments>http://elegantcode.com/2009/11/30/wrapping-up-the-structuremap-automocking-container/#comments</comments>
		<pubDate>Mon, 30 Nov 2009 07:21:43 +0000</pubDate>
		<dc:creator>Richard Cirerol</dc:creator>
				<category><![CDATA[TDD]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Unit Testing]]></category>
		<category><![CDATA[StructureMap; Automocking; MSpec;]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/11/30/wrapping-up-the-structuremap-automocking-container/</guid>
		<description><![CDATA[<p><font color="#804040"><strong>UPDATE</strong>: I apologize…the original wrapper did not allow injected dependencies.&#160; I have fixed this bug and updated the sample.</font></p> I have been using StructureMap.AutoMocking with MSpec (Machine.Specifications) and Rhino.Mocks for a few months now.  Although I am very comfortable with the patterns that emerge from using the frameworks together, introducing StructureMap.Automocking to other developers is sometimes challenging. I decided to wrap the details of the container to make the intention clearer and explanation easier.  I have started using this wrapper in my projects, and have found it makes building up specifications more efficient in my daily coding.]]></description>
			<content:encoded><![CDATA[<span style="color: #804040;"><strong>UPDATE</strong>: I apologize…the original wrapper did not allow injected dependencies.  I have fixed this bug and updated the sample.</span>

I have been using StructureMap.AutoMocking with MSpec (Machine.Specifications) and Rhino.Mocks for a few months now.  Although I am very comfortable with the patterns that emerge from using the frameworks together, introducing StructureMap.Automocking to other developers is sometimes challenging.

When viewing a specification or test set up with the Rhino.Mocks or Moq automocking container, what is being tested is not readily apparent.  Once the concept is explained and demonstrated, these same developers seem to have no issue with maintaining the specifications/tests.

I decided to wrap the details of the container to make the intention clearer and explanation easier.  I have started using this wrapper in my projects, and have found it makes building up specifications more efficient in my daily coding.

Let me know whether this is useful to you, or how it could be made more useful.
<h4>The Examples</h4>
Let’s contrive an example.  We’ll say we have a coffee machine that grinds its own beans before brewing. However, the hopper has to have beans before starting the grind.  Here is the basic specification:
<table border="1" cellspacing="0" cellpadding="2" width="533">
<tbody>
<tr>
<td width="117" valign="top">Action/Behavior</td>
<td width="414" valign="top">Prepare coffee grounds for 12 cups of coffee</td>
</tr>
<tr>
<td rowspan="2" width="117" valign="top">Expectations</td>
<td width="414" valign="top">Should check that hopper has beans (mock returns true)</td>
</tr>
<tr>
<td width="414" valign="top">Because hopper has beans, should ask grinder to grind enough beans for 12 cups of coffee</td>
</tr>
</tbody></table>
We could start without a container, using Rhino.Mocks to build up the CoffeeMachine dependencies manually:
<pre class="brush: csharp;">[Subject(typeof(CoffeeMachine),"using vanilla Rhino.Mocks")]
public class Example01_when_preparing_coffee_grounds
{
    Establish context = () =&gt;
        {
            Grinder = MockRepository.GenerateMock&lt;IGrinder&gt;();
            Hopper = MockRepository.GenerateMock&lt;IHopper&gt;();
            Hopper.Expect(x =&gt; x.HasBeans()).Return(true);
            CoffeeMachine = new CoffeeMachine(Grinder, Hopper);
        };

    Because of = () =&gt; _coffeeMachine.PrepareCoffeeGrounds(12);

    It should_check_if_hopper_has_beans = () =&gt; Hopper.VerifyAllExpectations();
    It should_grind_coffee = () =&gt; Grinder.AssertWasCalled(x =&gt; x.Grind(12));

    static IGrinder Grinder;
    static IHopper Hopper;
    static CoffeeMachine CoffeeMachine;
}</pre>
For those of you not familiar with the MSpec style, please refer to the following posts:
<ul>
	<li><a href="http://blog.wekeroad.com/blog/make-bdd-your-bff-2/" target="_blank">Make BDD Your BFF</a></li>
	<li><a href="http://www.lostechies.com/blogs/seanbiefeld/archive/2009/08/25/step-by-step-to-using-machine-specifications-with-resharper.aspx" target="_blank">Step by Step to Using MSpec (Machine.Specifications) with ReSharper</a></li>
	<li><a href="http://elegantcode.com/2009/07/05/mspec-take-2/" target="_blank">MSpec - Take 2</a></li>
	<li><a href="http://marcinobel.com/index.php/mspec-bdd-installer/" target="_blank">MSpec BDD framework installer</a></li>
	<li><strong>Updated! </strong>From the <a href="http://blog.cwa.me.uk/2009/11/30/the-morning-brew-487/" target="_blank">Morning Brew #487</a>: BDD with MSpec and Rhino Auto Mocks, parts  <a href="http://telldontask.wordpress.com/2009/11/10/bdd-with-mspec-and-rhino-auto-mocks/" target="_blank">1</a>, <a href="http://telldontask.wordpress.com/2009/11/19/bdd-with-mspec-and-rhino-auto-mocks-part-2/" target="_blank">2</a>, and <a href="http://telldontask.wordpress.com/2009/11/29/bdd-with-mspec-and-rhino-auto-mocks-part-3/" target="_blank">3</a>
Here is the same specification using the RhinoAutoMocker&lt;T&gt; class provided by StructureMap.AutoMocking:</li>
</ul>
<pre class="brush: csharp;">[Subject(typeof(CoffeeMachine),"using RhinoAutoMocker&lt;CoffeeMachine&gt;")]
public class Example02_when_preparing_coffee_grounds
{
    Establish context = () =&gt;
        {
            CoffeeMachine = new RhinoAutoMocker&lt;CoffeeMachine&gt;();
            Grinder = CoffeeMachine.Get&lt;IGrinder&gt;();
            Hopper = CoffeeMachine.Get&lt;IHopper&gt;();
            Hopper.Expect(x =&gt; x.HasBeans()).Return(true);
        };

    Because of = () =&gt; v.ClassUnderTest.PrepareCoffeeGrounds(12);

    It should_check_if_hopper_has_beans = () =&gt; Hopper.VerifyAllExpectations();
    It should_grind_coffee = () =&gt; Grinder.AssertWasCalled(x =&gt; x.Grind(12));

    static IGrinder Grinder;
    static IHopper Hopper;
    static RhinoAutoMocker&lt;CoffeeMachine&gt; CoffeeMachine;
}</pre>
Although I think this looks cleaner, the initialization of CoffeeMachine causes some confusion. Unfortunately, a common question would be, “Is RhinoAutoMocker&lt;CoffeeMachine&gt; creating a mocked version of CoffeeMachine?” Well, not exactly.

RhinoAutoMocker is an implementation of the AutoMocker base class which uses StructureMap to fill dependencies.  The RhinoAutoMocker implementation of the container uses Rhino.Mocks to generate all of dependencies of the target class, whereas the MoqAutoMocker implementation uses Moq.  (Optionally, the target class can be partially mocked in order to further isolate behavior.)  We then retrieve the class under test (in this case, CoffeeMachine) and its dependencies (IGrinder and IHopper) from the container for use.

If you do not need to setup any expectations in the specification, there is no need to retrieve the dependency from the container.  However, in this specification, we need both dependencies.

<em>(Incidentally, I do not like the ClassUnderTest name.  I may end up changing this to Instance, ClassInstance, TargetClass, or something similar.  Suggestions?)</em>

By moving the initialization of the RhinoAutoMocker to a base class, some of the chattiness of the context can be hidden.
<ul>
<pre class="brush: csharp;">[Subject(typeof(CoffeeMachine),"using RhinoAutoMocker base")]
public class Example03_when_preparing_coffee_grounds : with_rhinoautomocker
{
    Establish context = () =&gt; Hopper.Expect(x =&gt; x.HasBeans()).Return(true);

    Because of = () =&gt; CoffeeMachine.ClassUnderTest.PrepareCoffeeGrounds(12);

    It should_check_if_hopper_has_beans = () =&gt; Hopper.VerifyAllExpectations();
    It should_grind_coffee = () =&gt; Grinder.AssertWasCalled(x =&gt; x.Grind(12));

}

[Subject("using RhinoAutoMocker&lt;T&gt;")]
public class with_rhinoautomocker
{
    protected static IGrinder Grinder;
    protected static IHopper Hopper;
    protected static RhinoAutoMocker&lt;CoffeeMachine&gt; CoffeeMachine;

    Establish context = () =&gt;
    {
        CoffeeMachine = new RhinoAutoMocker&lt;CoffeeMachine&gt;();
        Grinder = CoffeeMachine.Get&lt;IGrinder&gt;();
        Hopper = CoffeeMachine.Get&lt;IHopper&gt;();
    };
}</pre>
However, we are still initializing and accessing the class in a less than optimal manner.To make the usage of the container a little more seamless, I decided to create a wrapper and factory for the AutoMocker.  Setup of the dependencies and expectations are done through an AutoMocker wrapper object.  The instance of the class under test is accessed through a ClassUnderTest object.
<h4>The Result</h4>
The specification (and base class) now look like this:
<pre class="brush: csharp;">[Subject(typeof(CoffeeMachine),"using coffee machine base")]
public class Example05_when_preparing_coffee_grounds : with_coffee_machine
{
    Establish context = () =&gt; Hopper.Expect(x =&gt; x.HasBeans()).Return(true);

    Because of = () =&gt; ClassUnderTest.PrepareCoffeeGrounds(12);

    It should_check_if_hopper_has_beans = () =&gt; Hopper.VerifyAllExpectations();
    It should_grind_coffee = () =&gt; Grinder.AssertWasCalled(x =&gt; x.Grind(12));
}

[Subject("using SpecificationFor&lt;CoffeeMachine&gt;")]
public class with_coffee_machine : SpecificationFor&lt;CoffeeMachine&gt;
{
    protected static IGrinder Grinder;
    protected static IHopper Hopper;

    public with_coffee_machine
    {
        Grinder = AutoMocker.Get&lt;IGrinder&gt;();
        Hopper = AutoMocker.Get&lt;IHopper&gt;();
    }
}</pre>
As you can see, the base class inherits from SpecificationFor&lt;T&gt;.  The default constructor uses Rhino.Mocks(MockMode.AAA) to generate the dependencies.  It then exposes a AutoMocker object, which is just the wrapper around the AutoMocker base class.  It also exposes a ClassUnderTest object.  If I didn’t need to use the dependencies, I could make the <em>Example05_when_preparing_coffee_grounds</em> class inherit from <em>SpecificationFor&lt;CoffeeMachine&gt; </em>instead of inheriting from the base class<em>.</em>
<h4>The Code</h4>
I have included the code for the wrapper below for your review.  The code and six examples are available on my <a href="http://codeprogression.googlecode.com/svn/trunk/CodeProgression.Framework.Testing" target="_blank">Google code repository</a>. The repository also includes an example using the MoqAutoMocker.  All the examples have the same assertions, but are built up using the different techniques.
<pre class="brush: csharp;">namespace CodeProgression.Framework.Testing
{
    public abstract class SpecificationFor&lt;T&gt; where T: class
    {
        protected static ClassUnderTest&lt;T&gt; Factory;

        // UPDATE 2009-12-21:
        //   Moved initialization here
        protected static T ClassUnderTest {get {return AutoMocker.Instance;} }

        protected SpecificationFor()
        {
            AutoMocker = AutoMockFactory.CreateTarget&lt;T&gt;();

            // UPDATE 2009-12-21:
            //    Initializing here prevented injected dependencies!
            // AutoMocker.PartialMockTheClassUnderTest();
            // ClassUnderTest = AutoMocker.Instance;
        }

        protected SpecificationFor(AutoMockType type)
        {
            AutoMocker = AutoMockFactory.CreateTarget&lt;T&gt;(type);

            // UPDATE 2009-12-21:
            // Initializing here prevented injected dependencies!
            // AutoMocker.PartialMockTheClassUnderTest();
            // ClassUnderTest = AutoMocker.Instance;
        }
    }

    public static class AutoMockFactory
    {
        public static ClassUnderTest&lt;TARGETCLASS&gt; CreateTarget&lt;TARGETCLASS&gt;() where TARGETCLASS : class
        {
            return CreateTarget&lt;TARGETCLASS&gt;(AutoMockType.RhinoMocksAAA);
        }

        public static ClassUnderTest&lt;TARGETCLASS&gt; CreateTarget&lt;TARGETCLASS&gt;(AutoMockType framework) where TARGETCLASS : class
        {
            AutoMocker&lt;TARGETCLASS&gt; mocker;
            ServiceLocator serviceLocator;
            switch (framework)
            {
                case AutoMockType.RhinoMocksAAA:
                    mocker = new RhinoAutoMocker&lt;TARGETCLASS&gt;(MockMode.AAA);
                    serviceLocator = new RhinoMocksAAAServiceLocator();
                    break;
                case AutoMockType.RhinoMocksClassic:
                    mocker = new RhinoAutoMocker&lt;TARGETCLASS&gt;(MockMode.RecordAndReplay);
                    serviceLocator = new RhinoMocksClassicServiceLocator();
                    break;
                case AutoMockType.Moq:
                    mocker = new MoqAutoMocker&lt;TARGETCLASS&gt;();
                    serviceLocator = new MoqServiceLocator();
                    break;
                default:
                    throw new ArgumentOutOfRangeException("framework");
            }
            return new ClassUnderTest&lt;TARGETCLASS&gt;(mocker, serviceLocator);
        }
    }

    public enum AutoMockType
    {
        Moq,
        RhinoMocksAAA,
        RhinoMocksClassic
    }

    public class ClassUnderTest&lt;TARGETCLASS&gt; where TARGETCLASS : class
    {
        readonly IAutoMocker&lt;TARGETCLASS&gt; _mocker;
        readonly ServiceLocator _serviceLocator;

        public ClassUnderTest(IAutoMocker&lt;TARGETCLASS&gt; mocker, ServiceLocator serviceLocator)
        {
            _mocker = mocker;
            _serviceLocator = serviceLocator;
        }

        public AutoMockedContainer Container
        {
            get { return _mocker.Container; }
        }

        public TARGETCLASS Instance
        {
            get { return _mocker.ClassUnderTest; }
        }

        public void MockObjectFactory()
        {
            _mocker.MockObjectFactory();
        }

        public void PartialMockTheClassUnderTest()
        {
            _mocker.PartialMockTheClassUnderTest();
        }

        public T Get&lt;T&gt;() where T : class
        {
            return _mocker.Get&lt;T&gt;();
        }

        public void Inject(Type pluginType, object stub)
        {
            _mocker.Inject(pluginType, stub);
        }

        public void Inject&lt;T&gt;(T target)
        {
            _mocker.Inject(target);
        }

        public T AddAdditionalMockFor&lt;T&gt;() where T : class
        {
            return _mocker.AddAdditionalMockFor&lt;T&gt;();
        }

        public void UseConcreteClassFor&lt;T&gt;()
        {
            _mocker.UseConcreteClassFor&lt;T&gt;();
        }

        public T[] CreateMockArrayFor&lt;T&gt;(int count) where T : class
        {
            return _mocker.CreateMockArrayFor&lt;T&gt;(count);
        }

        public void InjectArray&lt;T&gt;(T[] stubs)
        {
            _mocker.InjectArray(stubs);
        }

        public T Mock&lt;T&gt;() where T : class
        {
            return _serviceLocator.Service&lt;T&gt;();
        }
        public object Mock(Type serviceType)
        {
            return _serviceLocator.Service(serviceType);
        }
        public T PartialMock&lt;T&gt;() where T : class
        {
            return _serviceLocator.PartialMock&lt;T&gt;();
        }
    }
}</pre>
</ul>
<script type="text/javascript">// <![CDATA[
 var cirerolGaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."); document.write(unescape("%3Cscript src='" + cirerolGaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
// ]]&gt;</script>

<script type="text/javascript">// <![CDATA[
 var cirerolPageTracker = _gat._getTracker('UA-8257866-3'); cirerolPageTracker._initData(); cirerolPageTracker._trackPageview();
// ]]&gt;</script>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/11/30/wrapping-up-the-structuremap-automocking-container/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Integration Test Brought to you by Powershell &amp; NUnit &#8211; with a Little Specification Syntax for Flavoring</title>
		<link>http://elegantcode.com/2009/10/25/integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring</link>
		<comments>http://elegantcode.com/2009/10/25/integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring/#comments</comments>
		<pubDate>Mon, 26 Oct 2009 05:00:40 +0000</pubDate>
		<dc:creator>Jason Jarrett</dc:creator>
				<category><![CDATA[Esoterica]]></category>
		<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/10/25/integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring/</guid>
		<description><![CDATA[One of the tools I’ve used the last half of a year and really enjoyed is the C# specification extension methods when writing unit test assertions. If you’re looking for a little more background on the topic, I wrote about Fluent Specification Extensions in a past blog. Recently I wanted to execute a PowerShell script [...]]]></description>
			<content:encoded><![CDATA[One of the tools I’ve used the last half of a year and really enjoyed is the C# specification extension methods when writing unit test assertions. If you’re looking for a little more background on the topic, I wrote about <a href="http://staxmanade.blogspot.com/2009/02/fluent-specification-extensions.html">Fluent Specification Extensions</a> in a past blog.

Recently I wanted to execute a PowerShell script to do some automated <a href="http://en.wikipedia.org/wiki/Functional_testing">functional testing</a>. I wanted to execute an application and apply some assertions on the output of the software(basically running a console app, parse the xml output and assert on values in the output).
<blockquote>FYI: I’m very new to PowerShell, so any suggestions on how I implemented the below are welcome…</blockquote>
I’ve seen a couple examples of writing test assertions in PowerShell out there. One example is <a href="http://www.psunit.org/">PSUnit</a>; however, this seemed a little heavy for my needs and not quite the syntactic sugar I was looking for.

Besides the syntax flavor I was desiring, another thing I wanted to do was leverage the power of NUnit.Framework’s assertion capabilities. I like the error messages generated when strings and other objects fail the assertion.
<h5>Examples of end result ShouldLookLike()…</h5>
$true.ShouldBeTrue()
$false.ShouldBeFalse()
"a".ShouldEqual("a")
"a".ShouldNotEqual("b")
<h5><strong>Step 1</strong>: Figure out how to write a C# style <a href="http://msdn.microsoft.com/en-us/library/bb383977.aspx">extension method</a> in PowerShell.</h5>
<blockquote>I found a great blog post describing how to extend any PowerShell object to add extension methods.

<a href="http://bartdesmet.net/blogs/bart/archive/2007/09/06/extension-methods-in-windows-powershell.aspx">Extension Methods in Windows PowerShell</a></blockquote>
In short, to extend types in PowerShell leveraging the <a href="http://msdn.microsoft.com/en-us/library/ms714419(VS.85).aspx">Extended Type System</a>, you need to define them in an xml file and import the method definitions into the PowerShell runtime instance.

Below is PowerShell XML definition for my NUnit Specification Extensions.
<pre class="brush: xml;">&lt;?xml version="1.0" encoding="utf-16"?&gt;
&lt;Types&gt;
    &lt;Type&gt;
        &lt;Name&gt;System.Object&lt;/Name&gt;
        &lt;Members&gt;
            &lt;ScriptMethod&gt;
                &lt;Name&gt;ShouldBeFalse&lt;/Name&gt;
                &lt;Script&gt;
                    [NUnit.Framework.Assert]::IsFalse($this)
                &lt;/Script&gt;
            &lt;/ScriptMethod&gt;
            &lt;ScriptMethod&gt;
                &lt;Name&gt;ShouldBeTrue&lt;/Name&gt;
                &lt;Script&gt;
                    [NUnit.Framework.Assert]::IsTrue($this)
                &lt;/Script&gt;
            &lt;/ScriptMethod&gt;
            &lt;ScriptMethod&gt;
                &lt;Name&gt;ShouldEqual&lt;/Name&gt;
                &lt;Script&gt;
                    [NUnit.Framework.Assert]::AreEqual($args[0], $this)
                &lt;/Script&gt;
            &lt;/ScriptMethod&gt;
            &lt;ScriptMethod&gt;
                &lt;Name&gt;ShouldNotEqual&lt;/Name&gt;
                &lt;Script&gt;
                    [NUnit.Framework.Assert]::AreNotEqual($args[0], $this)
                &lt;/Script&gt;
            &lt;/ScriptMethod&gt;
        &lt;/Members&gt;
    &lt;/Type&gt;
&lt;/Types&gt;</pre>
<h4></h4>
Take the above XML and save it to a file…
<blockquote>NOTE: the file HAS to be saved with the extension <strong>.ps1xml</strong>

Ex: NunitSpecificationPowerShellExtensions<strong>.ps1xml</strong></blockquote>
<h4></h4>
<h5>Step 2: Load the extended type definition into the PowerShell runtime.</h5>
Once you’ve saved the XML extended types to a file, you need to load it into the PowerShell runtime by executing the command below.
<blockquote>
Update-TypeData -PrependPath NunitSpecificationPowerShellExtensions.ps1xml</blockquote>
Before executing the above statement…Let’s quickly look at a System.String’s members and properties – just to show you what the extension methods look like when applied inside of the runtime.<a href="http://elegantcode.com/wp-content/uploads/2009/10/image3.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" src="http://elegantcode.com/wp-content/uploads/2009/10/image_thumb2.png" border="0" alt="image" width="586" height="479" /></a>

After executing the Update-TypeData command you’ll notice there are a number of “ScriptMethod” MemberTypes added to the object.

<a href="http://elegantcode.com/wp-content/uploads/2009/10/image4.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" src="http://elegantcode.com/wp-content/uploads/2009/10/image_thumb3.png" border="0" alt="image" width="600" height="580" /></a>

Now if you try to execute one of those newly added extension methods, you may get the following error…

PS C:\&gt; $testVar.<strong>ShouldEqual</strong>("hello world")

Exception calling "ShouldEqual" with "1" argument(s): "<strong>Unable to find type [NUnit.Framework.Assert]: make sure that the

assembly containing this type is loaded.</strong>"

At line:1 char:21

+ $testVar.ShouldEqual &lt;&lt;&lt;&lt; ("hello world")

+ CategoryInfo          : NotSpecified: (:) [], MethodInvocationException

+ FullyQualifiedErrorId : ScriptMethodRuntimeException

This is because we need to load the NUnit.Framework assembly into the runtime before we can leverage the extension methods.
<blockquote>[System.Reflection.Assembly]::LoadFrom("C:\Program Files\NUnit 2.5.2\bin\net-2.0\framework\nunit.framework.dll") | Out-Null</blockquote>
Now that the extension methods have been defined and loaded into the runtime, NUnit.Framework is loaded, we can now use the methods on any object that inherits from System.Object (which, as far as I know, is everything in PowerShell).

And now, everything you need in one script (if you have the xml extended type file saved somewhere…)
<pre>#
# Update-TypeData -prependPath C:\Code\NunitSpecificationPowerShellExtensions.ps1xml
#

[System.Reflection.Assembly]::LoadFrom("C:\Program Files\NUnit 2.5.2\bin\net-2.0\framework\nunit.framework.dll") | Out-Null

$true.ShouldBeTrue()

$false.ShouldBeFalse()

"a".ShouldEqual("a")

"a".ShouldNotEqual("b")</pre>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/10/25/integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Visual Studio Team System for Small Teams</title>
		<link>http://elegantcode.com/2009/12/10/statlight-goes-open-source/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=statlight-goes-open-source</link>
		<comments>http://elegantcode.com/2009/12/10/statlight-goes-open-source/#comments</comments>
		<pubDate>Fri, 11 Dec 2009 03:26:55 +0000</pubDate>
		<dc:creator>Jason Jarrett</dc:creator>
				<category><![CDATA[Esoterica]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[TDD]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Tools and Utilities]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/12/10/statlight-goes-open-source/</guid>
		<description><![CDATA[Although I made a very minor attempt at making StatLight a “for-sale” product, I knew when I started that open-source was most likely going to be my long term path for StatLight. What is it? (Silverlight Testing Automation Tool) StatLight is a tool developed for automating the setup, running, and gathering results of Silverlight unit [...]]]></description>
			<content:encoded><![CDATA[Although I made a very minor attempt at making <a href="http://statlight.net" target="_blank">StatLight</a> a “for-sale” product, I knew when I started that open-source was most likely going to be my long term path for <a href="http://statlight.net" target="_blank">StatLight</a>.
<h5>What is it? (Silverlight Testing Automation Tool)</h5>
StatLight is a tool developed for automating the setup, running, and gathering results of Silverlight unit tests. StatLight helps to speed up the feedback cycles while practicing<a href="http://en.wikipedia.org/wiki/Test-driven_development"> TDD</a>/<a href="http://en.wikipedia.org/wiki/Behavior_Driven_Development">BDD</a>/(insert your test style here) during Silverlight development.
<h5>Where can I get StatLight?</h5>
<a href="http://StatLight.CodePlex.com">http://StatLight.CodePlex.com</a>
<h4>Happy Coding !!!</h4>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/12/10/statlight-goes-open-source/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Elegant Code &#187; Unit Testing</title>
	<atom:link href="http://elegantcode.com/category/unit-testing/feed/" rel="self" type="application/rss+xml" />
	<link>http://elegantcode.com</link>
	<description></description>
	<lastBuildDate>Tue, 15 May 2012 10:00:00 +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>AutoTest.NET</title>
		<link>http://elegantcode.com/2010/11/30/autotest-net/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=autotest-net</link>
		<comments>http://elegantcode.com/2010/11/30/autotest-net/#comments</comments>
		<pubDate>Tue, 30 Nov 2010 11:00:00 +0000</pubDate>
		<dc:creator>Jan Van Ryswyck</dc:creator>
				<category><![CDATA[TDD]]></category>
		<category><![CDATA[Tools and Utilities]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/11/30/autotest-net/</guid>
		<description><![CDATA[I just want to quickly point out a tool that I’ve been playing with for a couple of days now, named AutoTest.NET. Its an open-source tool that originates from a popular tool in the Ruby community called ZenTest, which basically runs all your valuable unit tests when you save your source files or when you [...]]]></description>
			<content:encoded><![CDATA[<p>I just want to quickly point out a tool that I’ve been playing with for a couple of days now, named <a href="https://github.com/acken/AutoTest.Net" target="_blank">AutoTest.NET</a>. Its an open-source tool that originates from a popular tool in the Ruby community called <a href="http://www.zenspider.com/ZSS/Products/ZenTest/" target="_blank">ZenTest</a>, which basically runs all your valuable unit tests when you save your source files or when you build your code. It enables you to get feedback about your changes as soon as possible.</p>  <p>The project started out a couple of years ago on <a href="http://code.google.com/p/autotestnet/" target="_blank">Google code</a> and was first initiated by <a href="http://averyblog.com/" target="_blank">James Avery</a>. Contribution stopped at some point until recently where <a href="http://ackenpacken.blogspot.com/" target="_blank">Svein Arne Ackenhausen</a> forked the source code and <a href="https://github.com/acken/AutoTest.Net" target="_blank">put it on GitHub</a>. Now it runs both for .NET as well as Mono, with NUnit, MSTest and xUnit as the currently supported unit test frameworks. </p>  <p>Here’s a screenshot from the feedback window when all tests pass:</p>  <p><a href="http://elegantcode.com/wp-content/uploads/2010/11/Success.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="Success" border="0" alt="Success" src="http://elegantcode.com/wp-content/uploads/2010/11/Success_thumb.png" width="540" height="189" /></a> </p>  <p>And here you can see the same window after I broke one of my unit tests:</p>  <p><a href="http://elegantcode.com/wp-content/uploads/2010/11/Failure.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="Failure" border="0" alt="Failure" src="http://elegantcode.com/wp-content/uploads/2010/11/Failure_thumb.png" width="538" height="319" /></a> </p>  <p>Here you can see which particular unit test has been broken and by clicking the specified link you end up at the right source file in Visual Studio. </p>  <p>I encourage you to pick up this small tool and learn how it can facilitate your TDD flow. Take a look at <a href="https://github.com/acken/AutoTest.Net/wiki/Get-started!" target="_blank">this page</a> in order to get up-and-running in no time. Also don’t forget to provide the owner(s) of this project with some feedback that you might have. Svein has been very helpful over the last week answering all my stupid questions and remarks (and the Nobel price for this year’s most patient person goes to … ;-) ). </p>  <p>I would definitely like to see this tool becoming more popular, so go check it out.&#160;&#160; </p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/11/30/autotest-net/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>If Self-Documenting Code is the What, Unit Tests are the Why</title>
		<link>http://elegantcode.com/2010/04/25/if-self-documenting-code-is-the-what-unit-tests-are-the-why/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=if-self-documenting-code-is-the-what-unit-tests-are-the-why</link>
		<comments>http://elegantcode.com/2010/04/25/if-self-documenting-code-is-the-what-unit-tests-are-the-why/#comments</comments>
		<pubDate>Sun, 25 Apr 2010 19:09:04 +0000</pubDate>
		<dc:creator>John Sonmez</dc:creator>
				<category><![CDATA[Agile]]></category>
		<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Craftsmanship]]></category>
		<category><![CDATA[Documentation]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/04/25/if-self-documenting-code-is-the-what-unit-tests-are-the-why/</guid>
		<description><![CDATA[It is not enough to just write code that is clean and self-documenting.  Eliminating comments and replacing them with clear variable and method names, will tell the reader of your code clearly what it is doing, but it will not properly express why it is doing it. If you recall from my original post on [...]]]></description>
			<content:encoded><![CDATA[It is not enough to just write code that is clean and self-documenting.  <a href="http://elegantcode.com/2010/04/18/eliminating-comments-the-road-to-clarity/">Eliminating comments</a> and replacing them with clear variable and method names, will tell the reader of your code clearly what it is doing, but it will not properly express why it is doing it.

If you recall from my <a href="http://elegantcode.com/2010/04/09/what-does-elegant-code-mean-to-me/">original post</a> on Elegant code, I stated that elegant code is:
<blockquote>Something that is simple yet effective, delivered with grace.</blockquote>
By writing self-documenting code we are hopefully able to achieve some of the aspects of simplicity and grace, but it tells us nothing about the effectiveness of the code.
<h2>Bringing the dead to life</h2>
<a href="http://elegantcode.com/wp-content/uploads/2010/04/zombies.jpg"><img style="border-right-width: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto" title="zombies" src="http://elegantcode.com/wp-content/uploads/2010/04/zombies_thumb.jpg" border="0" alt="zombies" width="441" height="295" /></a>

Throwing out comments is a debatable topic.  <a href="http://www.reddit.com/r/programming/comments/bsutx/">It raises quite a bit of controversy</a>, as you can see from some of the comments on my post about the subject.  The reason, perhaps, that so many people are so staunchly opposed to the idea, is because they are worried, and rightly so, that throwing out comments will reduce the documentation of what the code is doing.

Think about that for a second.  Is documentation of what the code is doing important?  It better be.  What we are trying to accomplish by writing self-documenting code instead of comments, is to take the vessel, which is the code itself, and make that same vessel be the documentation of what the code does.  It is by doing this that we creating a living representation of the functionality of the code.  Comments are akin to a dead representation of the functionality of the code because they do not change automatically with the code.

I diverge to talk about comments so that I can draw a parallel to another form of documentation which is valuable and should be considered necessary.  That other set of documentation is requirements.  Have you ever written requirements documents?  Have you ever captured requirements from the customer and put them into UML diagrams, or perhaps plopped them into some templated Word document, which is never updated again, and no one reads, because no one trusts it is correct?  Wouldn’t it be great if we would replace that dead document or set of documents, with a living one?

The good news is we can, and some of us have.  And I fully expect this recommendation will be just as controversial, because <strong>I am suggesting that we don’t have to write low level specifications of the system at all, instead we can write good unit tests. </strong>When we do this, we are taking a dead form of document and bringing it to life.
<h2>Unit tests tell us why and how our code is effective</h2>
If
<pre class="csharpcode">i = 5;  // Widget count defaults to five.</pre>
is replaced with
<pre class="csharpcode">widgetCount = DEFAULT_WIDGET_COUNT;</pre>
<!--.csharpcode, .csharpcode pre { 	font-size: small; 	color: black; 	font-family: consolas, "Courier New", courier, monospace; 	background-color: #ffffff; 	/*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt  { 	background-color: #f4f4f4; 	width: 100%; 	margin: 0em; } .csharpcode .lnum { color: #606060; } -->

then
<blockquote><span style="background-color: #ffffff;">1.1.5 When a new widget is created, the widget count should be increased by one.</span></blockquote>
is replaced with
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">void</span> When_NewWidgetIsCreated_Then_WidgetCountIsIncreasedByOne()
{
     WidgetFactory.Count = 3;
     WidgetFactory.CreateNew();
     assertEquals(4, WidgetFactory.Count);
}</pre>
The unit test is replacing the low level requirement, which is somewhat open to interpretation and untied to the code, with an absolute and completely tied-to-the-code, specific requirement.

The unit test is telling us why our code is built the way it is.  It is telling us what requirement that particular structure of code is trying to address.  <strong>It is telling us what end result that code is trying to accomplish and what the expectations are on the results of a given condition.</strong>

The unit test is telling us how the code is to be used in order to achieve its result.  It is serving as a living reference to the syntax and use of the code we built.  <strong>Instead of providing instructions on how to use our API, we are providing a living example, and proof that it will indeed work.</strong> Examples are often much more effective than instructions anyway.
<h2>What exactly are we replacing?</h2>
At this point we are not trying to replace all the documentation of the system (at this point).

With self-documenting code, we sought to eliminate comments, and replace them with good variable and method names.

With unit tests, we seek to eliminate technical documentation and requirements of the system, that is targeted at a developer or technical audience.

We are NOT trying to eliminate high level specifications of the system, or use cases. <strong>Unit tests DO NOT replace that kind of documentation! </strong>We will talk about replacing that kind of documentation when we talk about automated functional or system tests.

Simply put, any kind of documentation that you would give to a developer so they understand how the system works and how to use the code or APIs, can be easily replaced by writing good unit tests.

Our simple goal is to replace the “dead” documentation (meaning that it does not update automatically with the thing it is documenting), with “living” documentation in the form of unit tests.

One last point.  I want to be clear that I am not saying that having unit tests automatically results in the ability to replace technical documentation.  Just like having long-named methods and variables doesn’t automatically replace the need for comments.  It is a matter of the quality of the unit tests that are written, just as it is a matter of the quality of the self-documenting code.
<h5>As always, you can subscribe to this <a href="http://feeds2.feedburner.com/ElegantCode">RSS feed</a> to follow my posts on elegant code.  Feel free to check out my main personal blog at <a href="http://simpleprogrammer.com">http://simpleprogrammer.com</a>, which has a wider range of posts, updated 2-3 times a week.  Also, you can follow me on twitter <a href="http://twitter.com/jsonmez">here</a>.</h5>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/04/25/if-self-documenting-code-is-the-what-unit-tests-are-the-why/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Behaviors with MSpec</title>
		<link>http://elegantcode.com/2010/02/26/behaviors-with-mspec/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=behaviors-with-mspec</link>
		<comments>http://elegantcode.com/2010/02/26/behaviors-with-mspec/#comments</comments>
		<pubDate>Fri, 26 Feb 2010 23:33:28 +0000</pubDate>
		<dc:creator>Jan Van Ryswyck</dc:creator>
				<category><![CDATA[BDD]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/02/26/behaviors-with-mspec/</guid>
		<description><![CDATA[In my previous posts, I showed the syntax for context/specifications using Machine.Specifications (or MSpec for short) and how to use an auto mocking container in conjunction with this excellent Behavior-Driven Development (BDD) framework. For this post, I want to show you one of the nice features of MSpec called behaviors. Suppose we have to create [...]]]></description>
			<content:encoded><![CDATA[<p>In my previous posts, I showed the <a href="http://elegantcode.com/2010/02/19/getting-started-with-machine-specifications-mspec/">syntax for context/specifications</a> using <a href="http://github.com/machine/machine.specifications">Machine.Specifications</a> (or MSpec for short) and <a href="http://elegantcode.com/2010/02/23/mspec-and-auto-mocking">how to use an auto mocking container</a> in conjunction with this excellent Behavior-Driven Development (BDD) framework. For this post, I want to show you one of the nice features of MSpec called <em>behaviors</em>.</p>  <p>Suppose we have to create some sort of specification that validates the format of an e-mail address. We typically use some regular expression in order to ensure that a specified e-mail address is properly formatted.</p>  <pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">class</span> EmailSpecification
{
    <span class="kwrd">private</span> <span class="kwrd">const</span> String EmailRegexPattern = <span class="str">@&quot;.. SOME_REGEX_PATTERN ...&quot;</span>;

    <span class="kwrd">public</span> Boolean IsSatisfiedBy(String candidate)
    {
        var regex = <span class="kwrd">new</span> Regex(EmailRegexPattern);
        <span class="kwrd">return</span> regex.IsMatch(candidate);
    }
}</pre>
<style type="text/css">

.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>I guess this is pretty common and straightforward. One way to provide some unit tests for this particular piece of code is to check a whole number of e-mail addresses that either pass or fail the specification. The following example shows only a couple of scenarios:</p>

<pre class="csharpcode">[TestFixture]
<span class="kwrd">public</span> <span class="kwrd">class</span> When_validating_an_email
    : ContextSpecification&lt;EmailSpecification&gt;
{
    <span class="kwrd">protected</span> <span class="kwrd">override</span> EmailSpecification Create_subject_under_test()
    {
        <span class="kwrd">return</span> <span class="kwrd">new</span> EmailSpecification();
    }

    [Test]
    <span class="kwrd">public</span> <span class="kwrd">void</span> ShouldBeSatisfied()
    {
        Assert.That(SUT.IsSatisfiedBy(<span class="str">&quot;one2@three.com&quot;</span>));
        Assert.That(SUT.IsSatisfiedBy(<span class="str">&quot;one@two3.com&quot;</span>));
    }

    [Test]
    <span class="kwrd">public</span> <span class="kwrd">void</span> ShouldNotBeSatisfied()
    {
        Assert.That(SUT.IsSatisfiedBy(<span class="str">&quot;one_two.com&quot;</span>), Is.False);
        Assert.That(SUT.IsSatisfiedBy(<span class="str">&quot;one_two@&quot;</span>), Is.False);
    }
}</pre>
<style type="text/css">

.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>A slightly more concise approach for these kind of unit tests can be accomplished by utilizing a feature of any decent unit test framework called <em>row tests. </em>With this approach we can, at the very least, reduce the number of asserts we have to write for each unit test.<em>&#160;</em></p>

<pre class="csharpcode">[TestFixture]
<span class="kwrd">public</span> <span class="kwrd">class</span> When_validating_an_email__approach_2
    : ContextSpecification&lt;EmailSpecification&gt;
{
    <span class="kwrd">protected</span> <span class="kwrd">override</span> EmailSpecification Create_subject_under_test()
    {
        <span class="kwrd">return</span> <span class="kwrd">new</span> EmailSpecification();
    }

    [RowTest]
    [Row(<span class="str">&quot;one2@three.com&quot;</span>)]
    [Row(<span class="str">&quot;one@two3.com&quot;</span>)]
    <span class="kwrd">public</span> <span class="kwrd">void</span> ShouldBeSatisfied(String email)
    {
        Assert.That(SUT.IsSatisfiedBy(email));
    }

    [RowTest]
    [Row(<span class="str">&quot;one_two.com&quot;</span>)]
    [Row(<span class="str">&quot;one_two@&quot;</span>)]
    <span class="kwrd">public</span> <span class="kwrd">void</span> ShouldNotBeSatisfied(String email)
    {
        Assert.That(SUT.IsSatisfiedBy(email), Is.False);
    }
}</pre>
<style type="text/css">

.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>Notice that I explicitly called both of these approaches <em>unit tests</em> as they don’t have much to do with BDD in my opinion. I’m not saying that using regular unit tests is a bad thing, but with&#160; behavior-driven development context is king. So these unit tests are perfect examples of ‘<a href="http://elegantcode.com/2008/12/30/dont-sell-out-on-the-context-dude/">context betrayal</a>’ when following the BDD approach. </p>

<p>Lets see what MSpec can bring to the table for these kind of scenarios:</p>

<pre class="csharpcode">[Subject(<span class="kwrd">typeof</span>(EmailSpecification), <span class="str">&quot;is satisfied&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_validating_an_email_address_with_a_number_in_the_local_part
    : email_specification_specs
{
    Establish context = () =&gt;
        EmailAddress = <span class="str">&quot;one2@three.com&quot;</span>;

    Behaves_like&lt;SatisfiedSpecificationBehavior&gt; a_satisfied_specification;
}

[Subject(<span class="kwrd">typeof</span>(EmailSpecification), <span class="str">&quot;is satisfied&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_validating_an_email_address_with_a_number_in_the_domain_name
    : email_specification_specs
{
    Establish context = () =&gt;
        EmailAddress = <span class="str">&quot;one@two3.com&quot;</span>;

    Behaves_like&lt;SatisfiedSpecificationBehavior&gt; a_satisfied_specification;
}

[Subject(<span class="kwrd">typeof</span>(EmailSpecification), <span class="str">&quot;is satisfied&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_validating_an_email_address_without_an_At_sign
    : email_specification_specs
{
    Establish context = () =&gt;
        EmailAddress = <span class="str">&quot;one_two.com&quot;</span>;

    Behaves_like&lt;UnsatisfiedSpecificationBehavior&gt; an_unsatisfied_specification;
}

[Subject(<span class="kwrd">typeof</span>(EmailSpecification), <span class="str">&quot;is satisfied&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_validating_an_email_address_without_a_domain
    : email_specification_specs
{
    Establish context = () =&gt;
        EmailAddress = <span class="str">&quot;one_two@&quot;</span>;

    Behaves_like&lt;UnsatisfiedSpecificationBehavior&gt; an_unsatisfied_specification;
}</pre>
<style type="text/css">

.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>In order to escape ‘context betrayal’, we’ve split up every context into a separate context/specification. In order to reduce the amount of effort caused by duplicate code, we stripped the context setup to the bare minimum (just a particular e-mail address in this case). The observations are isolated into MSpec behaviors which provides a very readable description of their outcome. Lets take a look at what is needed in order to get these <em>behaviors</em> to work.</p>

<p>But first lets take at look at the abstract base class that we’ve used for the context/specifications we’ve just shown.</p>

<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">abstract</span> <span class="kwrd">class</span> email_specification_specs
{
    Establish context = () =&gt;
    {
        SUT = <span class="kwrd">new</span> EmailSpecification();
    };

    Because of = () =&gt;
        Result = SUT.IsSatisfiedBy(EmailAddress);

    <span class="kwrd">protected</span> <span class="kwrd">static</span> Boolean Result;
    <span class="kwrd">protected</span> <span class="kwrd">static</span> String EmailAddress { get; set; }
    <span class="kwrd">protected</span> <span class="kwrd">static</span> EmailSpecification SUT { get; set; }
}</pre>

<p><style type="text/css">

.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style></p>

<p>&#160;</p>

<p>We abstracted as much as possible into this base class in order to remove duplication in the context/specifications. The creation of the subject-under-test and the calling of its <em>IsSatisfiedBy</em> method, but the important one is the declaration of the <em>Result</em> field. This field contains the outcome of the <em>IsSatisfiedBy</em> method. Finally, lets have a look at the behaviors themselves:</p>

<pre class="csharpcode">[Behaviors]
<span class="kwrd">public</span> <span class="kwrd">class</span> SatisfiedSpecificationBehavior
{
    <span class="kwrd">protected</span> <span class="kwrd">static</span> Boolean Result;
    
    It should_satisfy_the_specification = () =&gt;
        Result.ShouldBeTrue();
}

[Behaviors]
<span class="kwrd">public</span> <span class="kwrd">class</span> UnsatisfiedSpecificationBehavior
{
    <span class="kwrd">protected</span> <span class="kwrd">static</span> Boolean Result;

    It should_not_satisfy_the_specification = () =&gt;
        Result.ShouldBeFalse();
}</pre>
<style type="text/css">

.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>In order to create an MSpec behavior, we just have to create a separate class that we decorate with the <em>Behaviors</em> attribute. Also notice that we have the same declaration of the <em>Result</em> field. MSpec ensures that this field gets initialized with the value of the other <em>Result</em> field that is set in the base class of the context/specifications. Note that you don’t necessarily need to put this field in a base class. You can have that field in every context/specification if you’d like (not sure why) as long as the names match with the fields used in the defined behaviors.</p>

<p>I personally like the way how the MSpec contributors tried to solve testing the same logic with different input patterns and the syntax they provided to back this up.&#160;&#160; </p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/02/26/behaviors-with-mspec/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>MSpec and Auto Mocking</title>
		<link>http://elegantcode.com/2010/02/23/mspec-and-auto-mocking/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=mspec-and-auto-mocking</link>
		<comments>http://elegantcode.com/2010/02/23/mspec-and-auto-mocking/#comments</comments>
		<pubDate>Tue, 23 Feb 2010 20:38:54 +0000</pubDate>
		<dc:creator>Jan Van Ryswyck</dc:creator>
				<category><![CDATA[BDD]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/02/23/mspec-and-auto-mocking/</guid>
		<description><![CDATA[In my previous post, I explained how to get started with Machine.Specifications (or MSpec for short) and showed you how the syntax for context/specifications looks like when using this BDD framework. For this post, I want to show you how to use an auto mocking container (we’ll be using the one provided by StructureMap off [...]]]></description>
			<content:encoded><![CDATA[<p>In my <a href="http://elegantcode.com/2010/02/19/getting-started-with-machine-specifications-mspec/">previous post</a>, I explained how to get started with <a href="http://github.com/machine/machine.specifications">Machine.Specifications</a> (or MSpec for short) and showed you how the syntax for context/specifications looks like when using this BDD framework. For this post, I want to show you how to use an <a href="http://vanryswyckjan.blogspot.com/2008/01/automocking-container.html">auto mocking container</a> (we’ll be using the one provided by StructureMap off course).</p>  <p>We’ll use the same example as the one used in the previous post, but now we’ll deal with the message handler that makes a particular customer preferred.</p> <style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>  <pre class="csharpcode"><span class="rem">//</span>
<span class="rem">// Subject under test</span>
<span class="rem">//</span>
<span class="kwrd">public</span> <span class="kwrd">class</span> MakeCustomerPreferredMessageHandler
{
    <span class="kwrd">private</span> <span class="kwrd">readonly</span> ICustomerRepository&lt;ICanMakeCustomerPreferred&gt; _repository;

    <span class="kwrd">public</span> MakeCustomerPreferredMessageHandler(
        ICustomerRepository&lt;ICanMakeCustomerPreferred&gt; repository)
    {
        _repository = repository;
    }

    <span class="kwrd">public</span> <span class="kwrd">void</span> Handle(MakeCustomerPreferredMessage message)
    {
        var customer = _repository.Get(message.CustomerId);
        <span class="kwrd">if</span>(<span class="kwrd">null</span> == customer)
            <span class="kwrd">throw</span> <span class="kwrd">new</span> InvalidOperationException(
                <span class="str">&quot;No customer for specified identifier&quot;</span>);
        
        customer.MakePreferred();
        _repository.Save(customer);
    }
}</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>The <em>Customer</em> class implements a ‘<a href="http://martinfowler.com/bliki/RoleInterface.html">role interface’</a> called <em>ICanMakeCustomerPreferred</em>. We retrieve a customer from the repository and make it preferred. We throw an exception in case the customer cannot be found in the data store.</p>

<p>Here are the context/specifications for this easy example:</p>

<pre class="csharpcode">[Subject(<span class="str">&quot;Making a customer preferred&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_making_a_customer_preferred
    : context_specification&lt;MakeCustomerPreferredMessageHandler&gt;
{
    Establish context = () =&gt;
    {
        _message = <span class="kwrd">new</span> MakeCustomerPreferredMessage { CustomerId = 6412 };

        Repository.Stub(repository =&gt; repository.Get(_message.CustomerId))
            .Return(Customer);
    };

    Because of = () =&gt; 
        SUT.Handle(_message);
    
    It should_mark_the_customer_as_preferred = () =&gt;
        Customer.AssertWasCalled(customer =&gt; customer.MakePreferred());

    It should_save_the_customer_in_the_repository = () =&gt;
        Repository.AssertWasCalled(repository =&gt; repository.Save(Customer));

    <span class="kwrd">private</span> <span class="kwrd">static</span> ICanMakeCustomerPreferred Customer
    {
        get { <span class="kwrd">return</span> Dependency&lt;ICanMakeCustomerPreferred&gt;(); }
    }

    <span class="kwrd">private</span> <span class="kwrd">static</span> ICustomerRepository&lt;ICanMakeCustomerPreferred&gt; Repository
    {
        get { <span class="kwrd">return</span> Dependency&lt;ICustomerRepository&lt;ICanMakeCustomerPreferred&gt;&gt;(); }
    }

    <span class="kwrd">private</span> <span class="kwrd">static</span> MakeCustomerPreferredMessage _message;
}

[Subject(<span class="str">&quot;Making a customer preferred&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_making_an_unexisting_customer_preferred
    : context_specification&lt;MakeCustomerPreferredMessageHandler&gt;
{
    Establish context = () =&gt;   
    {
        _message = <span class="kwrd">new</span> MakeCustomerPreferredMessage() { CustomerId = 61544 };

        Dependency&lt;ICustomerRepository&lt;ICanMakeCustomerPreferred&gt;&gt;()
            .Stub(repository =&gt; repository.Get(_message.CustomerId))
            .Return(<span class="kwrd">null</span>);
    };

    Because of = () =&gt;
        _resultingException = Catch.Exception(() =&gt; SUT.Handle(_message));

    It should_result_in_an_error = () =&gt;
        _resultingException.ShouldBeOfType&lt;InvalidOperationException&gt;();

    <span class="kwrd">private</span> <span class="kwrd">static</span> MakeCustomerPreferredMessage _message;
    <span class="kwrd">private</span> <span class="kwrd">static</span> Exception _resultingException;
}</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>I want to point out that all fields and properties are made static. This is needed so that the anonymous methods can access them. I’m also using a base class for these specifications which I’ll show next. This base class uses an auto mocking container for providing the requested mocks and stubs through the <em>Dependency</em> and <em>Stub</em> methods. </p>

<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">abstract</span> <span class="kwrd">class</span> context_specification&lt;TSubjectUnderTest&gt;
    <span class="kwrd">where</span> TSubjectUnderTest : <span class="kwrd">class</span>
{
    <span class="kwrd">private</span> <span class="kwrd">static</span> IAutoMockingContainer&lt;TSubjectUnderTest&gt; _autoMockingContainer;
    <span class="kwrd">protected</span> <span class="kwrd">static</span> TSubjectUnderTest SUT { get; set; }

    Establish context = () =&gt;
    {
        _autoMockingContainer = <span class="kwrd">new</span> StructureMapAMC&lt;TSubjectUnderTest&gt;();
        SUT = _autoMockingContainer.Create();     
    };
    
    Cleanup stuff = () =&gt; 
    {
        SUT = <span class="kwrd">null</span>;
        _autoMockingContainer = <span class="kwrd">null</span>;
    };

    <span class="kwrd">protected</span> <span class="kwrd">static</span> TDependency Dependency&lt;TDependency&gt;()
        <span class="kwrd">where</span> TDependency : <span class="kwrd">class</span>
    {
        <span class="kwrd">return</span> _autoMockingContainer.GetMock&lt;TDependency&gt;();
    }

    <span class="kwrd">protected</span> <span class="kwrd">static</span> TStub Stub&lt;TStub&gt;()
        <span class="kwrd">where</span> TStub : <span class="kwrd">class</span>
    {
        <span class="kwrd">return</span> _autoMockingContainer.GetStub&lt;TStub&gt;();
    }
}

<span class="kwrd">public</span> <span class="kwrd">interface</span> IAutoMockingContainer&lt;TSubject&gt;
    <span class="kwrd">where</span> TSubject : <span class="kwrd">class</span>
{
    TSubject Create();
    TMock GetMock&lt;TMock&gt;() <span class="kwrd">where</span> TMock : <span class="kwrd">class</span>;
    TStub GetStub&lt;TStub&gt;() <span class="kwrd">where</span> TStub : <span class="kwrd">class</span>;
}

<span class="kwrd">public</span> <span class="kwrd">class</span> StructureMapAMC&lt;TSubject&gt; 
    : IAutoMockingContainer&lt;TSubject&gt;
    <span class="kwrd">where</span> TSubject : <span class="kwrd">class</span>
{
    <span class="kwrd">private</span> <span class="kwrd">readonly</span> RhinoAutoMocker&lt;TSubject&gt; _rhinoAutoMocker;

    <span class="kwrd">public</span> StructureMapAMC()
    {
        _rhinoAutoMocker = 
            <span class="kwrd">new</span> RhinoAutoMocker&lt;TSubject&gt;(MockMode.AAA);
    }

    <span class="kwrd">public</span> TSubject Create()
    {
        <span class="kwrd">return</span> _rhinoAutoMocker.ClassUnderTest;
    }

    <span class="kwrd">public</span> TMock GetMock&lt;TMock&gt;() 
        <span class="kwrd">where</span> TMock : <span class="kwrd">class</span>
    {
        <span class="kwrd">return</span> GetDependency&lt;TMock&gt;();
    }

    <span class="kwrd">public</span> TStub GetStub&lt;TStub&gt;() 
        <span class="kwrd">where</span> TStub : <span class="kwrd">class</span>
    {
        <span class="kwrd">return</span> GetDependency&lt;TStub&gt;();
    }

    <span class="kwrd">private</span> TDependency GetDependency&lt;TDependency&gt;() 
        <span class="kwrd">where</span> TDependency : <span class="kwrd">class</span>
    {
        <span class="kwrd">return</span> _rhinoAutoMocker.Get&lt;TDependency&gt;();
    }
}</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>Notice that I’m using the <em>Establish</em> and <em>Cleanup</em> delegates in the <em>context_specification</em> base class. This doesn’t prevent that these can be used again in derived context/specifications. MSpec ensures that the anonymous methods are called in the right order. This means that the <em>Establish</em> method of the base class is called before the <em>Establish</em> method of the derived context/specifications.&#160;&#160;&#160;&#160; </p>

<p>Absolutely no rocket science here, but I figured it might come in handy when you need it. For the next post I’ll try to demonstrate how to deal with reusable behaviors.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/02/23/mspec-and-auto-mocking/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Getting Started With Machine.Specifications (MSpec)</title>
		<link>http://elegantcode.com/2010/02/19/getting-started-with-machine-specifications-mspec/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=getting-started-with-machine-specifications-mspec</link>
		<comments>http://elegantcode.com/2010/02/19/getting-started-with-machine-specifications-mspec/#comments</comments>
		<pubDate>Fri, 19 Feb 2010 21:34:17 +0000</pubDate>
		<dc:creator>Jan Van Ryswyck</dc:creator>
				<category><![CDATA[BDD]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/02/19/getting-started-with-machine-specifications-mspec/</guid>
		<description><![CDATA[Its been a while since I evaluated and evolved my approach to BDD. The way I’ve been doing BDD up until now is described in this blog post which goes way back to 2008. Everyone has kind of their own style nowadays. Below you can find the code of two context/specifications for a method named [...]]]></description>
			<content:encoded><![CDATA[<p>Its been a while since I evaluated and evolved my approach to BDD. The way I’ve been doing BDD up until now is described in <a href="http://elegantcode.com/2008/10/25/refining-contextspecification-bdd-using-rhino-mocks-35/">this blog post</a> which goes way back to 2008. Everyone has kind of their own style nowadays. Below you can find the code of two context/specifications for a method named <em>MakePreferred</em> on a <em>Customer </em>class. This simple example clarifies the style that I’ve been following up until now.</p> <style type="text/css">


.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style><style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>  <pre class="csharpcode">[TestFixture]
<span class="kwrd">public</span> <span class="kwrd">class</span> When_making_a_regular_customer_preferred
    : ContextSpecification&lt;Customer&gt;
{
    <span class="kwrd">protected</span> <span class="kwrd">override</span> Customer Create_subject_under_test()
    {
        <span class="kwrd">return</span> <span class="kwrd">new</span> Customer(<span class="kwrd">new</span>[] { _order });
    }

    <span class="kwrd">protected</span> <span class="kwrd">override</span> <span class="kwrd">void</span> Establish_context()
    {
        _order = <span class="kwrd">new</span> Order(<span class="kwrd">new</span>[] { <span class="kwrd">new</span> OrderItem(12), 
                                   <span class="kwrd">new</span> OrderItem(16) });
                                   
        _totalAmountWithoutDiscount = _order.TotalAmount;
    }

    <span class="kwrd">protected</span> <span class="kwrd">override</span> <span class="kwrd">void</span> Because()
    {
        SUT.MakePreferred();
    }

    [Test]
    <span class="kwrd">public</span> <span class="kwrd">void</span> Then_the_customer_should_be_marked_as_preferred()
    {
        SUT.IsPreferred.ShouldBeTrue();
    }

    [Test]
    <span class="kwrd">public</span> <span class="kwrd">void</span> Then_a_ten_percent_discount_should_be_applied_to_all_outstanding_orders()
    {
        _order.TotalAmount.ShouldBeEqualTo(
            _totalAmountWithoutDiscount * 0.9);
    }

    <span class="kwrd">private</span> Order _order;
    <span class="kwrd">private</span> Double _totalAmountWithoutDiscount;
}

[TestFixture]
<span class="kwrd">public</span> <span class="kwrd">class</span> When_making_a_preferred_customer_preferred
    : ContextSpecification&lt;Customer&gt;
{
    <span class="kwrd">protected</span> <span class="kwrd">override</span> Customer Create_subject_under_test()
    {
        var customer = <span class="kwrd">new</span> Customer(<span class="kwrd">new</span>[] { _order });
        customer.MakePreferred();
        <span class="kwrd">return</span> customer;
    }

    <span class="kwrd">protected</span> <span class="kwrd">override</span> <span class="kwrd">void</span> Establish_context()
    {
        _order = <span class="kwrd">new</span> Order(<span class="kwrd">new</span>[] { <span class="kwrd">new</span> OrderItem(12), 
                                   <span class="kwrd">new</span> OrderItem(16) });
        _totalAmountWithoutDiscount = _order.TotalAmount;
    }

    <span class="kwrd">protected</span> <span class="kwrd">override</span> <span class="kwrd">void</span> Because()
    {
        SUT.MakePreferred();
    }

    [Test]
    <span class="kwrd">public</span> <span class="kwrd">void</span> Then_no_additional_discount_should_be_applied_to_the_outstanding_orders()
    {
        _order.TotalAmount.ShouldNotBeEqualTo(
            _totalAmountWithoutDiscount * 0.81);
    }

    <span class="kwrd">private</span> Order _order;
    <span class="kwrd">private</span> Double _totalAmountWithoutDiscount;
}

<span class="rem">//</span>
<span class="rem">// Subject under test</span>
<span class="rem">//</span>
<span class="kwrd">public</span> <span class="kwrd">class</span> Customer
{
    <span class="kwrd">private</span> <span class="kwrd">readonly</span> List&lt;Order&gt; _orders;
    <span class="kwrd">public</span> Boolean IsPreferred { get; <span class="kwrd">private</span> set; }

    <span class="kwrd">public</span> Customer(IEnumerable&lt;Order&gt; orders)
    {
        _orders = <span class="kwrd">new</span> List&lt;Order&gt;(orders);
    }

    <span class="kwrd">public</span> <span class="kwrd">void</span> MakePreferred()
    {
        <span class="kwrd">if</span>(IsPreferred)    
            <span class="kwrd">return</span>;
    
        IsPreferred = <span class="kwrd">true</span>;
        _orders.ForEach(order =&gt; order.ApplyDiscount(10));
    }
}</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>The bottom line of this example is that preferred customers get a 10 percent discount. Customers that are already preferred do not get an additional discount or otherwise we’re out of business ;-). </p>

<p>I’ve been pretty happy with this approach so far, although sometimes there were some quirks associated with this. So it was time for me to look beyond the horizon again, trying to look for ways to improve. </p>

<p><a href="http://github.com/machine/machine.specifications">Machine.Specifications</a> or MSpec for short is something that has been on my ‘cool-things-to-learn-list’ for quite some time now. As you will see later in this post, the syntax is a bit different as one would come to expect from a context/specification framework that targets the C# programming language. Its seems to be heavily inspired by Scott Bellware’s <a href="http://code.google.com/p/specunit-net/">SpecUnit framework</a> and <a href="http://rspec.info/">RSpec</a>.</p>

<p>Lets see how to set things up first. </p>

<p>The most obvious starting point is downloading the bits and bytes. You can grab the <a href="http://github.com/machine/machine.specifications">source code</a> from GitHub and build it or you can wuss out like I did and get the latest build from the <a href="http://teamcity.codebetter.com/login.html">TeamCity.CodeBetter.com</a> builder server (you can log on as a guest and search the artifacts for a latest build).&#160; </p>

<p>When you’re heavily addicted to <a href="http://www.testdriven.net/">TestDriven.NET</a> like I am, then its possible to keep using this wonderful Visual Studio add-in for running MSpec context/specifications. Just create a directory named <em>Machine.Specifications</em> in {$Program_Files}\TestDriven.NET 2.0 and copy the following files:</p>

<ul>
  <li>Machine.Specifications.dll</li>

  <li>Machine.Specifications.TDNetRunner.dll</li>

  <li>InstallTDNetRunner.bat</li>
</ul>

<ul>Run the InstallTDNetRunner.bat file and you’re able to run all MSpec context/specifications using TestDriven.NET.</ul>

<p>I also strongly encourage you to install the plugin for the Resharper test runner (if only to prevent some Resharper warnings later on). First step is to add a directory named <em>Plugins</em> to the <em>Bin</em> directory of Resharper ({$Program_Files}\JetBrains\ReSharper\v4.5\Bin\). Then create a directory named <em>Machine.Specifications</em> in the <em>Plugins</em> directory you just created and copy the following files:</p>

<ul>
  <li>Machine.Specifications.dll</li>

  <li>Machine.Specifications.ReSharperRunner.4.5.dll</li>

  <li>InstallResharperRunner.4.5.bat</li>
</ul>

<p>Run the InstallResharperRunner.4.5.bat file and you’re also able to run MSpec context/specifications using the Resharper test runner.</p>

<p>I’m not going to put this off any longer. Lets look at the code of the context/specifications shown earlier but completely revamped using the MSpec syntax:</p>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<pre class="csharpcode">[Subject(<span class="str">&quot;Making a customer preferred&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_a_regular_customer_is_made_preferred 
{
    Establish context = () =&gt;
    {
        _order = <span class="kwrd">new</span> Order(<span class="kwrd">new</span>[] { <span class="kwrd">new</span> OrderItem(12), 
                                   <span class="kwrd">new</span> OrderItem(16) });
        _totalAmountWithoutDiscount = _order.TotalAmount;

        SUT = <span class="kwrd">new</span> Customer(<span class="kwrd">new</span>[] { _order });
    };

    Because of = () =&gt; 
        SUT.MakePreferred();

    It should_mark_the_customer_as_preferred = () =&gt;
        SUT.IsPreferred.ShouldBeTrue();
        
    It should_apply_a_ten_percent_discount_to_all_outstanding_orders = () =&gt;
        _order.TotalAmount.ShouldEqual(_totalAmountWithoutDiscount * 0.9);      

    <span class="kwrd">private</span> <span class="kwrd">static</span> Customer SUT;
    
    <span class="kwrd">private</span> <span class="kwrd">static</span> Order _order;
    <span class="kwrd">private</span> <span class="kwrd">static</span> Double _totalAmountWithoutDiscount;
}

[Subject(<span class="str">&quot;Making a customer preferred&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_a_preferred_customer_is_made_preferred
{
    Establish context = () =&gt;
    {
        _order = <span class="kwrd">new</span> Order(<span class="kwrd">new</span>[] { <span class="kwrd">new</span> OrderItem(12), 
                                   <span class="kwrd">new</span> OrderItem(16) });
        _totalAmountWithoutDiscount = _order.TotalAmount;

        SUT = <span class="kwrd">new</span> Customer(<span class="kwrd">new</span>[] { _order });
        SUT.MakePreferred();
    };

    Because of = () =&gt;
        SUT.MakePreferred();

    It should_apply_no_additional_discount_to_the_outstanding_orders = () =&gt; 
        _order.TotalAmount.ShouldNotEqual(_totalAmountWithoutDiscount * 0.81);

    <span class="kwrd">private</span> <span class="kwrd">static</span> Customer SUT;

    <span class="kwrd">private</span> <span class="kwrd">static</span> Order _order;
    <span class="kwrd">private</span> <span class="kwrd">static</span> Double _totalAmountWithoutDiscount;
}</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>I warned you about the syntax, didn’t I :-). It only took me a couple of seconds to get used to this syntax but now I’m completely hooked. Instead of using methods and attributes, MSpec utilizes delegates and anonymous methods. But there’s more. </p>

<p>When using <a href="http://www.nunit.com/index.php">NUnit</a> for writing context/ specifications, the <em>Establish_context</em> and <em>Because</em> methods of the example shown earlier is executed before every observation (test). With MSpec, the <em>Establish</em> and <em>Because</em> anonymous methods are executed only once for every context no matter how many observations a particular context class contains. Big difference? Well, at first glance not but on second hand it does make <a href="http://elegantcode.com/2008/12/30/dont-sell-out-on-the-context-dude/">selling out on the context</a> a bit more difficult as it will probably blow up in your face sooner than later. You can force MSpec to execute the <em>Establish</em> and <em>Because</em> anonymous methods before every observation by applying the <em>SetupForEachSpecification</em> attribute to the context class, but I strongly encourage you to stay away from that unless absolutely needed.</p>

<p>Also notice that the fields in the contexts are now all static. This is needed so that the anonymous methods can access those.&#160;&#160;&#160;&#160;&#160; </p>

<p>Running these context/specifications using TestDriven.NET yields the following output in the output window of Visual Studio:</p>

<blockquote>
  <p><font face="Arial">Making a customer preferred, when a regular customer is made preferred
      <br />» should mark the customer as preferred

      <br />» should apply a ten percent discount to all outstanding orders</font></p>

  <p><font face="Arial">Making a customer preferred, when a preferred customer is made preferred
      <br />» should apply no additional discount to the outstanding orders</font></p>
</blockquote>

<p>What’s not to like? Well, the only downside so far is that Resharper was giving me some warnings about classes and fields not being used etc. … . Many of those warnings disappeared by registering the MSpec plugin for the Resharper test runner as I explained earlier.</p>

<p>So far, so good. I’ve got two more posts coming up on MSpec, so stay tuned.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/02/19/getting-started-with-machine-specifications-mspec/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Unity/Moq &#8211; AutoMocker or AutoMockingContainer</title>
		<link>http://elegantcode.com/2010/01/03/unitymoq-automocker-or-automockingcontainer/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=unitymoq-automocker-or-automockingcontainer</link>
		<comments>http://elegantcode.com/2010/01/03/unitymoq-automocker-or-automockingcontainer/#comments</comments>
		<pubDate>Sun, 03 Jan 2010 16:52:33 +0000</pubDate>
		<dc:creator>Jason Jarrett</dc:creator>
				<category><![CDATA[TDD]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Tools and Utilities]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/01/03/unitymoq-automocker-or-automockingcontainer/</guid>
		<description><![CDATA[What is an Auto Mocking Container? This post started to get a little long, so I won’t re-explain the concept. Joshua Flanagan wrote a nice overview at his Los Techies blog: Auto mocking Explained. My post is mainly here to describe the Unity version of an automocking container I threw together. In Jan 2009 I [...]]]></description>
			<content:encoded><![CDATA[<h4>What is an Auto Mocking Container?</h4>  <p>This post started to get a little long, so I won’t re-explain the concept.</p>  <p><a href="http://www.lostechies.com/blogs/joshuaflanagan/default.aspx">Joshua Flanagan</a> wrote a nice overview at his <a href="http://www.lostechies.com/">Los Techies</a> blog: <a href="http://www.lostechies.com/blogs/joshuaflanagan/archive/2009/02/03/auto-mocking-explained.aspx"><strong>Auto mocking Explained</strong></a>.</p>  <p>My post is mainly here to describe the Unity version of an automocking container I threw together.</p>  <h4>In Jan 2009 I blogged about my initial version of the Unity AutoMocker - Why am I blogging about it again?</h4>  <p>I originally wrote the AutoMocker for the Unity container a year ago (Jan 2009, in Silverlight), and finally got around to placing the code up in the <a href="http://code.google.com/p/moq-contrib/">moq-contrib</a> project in June of 2009.</p>  <p>I’m writing another post today in hopes to:</p>  <ol>   <li>Get some feedback on how this little snippet of code should continue. </li>    <li>Give a little more how-to/example code </li>    <li>Describe some updates I made since I originally created it.&#160; </li> </ol>  <h4>Where can I get it?</h4>  <p><strong>This is one part where I’d appreciate some feedback.</strong></p>  <p>I have two slightly different versions out there (currently).</p>  <p>I have one version at the <a href="http://code.google.com/p/elegantcode/source/browse/#svn/trunk/Coders/JasonJarrett/UnityAutoMocker">ElegantCode</a> repository where I was working on it, and the other I threw up at <a href="http://code.google.com/p/moq-contrib/">moq-contrib</a>.</p>  <p>The core of the UnityAutoMockContainer is the same in both places, it’s how the tests are separated out that differ.</p>  <p>In the <a href="http://code.google.com/p/elegantcode/source/browse/#svn/trunk/Coders/JasonJarrett/UnityAutoMocker">ElegantCode repository</a> it’s an all in one self contained single file (that you can copy into your own test project(s)). You can then setup a single test in your own testing framework that runs all internal automocker tests (in case you need to modify it yourself, and don’t want to break any existing functionality). EX: test</p>  <pre class="brush: csharp;">[Test]
public void Should_run_all_UnityAutoMockContainer_internal_tests()
{
    Moq.AutoMocking.SelfTesting.UnityAutoMockContainerFixture
        .RunAllTests(Console.WriteLine);
}</pre>

<p>I kind of like this format as it makes it easy to port between test libraries. Can’t say I like having the tests in the same file as the core, but it certainly is not a large chunk of code (so far) so it’s relatively small to maintain and definitely easier to manage as a single .cs file than another assembly (which would have to be version dependent on both Unity and Moq).</p>

<p>The <a href="http://code.google.com/p/moq-contrib/">moq-contrib</a> is definitely where I think this helper should end up (and it is there). I just happened to break the tests out into the Silverlight test project and the core is alone in a file. </p>

<p>It’s current state isn’t as easy to copy to a test library (Silverlight/Desktop/Unity 1.2/Unity 2.0) as the one at <a href="http://elegantcode.com/">ElegantCode</a>. <strong>What does anyone think?</strong> Should I put them all together in one file?</p>

<p>However it ends up (1. all in one file or two (1 test) (1 core)) it will continue to be maintained on the <a href="http://code.google.com/p/moq-contrib/">moq-contrib</a> project.</p>

<h4>What is the high level API of the container?</h4>

<p>It’s pretty simple, (currently) there are four methods on the container.</p>

<p><strong>Two for registering items with the container</strong>. Say you want to register an already created instance, or say you want to map an interface to a concrete class and _not_ have the container generate mocks automatically for special cases. </p>

<p>And <strong>two for pulling items out of the container</strong>. Whether you want a instance of T or a Mock&lt;T&gt;, it gives you ways to retrieve both.</p>

<blockquote>
  <p><a href="http://elegantcode.com/wp-content/uploads/2010/01/image.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://elegantcode.com/wp-content/uploads/2010/01/image_thumb.png" width="396" height="106" /></a> </p>
</blockquote>

<h4>How can I setup my own registrations with the container? </h4>

<p>Say I don’t want to have the container generate mocks for specific items and I want to supply specific configuration to the UnityContainer.</p>

<blockquote>
  <p>public UnityAutoMockContainer RegisterInstance&lt;TService&gt;(TService instance)</p>

  <p>public UnityAutoMockContainer Register&lt;TService, TImplementation&gt;() 
    <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; where TImplementation : TService</p>
</blockquote>

<p><strong>Note</strong>: both of these registration methods return the container itself so you can fluently stack registration. <strong>EX:</strong></p>

<pre class="brush: csharp;">AutoMockContainer
    .Register&lt;IServiceA, ServiceA&gt;()
    .Register&lt;IServiceB, ServiceB&gt;();</pre>

<p><strong>Let me know</strong>: I haven’t tested or played around with how this automocking container deals with any container specific xml configuration… So although I don’t think you should probably have that in a test assembly (stuff happens). Let me know if there are any issues.</p>

<h4>How do I get items out of the container?</h4>

<p>First is the Resolve&lt;T&gt;(). It will pull an item T out of the container. (Creating it if not already existing)</p>

<blockquote>
  <p>public T Resolve&lt;T&gt;()</p>
</blockquote>

<p>When T is an interface Resolve&lt;T&gt; (unless you setup registration specifically with the container) should return basically “(new Mock&lt;T&gt;()).Object”</p>

<p>When T is a concrete Class, the container should return an instance of T and any of it’s dependencies will be satisfied by mocks. (Note that T will not be any sort of mocked instance of T, unless you used the GetMock&lt;T&gt; as described below first)</p>

<blockquote>
  <p>public Mock&lt;T&gt; GetMock&lt;T&gt;() where T : class</p>
</blockquote>

<p>When T is an interface GetMock&lt;T&gt; should return basically “(new Mock&lt;T&gt;())” </p>

<p>When T is a concrete Class, the container should return a new Mock&lt;T&gt;() and any of it’s dependencies will be satisfied by mocks.</p>

<h4>How do I use the UnityAutoMockContainer?</h4>

<p>It’s pretty basic, you first create an instance of the UnityAutoMockContainer, and from there you can ask it for mocks of an (Interface, Class, or Abstract Class).</p>

<p>If you request an instance of a concrete class, or abstract class, the UnityAutoMockContainer will stuff mocks in for any constructor dependencies of your concrete class (if it can). You can then request from the container those same dependencies one at a time and either apply mocking setups or verifications.</p>

<blockquote>
  <p><strong>NOTE:</strong> Anything the container creates will live as a singleton instance in the container. So any other requests from the container will always return the originally created instance. Therefore, each distinct scenario in a test suite should have their own instances of the container.</p>
</blockquote>

<p>Below his an example of how you can leverage the container in some tests. Given this base fixture class…</p>

<pre class="brush: csharp;">public class FixtureBase
{
    private readonly UnityAutoMockContainer _autoMockContainer = new UnityAutoMockContainer();

    protected UnityAutoMockContainer AutoMockContainer
    {
        get { return _autoMockContainer; }
    }

    [TestFixtureSetUp]
    public void SetupContext_ALL()
    {
        Before_all_tests();
        Because();
    }

    [TestFixtureTearDown]
    public void TearDownContext_ALL()
    {
        After_all_tests();
    }

    protected virtual void Before_all_tests()
    {
    }

    protected virtual void Because()
    {
    }

    protected virtual void After_all_tests()
    {
    }
}</pre>

<p>If I were given the following system to test.</p>

<pre class="brush: csharp;">public interface IServiceA { void RunA(); }
public interface IServiceB { void RunB(); }

public class TestComponent
{
    public TestComponent(IServiceA serviceA, IServiceB serviceB)
    {
        ServiceA = serviceA;
        ServiceB = serviceB;
    }

    public IServiceA ServiceA { get; private set; }
    public IServiceB ServiceB { get; private set; }

    public void RunAll()
    {
        if (!HowDidItGo())
            return;
        ServiceA.RunA();
        ServiceB.RunB();
    }

    public virtual bool HowDidItGo()
    {
        // some really nasty untestable code
        return true;
    }
}</pre>

<p>The below example demonstrates simply verifying some behavior on the mocked dependencies of the system under test.</p>

<pre class="brush: csharp;">[TestFixture]
public class Example__how_to_pull_items_from_the_UnityAutoMockContainer_when_verifying_behavior_after_an_action_was_taken 
    : FixtureBase
{
    private TestComponent _testComponent;

    protected override void Before_all_tests()
    {
        base.Before_all_tests();
        _testComponent = AutoMockContainer.Resolve&lt;TestComponent&gt;();
    }

    protected override void Because()
    {
        _testComponent.RunAll();
    }

    [Test]
    public void Should_run_ServiceA_RunA()
    {
        AutoMockContainer
            .GetMock&lt;IServiceA&gt;()
            .Verify(v =&gt; v.RunA(), Times.Once());
    }

    [Test]
    public void Should_run_ServiceB_RunB()
    {
        AutoMockContainer
            .GetMock&lt;IServiceB&gt;()
            .Verify(v =&gt; v.RunB(), Times.Once());
    }
}</pre>

<p>Next, you may have noticed that the system under test had a complicated internal method (that may not necessarily be testable). You can use the AutoMocker to create the system under test as a Mock itself, so we can override some of the behavior. Here’s how you could quickly do that. </p>

<blockquote>
  <p><strong>Aside</strong>: I’m not saying this is a good practice or aids in good component design, just saying it’s possible</p>
</blockquote>

<pre class="brush: csharp;">[TestFixture]
public class Example__how_to_use_the_UnityAutoMockContainer_to_override_a_method_on_the_SystemUnderTest_to_test_a_certain_behavior
    : FixtureBase
{

    private TestComponent _testComponent;

    protected override void Before_all_tests()
    {
        base.Before_all_tests();
        var mockTestComponent = AutoMockContainer.GetMock&lt;TestComponent&gt;();

        mockTestComponent
            .Setup(s =&gt; s.HowDidItGo())
            .Returns(false);

        _testComponent = mockTestComponent.Object;
    }

    protected override void Because()
    {
        _testComponent.RunAll();
    }

    [Test]
    public void Should_run_ServiceA_RunA()
    {
        AutoMockContainer
            .GetMock&lt;IServiceA&gt;()
            .Verify(v =&gt; v.RunA(), Times.Never());
    }

    [Test]
    public void Should_run_ServiceB_RunB()
    {
        AutoMockContainer
            .GetMock&lt;IServiceB&gt;()
            .Verify(v =&gt; v.RunB(), Times.Never());
    }
}</pre>

<p>&#160;</p>

<p>It’s amazing how much redundant test setup code this little helper has saved me in my tests. I hope others can find some use with this as well.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/01/03/unitymoq-automocker-or-automockingcontainer/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>StatLight &#8211; Goes Open Source</title>
		<link>http://elegantcode.com/2009/12/10/statlight-goes-open-source/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=statlight-goes-open-source</link>
		<comments>http://elegantcode.com/2009/12/10/statlight-goes-open-source/#comments</comments>
		<pubDate>Fri, 11 Dec 2009 03:26:55 +0000</pubDate>
		<dc:creator>Jason Jarrett</dc:creator>
				<category><![CDATA[Esoterica]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[TDD]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Tools and Utilities]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/12/10/statlight-goes-open-source/</guid>
		<description><![CDATA[Although I made a very minor attempt at making StatLight a “for-sale” product, I knew when I started that open-source was most likely going to be my long term path for StatLight. What is it? (Silverlight Testing Automation Tool) StatLight is a tool developed for automating the setup, running, and gathering results of Silverlight unit [...]]]></description>
			<content:encoded><![CDATA[Although I made a very minor attempt at making <a href="http://statlight.net" target="_blank">StatLight</a> a “for-sale” product, I knew when I started that open-source was most likely going to be my long term path for <a href="http://statlight.net" target="_blank">StatLight</a>.
<h5>What is it? (Silverlight Testing Automation Tool)</h5>
StatLight is a tool developed for automating the setup, running, and gathering results of Silverlight unit tests. StatLight helps to speed up the feedback cycles while practicing<a href="http://en.wikipedia.org/wiki/Test-driven_development"> TDD</a>/<a href="http://en.wikipedia.org/wiki/Behavior_Driven_Development">BDD</a>/(insert your test style here) during Silverlight development.
<h5>Where can I get StatLight?</h5>
<a href="http://StatLight.CodePlex.com">http://StatLight.CodePlex.com</a>
<h4>Happy Coding !!!</h4>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/12/10/statlight-goes-open-source/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Wrapping up the StructureMap Automocking Container</title>
		<link>http://elegantcode.com/2009/11/30/wrapping-up-the-structuremap-automocking-container/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=wrapping-up-the-structuremap-automocking-container</link>
		<comments>http://elegantcode.com/2009/11/30/wrapping-up-the-structuremap-automocking-container/#comments</comments>
		<pubDate>Mon, 30 Nov 2009 07:21:43 +0000</pubDate>
		<dc:creator>Richard Cirerol</dc:creator>
				<category><![CDATA[TDD]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Unit Testing]]></category>
		<category><![CDATA[StructureMap; Automocking; MSpec;]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/11/30/wrapping-up-the-structuremap-automocking-container/</guid>
		<description><![CDATA[<p><font color="#804040"><strong>UPDATE</strong>: I apologize…the original wrapper did not allow injected dependencies.&#160; I have fixed this bug and updated the sample.</font></p> I have been using StructureMap.AutoMocking with MSpec (Machine.Specifications) and Rhino.Mocks for a few months now.  Although I am very comfortable with the patterns that emerge from using the frameworks together, introducing StructureMap.Automocking to other developers is sometimes challenging. I decided to wrap the details of the container to make the intention clearer and explanation easier.  I have started using this wrapper in my projects, and have found it makes building up specifications more efficient in my daily coding.]]></description>
			<content:encoded><![CDATA[<span style="color: #804040;"><strong>UPDATE</strong>: I apologize…the original wrapper did not allow injected dependencies.  I have fixed this bug and updated the sample.</span>

I have been using StructureMap.AutoMocking with MSpec (Machine.Specifications) and Rhino.Mocks for a few months now.  Although I am very comfortable with the patterns that emerge from using the frameworks together, introducing StructureMap.Automocking to other developers is sometimes challenging.

When viewing a specification or test set up with the Rhino.Mocks or Moq automocking container, what is being tested is not readily apparent.  Once the concept is explained and demonstrated, these same developers seem to have no issue with maintaining the specifications/tests.

I decided to wrap the details of the container to make the intention clearer and explanation easier.  I have started using this wrapper in my projects, and have found it makes building up specifications more efficient in my daily coding.

Let me know whether this is useful to you, or how it could be made more useful.
<h4>The Examples</h4>
Let’s contrive an example.  We’ll say we have a coffee machine that grinds its own beans before brewing. However, the hopper has to have beans before starting the grind.  Here is the basic specification:
<table border="1" cellspacing="0" cellpadding="2" width="533">
<tbody>
<tr>
<td width="117" valign="top">Action/Behavior</td>
<td width="414" valign="top">Prepare coffee grounds for 12 cups of coffee</td>
</tr>
<tr>
<td rowspan="2" width="117" valign="top">Expectations</td>
<td width="414" valign="top">Should check that hopper has beans (mock returns true)</td>
</tr>
<tr>
<td width="414" valign="top">Because hopper has beans, should ask grinder to grind enough beans for 12 cups of coffee</td>
</tr>
</tbody></table>
We could start without a container, using Rhino.Mocks to build up the CoffeeMachine dependencies manually:
<pre class="brush: csharp;">[Subject(typeof(CoffeeMachine),"using vanilla Rhino.Mocks")]
public class Example01_when_preparing_coffee_grounds
{
    Establish context = () =&gt;
        {
            Grinder = MockRepository.GenerateMock&lt;IGrinder&gt;();
            Hopper = MockRepository.GenerateMock&lt;IHopper&gt;();
            Hopper.Expect(x =&gt; x.HasBeans()).Return(true);
            CoffeeMachine = new CoffeeMachine(Grinder, Hopper);
        };

    Because of = () =&gt; _coffeeMachine.PrepareCoffeeGrounds(12);

    It should_check_if_hopper_has_beans = () =&gt; Hopper.VerifyAllExpectations();
    It should_grind_coffee = () =&gt; Grinder.AssertWasCalled(x =&gt; x.Grind(12));

    static IGrinder Grinder;
    static IHopper Hopper;
    static CoffeeMachine CoffeeMachine;
}</pre>
For those of you not familiar with the MSpec style, please refer to the following posts:
<ul>
	<li><a href="http://blog.wekeroad.com/blog/make-bdd-your-bff-2/" target="_blank">Make BDD Your BFF</a></li>
	<li><a href="http://www.lostechies.com/blogs/seanbiefeld/archive/2009/08/25/step-by-step-to-using-machine-specifications-with-resharper.aspx" target="_blank">Step by Step to Using MSpec (Machine.Specifications) with ReSharper</a></li>
	<li><a href="http://elegantcode.com/2009/07/05/mspec-take-2/" target="_blank">MSpec - Take 2</a></li>
	<li><a href="http://marcinobel.com/index.php/mspec-bdd-installer/" target="_blank">MSpec BDD framework installer</a></li>
	<li><strong>Updated! </strong>From the <a href="http://blog.cwa.me.uk/2009/11/30/the-morning-brew-487/" target="_blank">Morning Brew #487</a>: BDD with MSpec and Rhino Auto Mocks, parts  <a href="http://telldontask.wordpress.com/2009/11/10/bdd-with-mspec-and-rhino-auto-mocks/" target="_blank">1</a>, <a href="http://telldontask.wordpress.com/2009/11/19/bdd-with-mspec-and-rhino-auto-mocks-part-2/" target="_blank">2</a>, and <a href="http://telldontask.wordpress.com/2009/11/29/bdd-with-mspec-and-rhino-auto-mocks-part-3/" target="_blank">3</a>
Here is the same specification using the RhinoAutoMocker&lt;T&gt; class provided by StructureMap.AutoMocking:</li>
</ul>
<pre class="brush: csharp;">[Subject(typeof(CoffeeMachine),"using RhinoAutoMocker&lt;CoffeeMachine&gt;")]
public class Example02_when_preparing_coffee_grounds
{
    Establish context = () =&gt;
        {
            CoffeeMachine = new RhinoAutoMocker&lt;CoffeeMachine&gt;();
            Grinder = CoffeeMachine.Get&lt;IGrinder&gt;();
            Hopper = CoffeeMachine.Get&lt;IHopper&gt;();
            Hopper.Expect(x =&gt; x.HasBeans()).Return(true);
        };

    Because of = () =&gt; v.ClassUnderTest.PrepareCoffeeGrounds(12);

    It should_check_if_hopper_has_beans = () =&gt; Hopper.VerifyAllExpectations();
    It should_grind_coffee = () =&gt; Grinder.AssertWasCalled(x =&gt; x.Grind(12));

    static IGrinder Grinder;
    static IHopper Hopper;
    static RhinoAutoMocker&lt;CoffeeMachine&gt; CoffeeMachine;
}</pre>
Although I think this looks cleaner, the initialization of CoffeeMachine causes some confusion. Unfortunately, a common question would be, “Is RhinoAutoMocker&lt;CoffeeMachine&gt; creating a mocked version of CoffeeMachine?” Well, not exactly.

RhinoAutoMocker is an implementation of the AutoMocker base class which uses StructureMap to fill dependencies.  The RhinoAutoMocker implementation of the container uses Rhino.Mocks to generate all of dependencies of the target class, whereas the MoqAutoMocker implementation uses Moq.  (Optionally, the target class can be partially mocked in order to further isolate behavior.)  We then retrieve the class under test (in this case, CoffeeMachine) and its dependencies (IGrinder and IHopper) from the container for use.

If you do not need to setup any expectations in the specification, there is no need to retrieve the dependency from the container.  However, in this specification, we need both dependencies.

<em>(Incidentally, I do not like the ClassUnderTest name.  I may end up changing this to Instance, ClassInstance, TargetClass, or something similar.  Suggestions?)</em>

By moving the initialization of the RhinoAutoMocker to a base class, some of the chattiness of the context can be hidden.
<ul>
<pre class="brush: csharp;">[Subject(typeof(CoffeeMachine),"using RhinoAutoMocker base")]
public class Example03_when_preparing_coffee_grounds : with_rhinoautomocker
{
    Establish context = () =&gt; Hopper.Expect(x =&gt; x.HasBeans()).Return(true);

    Because of = () =&gt; CoffeeMachine.ClassUnderTest.PrepareCoffeeGrounds(12);

    It should_check_if_hopper_has_beans = () =&gt; Hopper.VerifyAllExpectations();
    It should_grind_coffee = () =&gt; Grinder.AssertWasCalled(x =&gt; x.Grind(12));

}

[Subject("using RhinoAutoMocker&lt;T&gt;")]
public class with_rhinoautomocker
{
    protected static IGrinder Grinder;
    protected static IHopper Hopper;
    protected static RhinoAutoMocker&lt;CoffeeMachine&gt; CoffeeMachine;

    Establish context = () =&gt;
    {
        CoffeeMachine = new RhinoAutoMocker&lt;CoffeeMachine&gt;();
        Grinder = CoffeeMachine.Get&lt;IGrinder&gt;();
        Hopper = CoffeeMachine.Get&lt;IHopper&gt;();
    };
}</pre>
However, we are still initializing and accessing the class in a less than optimal manner.To make the usage of the container a little more seamless, I decided to create a wrapper and factory for the AutoMocker.  Setup of the dependencies and expectations are done through an AutoMocker wrapper object.  The instance of the class under test is accessed through a ClassUnderTest object.
<h4>The Result</h4>
The specification (and base class) now look like this:
<pre class="brush: csharp;">[Subject(typeof(CoffeeMachine),"using coffee machine base")]
public class Example05_when_preparing_coffee_grounds : with_coffee_machine
{
    Establish context = () =&gt; Hopper.Expect(x =&gt; x.HasBeans()).Return(true);

    Because of = () =&gt; ClassUnderTest.PrepareCoffeeGrounds(12);

    It should_check_if_hopper_has_beans = () =&gt; Hopper.VerifyAllExpectations();
    It should_grind_coffee = () =&gt; Grinder.AssertWasCalled(x =&gt; x.Grind(12));
}

[Subject("using SpecificationFor&lt;CoffeeMachine&gt;")]
public class with_coffee_machine : SpecificationFor&lt;CoffeeMachine&gt;
{
    protected static IGrinder Grinder;
    protected static IHopper Hopper;

    public with_coffee_machine
    {
        Grinder = AutoMocker.Get&lt;IGrinder&gt;();
        Hopper = AutoMocker.Get&lt;IHopper&gt;();
    }
}</pre>
As you can see, the base class inherits from SpecificationFor&lt;T&gt;.  The default constructor uses Rhino.Mocks(MockMode.AAA) to generate the dependencies.  It then exposes a AutoMocker object, which is just the wrapper around the AutoMocker base class.  It also exposes a ClassUnderTest object.  If I didn’t need to use the dependencies, I could make the <em>Example05_when_preparing_coffee_grounds</em> class inherit from <em>SpecificationFor&lt;CoffeeMachine&gt; </em>instead of inheriting from the base class<em>.</em>
<h4>The Code</h4>
I have included the code for the wrapper below for your review.  The code and six examples are available on my <a href="http://codeprogression.googlecode.com/svn/trunk/CodeProgression.Framework.Testing" target="_blank">Google code repository</a>. The repository also includes an example using the MoqAutoMocker.  All the examples have the same assertions, but are built up using the different techniques.
<pre class="brush: csharp;">namespace CodeProgression.Framework.Testing
{
    public abstract class SpecificationFor&lt;T&gt; where T: class
    {
        protected static ClassUnderTest&lt;T&gt; Factory;

        // UPDATE 2009-12-21:
        //   Moved initialization here
        protected static T ClassUnderTest {get {return AutoMocker.Instance;} }

        protected SpecificationFor()
        {
            AutoMocker = AutoMockFactory.CreateTarget&lt;T&gt;();

            // UPDATE 2009-12-21:
            //    Initializing here prevented injected dependencies!
            // AutoMocker.PartialMockTheClassUnderTest();
            // ClassUnderTest = AutoMocker.Instance;
        }

        protected SpecificationFor(AutoMockType type)
        {
            AutoMocker = AutoMockFactory.CreateTarget&lt;T&gt;(type);

            // UPDATE 2009-12-21:
            // Initializing here prevented injected dependencies!
            // AutoMocker.PartialMockTheClassUnderTest();
            // ClassUnderTest = AutoMocker.Instance;
        }
    }

    public static class AutoMockFactory
    {
        public static ClassUnderTest&lt;TARGETCLASS&gt; CreateTarget&lt;TARGETCLASS&gt;() where TARGETCLASS : class
        {
            return CreateTarget&lt;TARGETCLASS&gt;(AutoMockType.RhinoMocksAAA);
        }

        public static ClassUnderTest&lt;TARGETCLASS&gt; CreateTarget&lt;TARGETCLASS&gt;(AutoMockType framework) where TARGETCLASS : class
        {
            AutoMocker&lt;TARGETCLASS&gt; mocker;
            ServiceLocator serviceLocator;
            switch (framework)
            {
                case AutoMockType.RhinoMocksAAA:
                    mocker = new RhinoAutoMocker&lt;TARGETCLASS&gt;(MockMode.AAA);
                    serviceLocator = new RhinoMocksAAAServiceLocator();
                    break;
                case AutoMockType.RhinoMocksClassic:
                    mocker = new RhinoAutoMocker&lt;TARGETCLASS&gt;(MockMode.RecordAndReplay);
                    serviceLocator = new RhinoMocksClassicServiceLocator();
                    break;
                case AutoMockType.Moq:
                    mocker = new MoqAutoMocker&lt;TARGETCLASS&gt;();
                    serviceLocator = new MoqServiceLocator();
                    break;
                default:
                    throw new ArgumentOutOfRangeException("framework");
            }
            return new ClassUnderTest&lt;TARGETCLASS&gt;(mocker, serviceLocator);
        }
    }

    public enum AutoMockType
    {
        Moq,
        RhinoMocksAAA,
        RhinoMocksClassic
    }

    public class ClassUnderTest&lt;TARGETCLASS&gt; where TARGETCLASS : class
    {
        readonly IAutoMocker&lt;TARGETCLASS&gt; _mocker;
        readonly ServiceLocator _serviceLocator;

        public ClassUnderTest(IAutoMocker&lt;TARGETCLASS&gt; mocker, ServiceLocator serviceLocator)
        {
            _mocker = mocker;
            _serviceLocator = serviceLocator;
        }

        public AutoMockedContainer Container
        {
            get { return _mocker.Container; }
        }

        public TARGETCLASS Instance
        {
            get { return _mocker.ClassUnderTest; }
        }

        public void MockObjectFactory()
        {
            _mocker.MockObjectFactory();
        }

        public void PartialMockTheClassUnderTest()
        {
            _mocker.PartialMockTheClassUnderTest();
        }

        public T Get&lt;T&gt;() where T : class
        {
            return _mocker.Get&lt;T&gt;();
        }

        public void Inject(Type pluginType, object stub)
        {
            _mocker.Inject(pluginType, stub);
        }

        public void Inject&lt;T&gt;(T target)
        {
            _mocker.Inject(target);
        }

        public T AddAdditionalMockFor&lt;T&gt;() where T : class
        {
            return _mocker.AddAdditionalMockFor&lt;T&gt;();
        }

        public void UseConcreteClassFor&lt;T&gt;()
        {
            _mocker.UseConcreteClassFor&lt;T&gt;();
        }

        public T[] CreateMockArrayFor&lt;T&gt;(int count) where T : class
        {
            return _mocker.CreateMockArrayFor&lt;T&gt;(count);
        }

        public void InjectArray&lt;T&gt;(T[] stubs)
        {
            _mocker.InjectArray(stubs);
        }

        public T Mock&lt;T&gt;() where T : class
        {
            return _serviceLocator.Service&lt;T&gt;();
        }
        public object Mock(Type serviceType)
        {
            return _serviceLocator.Service(serviceType);
        }
        public T PartialMock&lt;T&gt;() where T : class
        {
            return _serviceLocator.PartialMock&lt;T&gt;();
        }
    }
}</pre>
</ul>
<script type="text/javascript">// <![CDATA[
 var cirerolGaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."); document.write(unescape("%3Cscript src='" + cirerolGaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
// ]]&gt;</script>

<script type="text/javascript">// <![CDATA[
 var cirerolPageTracker = _gat._getTracker('UA-8257866-3'); cirerolPageTracker._initData(); cirerolPageTracker._trackPageview();
// ]]&gt;</script>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/11/30/wrapping-up-the-structuremap-automocking-container/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Integration Test Brought to you by Powershell &amp; NUnit &#8211; with a Little Specification Syntax for Flavoring</title>
		<link>http://elegantcode.com/2009/10/25/integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring</link>
		<comments>http://elegantcode.com/2009/10/25/integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring/#comments</comments>
		<pubDate>Mon, 26 Oct 2009 05:00:40 +0000</pubDate>
		<dc:creator>Jason Jarrett</dc:creator>
				<category><![CDATA[Esoterica]]></category>
		<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/10/25/integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring/</guid>
		<description><![CDATA[One of the tools I’ve used the last half of a year and really enjoyed is the C# specification extension methods when writing unit test assertions. If you’re looking for a little more background on the topic, I wrote about Fluent Specification Extensions in a past blog. Recently I wanted to execute a PowerShell script [...]]]></description>
			<content:encoded><![CDATA[One of the tools I’ve used the last half of a year and really enjoyed is the C# specification extension methods when writing unit test assertions. If you’re looking for a little more background on the topic, I wrote about <a href="http://staxmanade.blogspot.com/2009/02/fluent-specification-extensions.html">Fluent Specification Extensions</a> in a past blog.

Recently I wanted to execute a PowerShell script to do some automated <a href="http://en.wikipedia.org/wiki/Functional_testing">functional testing</a>. I wanted to execute an application and apply some assertions on the output of the software(basically running a console app, parse the xml output and assert on values in the output).
<blockquote>FYI: I’m very new to PowerShell, so any suggestions on how I implemented the below are welcome…</blockquote>
I’ve seen a couple examples of writing test assertions in PowerShell out there. One example is <a href="http://www.psunit.org/">PSUnit</a>; however, this seemed a little heavy for my needs and not quite the syntactic sugar I was looking for.

Besides the syntax flavor I was desiring, another thing I wanted to do was leverage the power of NUnit.Framework’s assertion capabilities. I like the error messages generated when strings and other objects fail the assertion.
<h5>Examples of end result ShouldLookLike()…</h5>
$true.ShouldBeTrue()
$false.ShouldBeFalse()
"a".ShouldEqual("a")
"a".ShouldNotEqual("b")
<h5><strong>Step 1</strong>: Figure out how to write a C# style <a href="http://msdn.microsoft.com/en-us/library/bb383977.aspx">extension method</a> in PowerShell.</h5>
<blockquote>I found a great blog post describing how to extend any PowerShell object to add extension methods.

<a href="http://bartdesmet.net/blogs/bart/archive/2007/09/06/extension-methods-in-windows-powershell.aspx">Extension Methods in Windows PowerShell</a></blockquote>
In short, to extend types in PowerShell leveraging the <a href="http://msdn.microsoft.com/en-us/library/ms714419(VS.85).aspx">Extended Type System</a>, you need to define them in an xml file and import the method definitions into the PowerShell runtime instance.

Below is PowerShell XML definition for my NUnit Specification Extensions.
<pre class="brush: xml;">&lt;?xml version="1.0" encoding="utf-16"?&gt;
&lt;Types&gt;
    &lt;Type&gt;
        &lt;Name&gt;System.Object&lt;/Name&gt;
        &lt;Members&gt;
            &lt;ScriptMethod&gt;
                &lt;Name&gt;ShouldBeFalse&lt;/Name&gt;
                &lt;Script&gt;
                    [NUnit.Framework.Assert]::IsFalse($this)
                &lt;/Script&gt;
            &lt;/ScriptMethod&gt;
            &lt;ScriptMethod&gt;
                &lt;Name&gt;ShouldBeTrue&lt;/Name&gt;
                &lt;Script&gt;
                    [NUnit.Framework.Assert]::IsTrue($this)
                &lt;/Script&gt;
            &lt;/ScriptMethod&gt;
            &lt;ScriptMethod&gt;
                &lt;Name&gt;ShouldEqual&lt;/Name&gt;
                &lt;Script&gt;
                    [NUnit.Framework.Assert]::AreEqual($args[0], $this)
                &lt;/Script&gt;
            &lt;/ScriptMethod&gt;
            &lt;ScriptMethod&gt;
                &lt;Name&gt;ShouldNotEqual&lt;/Name&gt;
                &lt;Script&gt;
                    [NUnit.Framework.Assert]::AreNotEqual($args[0], $this)
                &lt;/Script&gt;
            &lt;/ScriptMethod&gt;
        &lt;/Members&gt;
    &lt;/Type&gt;
&lt;/Types&gt;</pre>
<h4></h4>
Take the above XML and save it to a file…
<blockquote>NOTE: the file HAS to be saved with the extension <strong>.ps1xml</strong>

Ex: NunitSpecificationPowerShellExtensions<strong>.ps1xml</strong></blockquote>
<h4></h4>
<h5>Step 2: Load the extended type definition into the PowerShell runtime.</h5>
Once you’ve saved the XML extended types to a file, you need to load it into the PowerShell runtime by executing the command below.
<blockquote>
Update-TypeData -PrependPath NunitSpecificationPowerShellExtensions.ps1xml</blockquote>
Before executing the above statement…Let’s quickly look at a System.String’s members and properties – just to show you what the extension methods look like when applied inside of the runtime.<a href="http://elegantcode.com/wp-content/uploads/2009/10/image3.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" src="http://elegantcode.com/wp-content/uploads/2009/10/image_thumb2.png" border="0" alt="image" width="586" height="479" /></a>

After executing the Update-TypeData command you’ll notice there are a number of “ScriptMethod” MemberTypes added to the object.

<a href="http://elegantcode.com/wp-content/uploads/2009/10/image4.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" src="http://elegantcode.com/wp-content/uploads/2009/10/image_thumb3.png" border="0" alt="image" width="600" height="580" /></a>

Now if you try to execute one of those newly added extension methods, you may get the following error…

PS C:\&gt; $testVar.<strong>ShouldEqual</strong>("hello world")

Exception calling "ShouldEqual" with "1" argument(s): "<strong>Unable to find type [NUnit.Framework.Assert]: make sure that the

assembly containing this type is loaded.</strong>"

At line:1 char:21

+ $testVar.ShouldEqual &lt;&lt;&lt;&lt; ("hello world")

+ CategoryInfo          : NotSpecified: (:) [], MethodInvocationException

+ FullyQualifiedErrorId : ScriptMethodRuntimeException

This is because we need to load the NUnit.Framework assembly into the runtime before we can leverage the extension methods.
<blockquote>[System.Reflection.Assembly]::LoadFrom("C:\Program Files\NUnit 2.5.2\bin\net-2.0\framework\nunit.framework.dll") | Out-Null</blockquote>
Now that the extension methods have been defined and loaded into the runtime, NUnit.Framework is loaded, we can now use the methods on any object that inherits from System.Object (which, as far as I know, is everything in PowerShell).

And now, everything you need in one script (if you have the xml extended type file saved somewhere…)
<pre>#
# Update-TypeData -prependPath C:\Code\NunitSpecificationPowerShellExtensions.ps1xml
#

[System.Reflection.Assembly]::LoadFrom("C:\Program Files\NUnit 2.5.2\bin\net-2.0\framework\nunit.framework.dll") | Out-Null

$true.ShouldBeTrue()

$false.ShouldBeFalse()

"a".ShouldEqual("a")

"a".ShouldNotEqual("b")</pre>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/10/25/integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Visual Studio Team System for Small Teams</title>
		<link>http://elegantcode.com/2009/11/30/wrapping-up-the-structuremap-automocking-container/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=wrapping-up-the-structuremap-automocking-container</link>
		<comments>http://elegantcode.com/2009/11/30/wrapping-up-the-structuremap-automocking-container/#comments</comments>
		<pubDate>Mon, 30 Nov 2009 07:21:43 +0000</pubDate>
		<dc:creator>Richard Cirerol</dc:creator>
				<category><![CDATA[TDD]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Unit Testing]]></category>
		<category><![CDATA[StructureMap; Automocking; MSpec;]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/11/30/wrapping-up-the-structuremap-automocking-container/</guid>
		<description><![CDATA[<p><font color="#804040"><strong>UPDATE</strong>: I apologize…the original wrapper did not allow injected dependencies.&#160; I have fixed this bug and updated the sample.</font></p> I have been using StructureMap.AutoMocking with MSpec (Machine.Specifications) and Rhino.Mocks for a few months now.  Although I am very comfortable with the patterns that emerge from using the frameworks together, introducing StructureMap.Automocking to other developers is sometimes challenging. I decided to wrap the details of the container to make the intention clearer and explanation easier.  I have started using this wrapper in my projects, and have found it makes building up specifications more efficient in my daily coding.]]></description>
			<content:encoded><![CDATA[<span style="color: #804040;"><strong>UPDATE</strong>: I apologize…the original wrapper did not allow injected dependencies.  I have fixed this bug and updated the sample.</span>

I have been using StructureMap.AutoMocking with MSpec (Machine.Specifications) and Rhino.Mocks for a few months now.  Although I am very comfortable with the patterns that emerge from using the frameworks together, introducing StructureMap.Automocking to other developers is sometimes challenging.

When viewing a specification or test set up with the Rhino.Mocks or Moq automocking container, what is being tested is not readily apparent.  Once the concept is explained and demonstrated, these same developers seem to have no issue with maintaining the specifications/tests.

I decided to wrap the details of the container to make the intention clearer and explanation easier.  I have started using this wrapper in my projects, and have found it makes building up specifications more efficient in my daily coding.

Let me know whether this is useful to you, or how it could be made more useful.
<h4>The Examples</h4>
Let’s contrive an example.  We’ll say we have a coffee machine that grinds its own beans before brewing. However, the hopper has to have beans before starting the grind.  Here is the basic specification:
<table border="1" cellspacing="0" cellpadding="2" width="533">
<tbody>
<tr>
<td width="117" valign="top">Action/Behavior</td>
<td width="414" valign="top">Prepare coffee grounds for 12 cups of coffee</td>
</tr>
<tr>
<td rowspan="2" width="117" valign="top">Expectations</td>
<td width="414" valign="top">Should check that hopper has beans (mock returns true)</td>
</tr>
<tr>
<td width="414" valign="top">Because hopper has beans, should ask grinder to grind enough beans for 12 cups of coffee</td>
</tr>
</tbody></table>
We could start without a container, using Rhino.Mocks to build up the CoffeeMachine dependencies manually:
<pre class="brush: csharp;">[Subject(typeof(CoffeeMachine),"using vanilla Rhino.Mocks")]
public class Example01_when_preparing_coffee_grounds
{
    Establish context = () =&gt;
        {
            Grinder = MockRepository.GenerateMock&lt;IGrinder&gt;();
            Hopper = MockRepository.GenerateMock&lt;IHopper&gt;();
            Hopper.Expect(x =&gt; x.HasBeans()).Return(true);
            CoffeeMachine = new CoffeeMachine(Grinder, Hopper);
        };

    Because of = () =&gt; _coffeeMachine.PrepareCoffeeGrounds(12);

    It should_check_if_hopper_has_beans = () =&gt; Hopper.VerifyAllExpectations();
    It should_grind_coffee = () =&gt; Grinder.AssertWasCalled(x =&gt; x.Grind(12));

    static IGrinder Grinder;
    static IHopper Hopper;
    static CoffeeMachine CoffeeMachine;
}</pre>
For those of you not familiar with the MSpec style, please refer to the following posts:
<ul>
	<li><a href="http://blog.wekeroad.com/blog/make-bdd-your-bff-2/" target="_blank">Make BDD Your BFF</a></li>
	<li><a href="http://www.lostechies.com/blogs/seanbiefeld/archive/2009/08/25/step-by-step-to-using-machine-specifications-with-resharper.aspx" target="_blank">Step by Step to Using MSpec (Machine.Specifications) with ReSharper</a></li>
	<li><a href="http://elegantcode.com/2009/07/05/mspec-take-2/" target="_blank">MSpec - Take 2</a></li>
	<li><a href="http://marcinobel.com/index.php/mspec-bdd-installer/" target="_blank">MSpec BDD framework installer</a></li>
	<li><strong>Updated! </strong>From the <a href="http://blog.cwa.me.uk/2009/11/30/the-morning-brew-487/" target="_blank">Morning Brew #487</a>: BDD with MSpec and Rhino Auto Mocks, parts  <a href="http://telldontask.wordpress.com/2009/11/10/bdd-with-mspec-and-rhino-auto-mocks/" target="_blank">1</a>, <a href="http://telldontask.wordpress.com/2009/11/19/bdd-with-mspec-and-rhino-auto-mocks-part-2/" target="_blank">2</a>, and <a href="http://telldontask.wordpress.com/2009/11/29/bdd-with-mspec-and-rhino-auto-mocks-part-3/" target="_blank">3</a>
Here is the same specification using the RhinoAutoMocker&lt;T&gt; class provided by StructureMap.AutoMocking:</li>
</ul>
<pre class="brush: csharp;">[Subject(typeof(CoffeeMachine),"using RhinoAutoMocker&lt;CoffeeMachine&gt;")]
public class Example02_when_preparing_coffee_grounds
{
    Establish context = () =&gt;
        {
            CoffeeMachine = new RhinoAutoMocker&lt;CoffeeMachine&gt;();
            Grinder = CoffeeMachine.Get&lt;IGrinder&gt;();
            Hopper = CoffeeMachine.Get&lt;IHopper&gt;();
            Hopper.Expect(x =&gt; x.HasBeans()).Return(true);
        };

    Because of = () =&gt; v.ClassUnderTest.PrepareCoffeeGrounds(12);

    It should_check_if_hopper_has_beans = () =&gt; Hopper.VerifyAllExpectations();
    It should_grind_coffee = () =&gt; Grinder.AssertWasCalled(x =&gt; x.Grind(12));

    static IGrinder Grinder;
    static IHopper Hopper;
    static RhinoAutoMocker&lt;CoffeeMachine&gt; CoffeeMachine;
}</pre>
Although I think this looks cleaner, the initialization of CoffeeMachine causes some confusion. Unfortunately, a common question would be, “Is RhinoAutoMocker&lt;CoffeeMachine&gt; creating a mocked version of CoffeeMachine?” Well, not exactly.

RhinoAutoMocker is an implementation of the AutoMocker base class which uses StructureMap to fill dependencies.  The RhinoAutoMocker implementation of the container uses Rhino.Mocks to generate all of dependencies of the target class, whereas the MoqAutoMocker implementation uses Moq.  (Optionally, the target class can be partially mocked in order to further isolate behavior.)  We then retrieve the class under test (in this case, CoffeeMachine) and its dependencies (IGrinder and IHopper) from the container for use.

If you do not need to setup any expectations in the specification, there is no need to retrieve the dependency from the container.  However, in this specification, we need both dependencies.

<em>(Incidentally, I do not like the ClassUnderTest name.  I may end up changing this to Instance, ClassInstance, TargetClass, or something similar.  Suggestions?)</em>

By moving the initialization of the RhinoAutoMocker to a base class, some of the chattiness of the context can be hidden.
<ul>
<pre class="brush: csharp;">[Subject(typeof(CoffeeMachine),"using RhinoAutoMocker base")]
public class Example03_when_preparing_coffee_grounds : with_rhinoautomocker
{
    Establish context = () =&gt; Hopper.Expect(x =&gt; x.HasBeans()).Return(true);

    Because of = () =&gt; CoffeeMachine.ClassUnderTest.PrepareCoffeeGrounds(12);

    It should_check_if_hopper_has_beans = () =&gt; Hopper.VerifyAllExpectations();
    It should_grind_coffee = () =&gt; Grinder.AssertWasCalled(x =&gt; x.Grind(12));

}

[Subject("using RhinoAutoMocker&lt;T&gt;")]
public class with_rhinoautomocker
{
    protected static IGrinder Grinder;
    protected static IHopper Hopper;
    protected static RhinoAutoMocker&lt;CoffeeMachine&gt; CoffeeMachine;

    Establish context = () =&gt;
    {
        CoffeeMachine = new RhinoAutoMocker&lt;CoffeeMachine&gt;();
        Grinder = CoffeeMachine.Get&lt;IGrinder&gt;();
        Hopper = CoffeeMachine.Get&lt;IHopper&gt;();
    };
}</pre>
However, we are still initializing and accessing the class in a less than optimal manner.To make the usage of the container a little more seamless, I decided to create a wrapper and factory for the AutoMocker.  Setup of the dependencies and expectations are done through an AutoMocker wrapper object.  The instance of the class under test is accessed through a ClassUnderTest object.
<h4>The Result</h4>
The specification (and base class) now look like this:
<pre class="brush: csharp;">[Subject(typeof(CoffeeMachine),"using coffee machine base")]
public class Example05_when_preparing_coffee_grounds : with_coffee_machine
{
    Establish context = () =&gt; Hopper.Expect(x =&gt; x.HasBeans()).Return(true);

    Because of = () =&gt; ClassUnderTest.PrepareCoffeeGrounds(12);

    It should_check_if_hopper_has_beans = () =&gt; Hopper.VerifyAllExpectations();
    It should_grind_coffee = () =&gt; Grinder.AssertWasCalled(x =&gt; x.Grind(12));
}

[Subject("using SpecificationFor&lt;CoffeeMachine&gt;")]
public class with_coffee_machine : SpecificationFor&lt;CoffeeMachine&gt;
{
    protected static IGrinder Grinder;
    protected static IHopper Hopper;

    public with_coffee_machine
    {
        Grinder = AutoMocker.Get&lt;IGrinder&gt;();
        Hopper = AutoMocker.Get&lt;IHopper&gt;();
    }
}</pre>
As you can see, the base class inherits from SpecificationFor&lt;T&gt;.  The default constructor uses Rhino.Mocks(MockMode.AAA) to generate the dependencies.  It then exposes a AutoMocker object, which is just the wrapper around the AutoMocker base class.  It also exposes a ClassUnderTest object.  If I didn’t need to use the dependencies, I could make the <em>Example05_when_preparing_coffee_grounds</em> class inherit from <em>SpecificationFor&lt;CoffeeMachine&gt; </em>instead of inheriting from the base class<em>.</em>
<h4>The Code</h4>
I have included the code for the wrapper below for your review.  The code and six examples are available on my <a href="http://codeprogression.googlecode.com/svn/trunk/CodeProgression.Framework.Testing" target="_blank">Google code repository</a>. The repository also includes an example using the MoqAutoMocker.  All the examples have the same assertions, but are built up using the different techniques.
<pre class="brush: csharp;">namespace CodeProgression.Framework.Testing
{
    public abstract class SpecificationFor&lt;T&gt; where T: class
    {
        protected static ClassUnderTest&lt;T&gt; Factory;

        // UPDATE 2009-12-21:
        //   Moved initialization here
        protected static T ClassUnderTest {get {return AutoMocker.Instance;} }

        protected SpecificationFor()
        {
            AutoMocker = AutoMockFactory.CreateTarget&lt;T&gt;();

            // UPDATE 2009-12-21:
            //    Initializing here prevented injected dependencies!
            // AutoMocker.PartialMockTheClassUnderTest();
            // ClassUnderTest = AutoMocker.Instance;
        }

        protected SpecificationFor(AutoMockType type)
        {
            AutoMocker = AutoMockFactory.CreateTarget&lt;T&gt;(type);

            // UPDATE 2009-12-21:
            // Initializing here prevented injected dependencies!
            // AutoMocker.PartialMockTheClassUnderTest();
            // ClassUnderTest = AutoMocker.Instance;
        }
    }

    public static class AutoMockFactory
    {
        public static ClassUnderTest&lt;TARGETCLASS&gt; CreateTarget&lt;TARGETCLASS&gt;() where TARGETCLASS : class
        {
            return CreateTarget&lt;TARGETCLASS&gt;(AutoMockType.RhinoMocksAAA);
        }

        public static ClassUnderTest&lt;TARGETCLASS&gt; CreateTarget&lt;TARGETCLASS&gt;(AutoMockType framework) where TARGETCLASS : class
        {
            AutoMocker&lt;TARGETCLASS&gt; mocker;
            ServiceLocator serviceLocator;
            switch (framework)
            {
                case AutoMockType.RhinoMocksAAA:
                    mocker = new RhinoAutoMocker&lt;TARGETCLASS&gt;(MockMode.AAA);
                    serviceLocator = new RhinoMocksAAAServiceLocator();
                    break;
                case AutoMockType.RhinoMocksClassic:
                    mocker = new RhinoAutoMocker&lt;TARGETCLASS&gt;(MockMode.RecordAndReplay);
                    serviceLocator = new RhinoMocksClassicServiceLocator();
                    break;
                case AutoMockType.Moq:
                    mocker = new MoqAutoMocker&lt;TARGETCLASS&gt;();
                    serviceLocator = new MoqServiceLocator();
                    break;
                default:
                    throw new ArgumentOutOfRangeException("framework");
            }
            return new ClassUnderTest&lt;TARGETCLASS&gt;(mocker, serviceLocator);
        }
    }

    public enum AutoMockType
    {
        Moq,
        RhinoMocksAAA,
        RhinoMocksClassic
    }

    public class ClassUnderTest&lt;TARGETCLASS&gt; where TARGETCLASS : class
    {
        readonly IAutoMocker&lt;TARGETCLASS&gt; _mocker;
        readonly ServiceLocator _serviceLocator;

        public ClassUnderTest(IAutoMocker&lt;TARGETCLASS&gt; mocker, ServiceLocator serviceLocator)
        {
            _mocker = mocker;
            _serviceLocator = serviceLocator;
        }

        public AutoMockedContainer Container
        {
            get { return _mocker.Container; }
        }

        public TARGETCLASS Instance
        {
            get { return _mocker.ClassUnderTest; }
        }

        public void MockObjectFactory()
        {
            _mocker.MockObjectFactory();
        }

        public void PartialMockTheClassUnderTest()
        {
            _mocker.PartialMockTheClassUnderTest();
        }

        public T Get&lt;T&gt;() where T : class
        {
            return _mocker.Get&lt;T&gt;();
        }

        public void Inject(Type pluginType, object stub)
        {
            _mocker.Inject(pluginType, stub);
        }

        public void Inject&lt;T&gt;(T target)
        {
            _mocker.Inject(target);
        }

        public T AddAdditionalMockFor&lt;T&gt;() where T : class
        {
            return _mocker.AddAdditionalMockFor&lt;T&gt;();
        }

        public void UseConcreteClassFor&lt;T&gt;()
        {
            _mocker.UseConcreteClassFor&lt;T&gt;();
        }

        public T[] CreateMockArrayFor&lt;T&gt;(int count) where T : class
        {
            return _mocker.CreateMockArrayFor&lt;T&gt;(count);
        }

        public void InjectArray&lt;T&gt;(T[] stubs)
        {
            _mocker.InjectArray(stubs);
        }

        public T Mock&lt;T&gt;() where T : class
        {
            return _serviceLocator.Service&lt;T&gt;();
        }
        public object Mock(Type serviceType)
        {
            return _serviceLocator.Service(serviceType);
        }
        public T PartialMock&lt;T&gt;() where T : class
        {
            return _serviceLocator.PartialMock&lt;T&gt;();
        }
    }
}</pre>
</ul>
<script type="text/javascript">// <![CDATA[
 var cirerolGaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."); document.write(unescape("%3Cscript src='" + cirerolGaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
// ]]&gt;</script>

<script type="text/javascript">// <![CDATA[
 var cirerolPageTracker = _gat._getTracker('UA-8257866-3'); cirerolPageTracker._initData(); cirerolPageTracker._trackPageview();
// ]]&gt;</script>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/11/30/wrapping-up-the-structuremap-automocking-container/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Elegant Code &#187; Unit Testing</title>
	<atom:link href="http://elegantcode.com/category/unit-testing/feed/" rel="self" type="application/rss+xml" />
	<link>http://elegantcode.com</link>
	<description></description>
	<lastBuildDate>Tue, 15 May 2012 10:00:00 +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>AutoTest.NET</title>
		<link>http://elegantcode.com/2010/11/30/autotest-net/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=autotest-net</link>
		<comments>http://elegantcode.com/2010/11/30/autotest-net/#comments</comments>
		<pubDate>Tue, 30 Nov 2010 11:00:00 +0000</pubDate>
		<dc:creator>Jan Van Ryswyck</dc:creator>
				<category><![CDATA[TDD]]></category>
		<category><![CDATA[Tools and Utilities]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/11/30/autotest-net/</guid>
		<description><![CDATA[I just want to quickly point out a tool that I’ve been playing with for a couple of days now, named AutoTest.NET. Its an open-source tool that originates from a popular tool in the Ruby community called ZenTest, which basically runs all your valuable unit tests when you save your source files or when you [...]]]></description>
			<content:encoded><![CDATA[<p>I just want to quickly point out a tool that I’ve been playing with for a couple of days now, named <a href="https://github.com/acken/AutoTest.Net" target="_blank">AutoTest.NET</a>. Its an open-source tool that originates from a popular tool in the Ruby community called <a href="http://www.zenspider.com/ZSS/Products/ZenTest/" target="_blank">ZenTest</a>, which basically runs all your valuable unit tests when you save your source files or when you build your code. It enables you to get feedback about your changes as soon as possible.</p>  <p>The project started out a couple of years ago on <a href="http://code.google.com/p/autotestnet/" target="_blank">Google code</a> and was first initiated by <a href="http://averyblog.com/" target="_blank">James Avery</a>. Contribution stopped at some point until recently where <a href="http://ackenpacken.blogspot.com/" target="_blank">Svein Arne Ackenhausen</a> forked the source code and <a href="https://github.com/acken/AutoTest.Net" target="_blank">put it on GitHub</a>. Now it runs both for .NET as well as Mono, with NUnit, MSTest and xUnit as the currently supported unit test frameworks. </p>  <p>Here’s a screenshot from the feedback window when all tests pass:</p>  <p><a href="http://elegantcode.com/wp-content/uploads/2010/11/Success.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="Success" border="0" alt="Success" src="http://elegantcode.com/wp-content/uploads/2010/11/Success_thumb.png" width="540" height="189" /></a> </p>  <p>And here you can see the same window after I broke one of my unit tests:</p>  <p><a href="http://elegantcode.com/wp-content/uploads/2010/11/Failure.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="Failure" border="0" alt="Failure" src="http://elegantcode.com/wp-content/uploads/2010/11/Failure_thumb.png" width="538" height="319" /></a> </p>  <p>Here you can see which particular unit test has been broken and by clicking the specified link you end up at the right source file in Visual Studio. </p>  <p>I encourage you to pick up this small tool and learn how it can facilitate your TDD flow. Take a look at <a href="https://github.com/acken/AutoTest.Net/wiki/Get-started!" target="_blank">this page</a> in order to get up-and-running in no time. Also don’t forget to provide the owner(s) of this project with some feedback that you might have. Svein has been very helpful over the last week answering all my stupid questions and remarks (and the Nobel price for this year’s most patient person goes to … ;-) ). </p>  <p>I would definitely like to see this tool becoming more popular, so go check it out.&#160;&#160; </p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/11/30/autotest-net/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>If Self-Documenting Code is the What, Unit Tests are the Why</title>
		<link>http://elegantcode.com/2010/04/25/if-self-documenting-code-is-the-what-unit-tests-are-the-why/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=if-self-documenting-code-is-the-what-unit-tests-are-the-why</link>
		<comments>http://elegantcode.com/2010/04/25/if-self-documenting-code-is-the-what-unit-tests-are-the-why/#comments</comments>
		<pubDate>Sun, 25 Apr 2010 19:09:04 +0000</pubDate>
		<dc:creator>John Sonmez</dc:creator>
				<category><![CDATA[Agile]]></category>
		<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Craftsmanship]]></category>
		<category><![CDATA[Documentation]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/04/25/if-self-documenting-code-is-the-what-unit-tests-are-the-why/</guid>
		<description><![CDATA[It is not enough to just write code that is clean and self-documenting.  Eliminating comments and replacing them with clear variable and method names, will tell the reader of your code clearly what it is doing, but it will not properly express why it is doing it. If you recall from my original post on [...]]]></description>
			<content:encoded><![CDATA[It is not enough to just write code that is clean and self-documenting.  <a href="http://elegantcode.com/2010/04/18/eliminating-comments-the-road-to-clarity/">Eliminating comments</a> and replacing them with clear variable and method names, will tell the reader of your code clearly what it is doing, but it will not properly express why it is doing it.

If you recall from my <a href="http://elegantcode.com/2010/04/09/what-does-elegant-code-mean-to-me/">original post</a> on Elegant code, I stated that elegant code is:
<blockquote>Something that is simple yet effective, delivered with grace.</blockquote>
By writing self-documenting code we are hopefully able to achieve some of the aspects of simplicity and grace, but it tells us nothing about the effectiveness of the code.
<h2>Bringing the dead to life</h2>
<a href="http://elegantcode.com/wp-content/uploads/2010/04/zombies.jpg"><img style="border-right-width: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto" title="zombies" src="http://elegantcode.com/wp-content/uploads/2010/04/zombies_thumb.jpg" border="0" alt="zombies" width="441" height="295" /></a>

Throwing out comments is a debatable topic.  <a href="http://www.reddit.com/r/programming/comments/bsutx/">It raises quite a bit of controversy</a>, as you can see from some of the comments on my post about the subject.  The reason, perhaps, that so many people are so staunchly opposed to the idea, is because they are worried, and rightly so, that throwing out comments will reduce the documentation of what the code is doing.

Think about that for a second.  Is documentation of what the code is doing important?  It better be.  What we are trying to accomplish by writing self-documenting code instead of comments, is to take the vessel, which is the code itself, and make that same vessel be the documentation of what the code does.  It is by doing this that we creating a living representation of the functionality of the code.  Comments are akin to a dead representation of the functionality of the code because they do not change automatically with the code.

I diverge to talk about comments so that I can draw a parallel to another form of documentation which is valuable and should be considered necessary.  That other set of documentation is requirements.  Have you ever written requirements documents?  Have you ever captured requirements from the customer and put them into UML diagrams, or perhaps plopped them into some templated Word document, which is never updated again, and no one reads, because no one trusts it is correct?  Wouldn’t it be great if we would replace that dead document or set of documents, with a living one?

The good news is we can, and some of us have.  And I fully expect this recommendation will be just as controversial, because <strong>I am suggesting that we don’t have to write low level specifications of the system at all, instead we can write good unit tests. </strong>When we do this, we are taking a dead form of document and bringing it to life.
<h2>Unit tests tell us why and how our code is effective</h2>
If
<pre class="csharpcode">i = 5;  // Widget count defaults to five.</pre>
is replaced with
<pre class="csharpcode">widgetCount = DEFAULT_WIDGET_COUNT;</pre>
<!--.csharpcode, .csharpcode pre { 	font-size: small; 	color: black; 	font-family: consolas, "Courier New", courier, monospace; 	background-color: #ffffff; 	/*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt  { 	background-color: #f4f4f4; 	width: 100%; 	margin: 0em; } .csharpcode .lnum { color: #606060; } -->

then
<blockquote><span style="background-color: #ffffff;">1.1.5 When a new widget is created, the widget count should be increased by one.</span></blockquote>
is replaced with
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">void</span> When_NewWidgetIsCreated_Then_WidgetCountIsIncreasedByOne()
{
     WidgetFactory.Count = 3;
     WidgetFactory.CreateNew();
     assertEquals(4, WidgetFactory.Count);
}</pre>
The unit test is replacing the low level requirement, which is somewhat open to interpretation and untied to the code, with an absolute and completely tied-to-the-code, specific requirement.

The unit test is telling us why our code is built the way it is.  It is telling us what requirement that particular structure of code is trying to address.  <strong>It is telling us what end result that code is trying to accomplish and what the expectations are on the results of a given condition.</strong>

The unit test is telling us how the code is to be used in order to achieve its result.  It is serving as a living reference to the syntax and use of the code we built.  <strong>Instead of providing instructions on how to use our API, we are providing a living example, and proof that it will indeed work.</strong> Examples are often much more effective than instructions anyway.
<h2>What exactly are we replacing?</h2>
At this point we are not trying to replace all the documentation of the system (at this point).

With self-documenting code, we sought to eliminate comments, and replace them with good variable and method names.

With unit tests, we seek to eliminate technical documentation and requirements of the system, that is targeted at a developer or technical audience.

We are NOT trying to eliminate high level specifications of the system, or use cases. <strong>Unit tests DO NOT replace that kind of documentation! </strong>We will talk about replacing that kind of documentation when we talk about automated functional or system tests.

Simply put, any kind of documentation that you would give to a developer so they understand how the system works and how to use the code or APIs, can be easily replaced by writing good unit tests.

Our simple goal is to replace the “dead” documentation (meaning that it does not update automatically with the thing it is documenting), with “living” documentation in the form of unit tests.

One last point.  I want to be clear that I am not saying that having unit tests automatically results in the ability to replace technical documentation.  Just like having long-named methods and variables doesn’t automatically replace the need for comments.  It is a matter of the quality of the unit tests that are written, just as it is a matter of the quality of the self-documenting code.
<h5>As always, you can subscribe to this <a href="http://feeds2.feedburner.com/ElegantCode">RSS feed</a> to follow my posts on elegant code.  Feel free to check out my main personal blog at <a href="http://simpleprogrammer.com">http://simpleprogrammer.com</a>, which has a wider range of posts, updated 2-3 times a week.  Also, you can follow me on twitter <a href="http://twitter.com/jsonmez">here</a>.</h5>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/04/25/if-self-documenting-code-is-the-what-unit-tests-are-the-why/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Behaviors with MSpec</title>
		<link>http://elegantcode.com/2010/02/26/behaviors-with-mspec/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=behaviors-with-mspec</link>
		<comments>http://elegantcode.com/2010/02/26/behaviors-with-mspec/#comments</comments>
		<pubDate>Fri, 26 Feb 2010 23:33:28 +0000</pubDate>
		<dc:creator>Jan Van Ryswyck</dc:creator>
				<category><![CDATA[BDD]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/02/26/behaviors-with-mspec/</guid>
		<description><![CDATA[In my previous posts, I showed the syntax for context/specifications using Machine.Specifications (or MSpec for short) and how to use an auto mocking container in conjunction with this excellent Behavior-Driven Development (BDD) framework. For this post, I want to show you one of the nice features of MSpec called behaviors. Suppose we have to create [...]]]></description>
			<content:encoded><![CDATA[<p>In my previous posts, I showed the <a href="http://elegantcode.com/2010/02/19/getting-started-with-machine-specifications-mspec/">syntax for context/specifications</a> using <a href="http://github.com/machine/machine.specifications">Machine.Specifications</a> (or MSpec for short) and <a href="http://elegantcode.com/2010/02/23/mspec-and-auto-mocking">how to use an auto mocking container</a> in conjunction with this excellent Behavior-Driven Development (BDD) framework. For this post, I want to show you one of the nice features of MSpec called <em>behaviors</em>.</p>  <p>Suppose we have to create some sort of specification that validates the format of an e-mail address. We typically use some regular expression in order to ensure that a specified e-mail address is properly formatted.</p>  <pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">class</span> EmailSpecification
{
    <span class="kwrd">private</span> <span class="kwrd">const</span> String EmailRegexPattern = <span class="str">@&quot;.. SOME_REGEX_PATTERN ...&quot;</span>;

    <span class="kwrd">public</span> Boolean IsSatisfiedBy(String candidate)
    {
        var regex = <span class="kwrd">new</span> Regex(EmailRegexPattern);
        <span class="kwrd">return</span> regex.IsMatch(candidate);
    }
}</pre>
<style type="text/css">

.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>I guess this is pretty common and straightforward. One way to provide some unit tests for this particular piece of code is to check a whole number of e-mail addresses that either pass or fail the specification. The following example shows only a couple of scenarios:</p>

<pre class="csharpcode">[TestFixture]
<span class="kwrd">public</span> <span class="kwrd">class</span> When_validating_an_email
    : ContextSpecification&lt;EmailSpecification&gt;
{
    <span class="kwrd">protected</span> <span class="kwrd">override</span> EmailSpecification Create_subject_under_test()
    {
        <span class="kwrd">return</span> <span class="kwrd">new</span> EmailSpecification();
    }

    [Test]
    <span class="kwrd">public</span> <span class="kwrd">void</span> ShouldBeSatisfied()
    {
        Assert.That(SUT.IsSatisfiedBy(<span class="str">&quot;one2@three.com&quot;</span>));
        Assert.That(SUT.IsSatisfiedBy(<span class="str">&quot;one@two3.com&quot;</span>));
    }

    [Test]
    <span class="kwrd">public</span> <span class="kwrd">void</span> ShouldNotBeSatisfied()
    {
        Assert.That(SUT.IsSatisfiedBy(<span class="str">&quot;one_two.com&quot;</span>), Is.False);
        Assert.That(SUT.IsSatisfiedBy(<span class="str">&quot;one_two@&quot;</span>), Is.False);
    }
}</pre>
<style type="text/css">

.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>A slightly more concise approach for these kind of unit tests can be accomplished by utilizing a feature of any decent unit test framework called <em>row tests. </em>With this approach we can, at the very least, reduce the number of asserts we have to write for each unit test.<em>&#160;</em></p>

<pre class="csharpcode">[TestFixture]
<span class="kwrd">public</span> <span class="kwrd">class</span> When_validating_an_email__approach_2
    : ContextSpecification&lt;EmailSpecification&gt;
{
    <span class="kwrd">protected</span> <span class="kwrd">override</span> EmailSpecification Create_subject_under_test()
    {
        <span class="kwrd">return</span> <span class="kwrd">new</span> EmailSpecification();
    }

    [RowTest]
    [Row(<span class="str">&quot;one2@three.com&quot;</span>)]
    [Row(<span class="str">&quot;one@two3.com&quot;</span>)]
    <span class="kwrd">public</span> <span class="kwrd">void</span> ShouldBeSatisfied(String email)
    {
        Assert.That(SUT.IsSatisfiedBy(email));
    }

    [RowTest]
    [Row(<span class="str">&quot;one_two.com&quot;</span>)]
    [Row(<span class="str">&quot;one_two@&quot;</span>)]
    <span class="kwrd">public</span> <span class="kwrd">void</span> ShouldNotBeSatisfied(String email)
    {
        Assert.That(SUT.IsSatisfiedBy(email), Is.False);
    }
}</pre>
<style type="text/css">

.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>Notice that I explicitly called both of these approaches <em>unit tests</em> as they don’t have much to do with BDD in my opinion. I’m not saying that using regular unit tests is a bad thing, but with&#160; behavior-driven development context is king. So these unit tests are perfect examples of ‘<a href="http://elegantcode.com/2008/12/30/dont-sell-out-on-the-context-dude/">context betrayal</a>’ when following the BDD approach. </p>

<p>Lets see what MSpec can bring to the table for these kind of scenarios:</p>

<pre class="csharpcode">[Subject(<span class="kwrd">typeof</span>(EmailSpecification), <span class="str">&quot;is satisfied&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_validating_an_email_address_with_a_number_in_the_local_part
    : email_specification_specs
{
    Establish context = () =&gt;
        EmailAddress = <span class="str">&quot;one2@three.com&quot;</span>;

    Behaves_like&lt;SatisfiedSpecificationBehavior&gt; a_satisfied_specification;
}

[Subject(<span class="kwrd">typeof</span>(EmailSpecification), <span class="str">&quot;is satisfied&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_validating_an_email_address_with_a_number_in_the_domain_name
    : email_specification_specs
{
    Establish context = () =&gt;
        EmailAddress = <span class="str">&quot;one@two3.com&quot;</span>;

    Behaves_like&lt;SatisfiedSpecificationBehavior&gt; a_satisfied_specification;
}

[Subject(<span class="kwrd">typeof</span>(EmailSpecification), <span class="str">&quot;is satisfied&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_validating_an_email_address_without_an_At_sign
    : email_specification_specs
{
    Establish context = () =&gt;
        EmailAddress = <span class="str">&quot;one_two.com&quot;</span>;

    Behaves_like&lt;UnsatisfiedSpecificationBehavior&gt; an_unsatisfied_specification;
}

[Subject(<span class="kwrd">typeof</span>(EmailSpecification), <span class="str">&quot;is satisfied&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_validating_an_email_address_without_a_domain
    : email_specification_specs
{
    Establish context = () =&gt;
        EmailAddress = <span class="str">&quot;one_two@&quot;</span>;

    Behaves_like&lt;UnsatisfiedSpecificationBehavior&gt; an_unsatisfied_specification;
}</pre>
<style type="text/css">

.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>In order to escape ‘context betrayal’, we’ve split up every context into a separate context/specification. In order to reduce the amount of effort caused by duplicate code, we stripped the context setup to the bare minimum (just a particular e-mail address in this case). The observations are isolated into MSpec behaviors which provides a very readable description of their outcome. Lets take a look at what is needed in order to get these <em>behaviors</em> to work.</p>

<p>But first lets take at look at the abstract base class that we’ve used for the context/specifications we’ve just shown.</p>

<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">abstract</span> <span class="kwrd">class</span> email_specification_specs
{
    Establish context = () =&gt;
    {
        SUT = <span class="kwrd">new</span> EmailSpecification();
    };

    Because of = () =&gt;
        Result = SUT.IsSatisfiedBy(EmailAddress);

    <span class="kwrd">protected</span> <span class="kwrd">static</span> Boolean Result;
    <span class="kwrd">protected</span> <span class="kwrd">static</span> String EmailAddress { get; set; }
    <span class="kwrd">protected</span> <span class="kwrd">static</span> EmailSpecification SUT { get; set; }
}</pre>

<p><style type="text/css">

.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style></p>

<p>&#160;</p>

<p>We abstracted as much as possible into this base class in order to remove duplication in the context/specifications. The creation of the subject-under-test and the calling of its <em>IsSatisfiedBy</em> method, but the important one is the declaration of the <em>Result</em> field. This field contains the outcome of the <em>IsSatisfiedBy</em> method. Finally, lets have a look at the behaviors themselves:</p>

<pre class="csharpcode">[Behaviors]
<span class="kwrd">public</span> <span class="kwrd">class</span> SatisfiedSpecificationBehavior
{
    <span class="kwrd">protected</span> <span class="kwrd">static</span> Boolean Result;
    
    It should_satisfy_the_specification = () =&gt;
        Result.ShouldBeTrue();
}

[Behaviors]
<span class="kwrd">public</span> <span class="kwrd">class</span> UnsatisfiedSpecificationBehavior
{
    <span class="kwrd">protected</span> <span class="kwrd">static</span> Boolean Result;

    It should_not_satisfy_the_specification = () =&gt;
        Result.ShouldBeFalse();
}</pre>
<style type="text/css">

.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>In order to create an MSpec behavior, we just have to create a separate class that we decorate with the <em>Behaviors</em> attribute. Also notice that we have the same declaration of the <em>Result</em> field. MSpec ensures that this field gets initialized with the value of the other <em>Result</em> field that is set in the base class of the context/specifications. Note that you don’t necessarily need to put this field in a base class. You can have that field in every context/specification if you’d like (not sure why) as long as the names match with the fields used in the defined behaviors.</p>

<p>I personally like the way how the MSpec contributors tried to solve testing the same logic with different input patterns and the syntax they provided to back this up.&#160;&#160; </p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/02/26/behaviors-with-mspec/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>MSpec and Auto Mocking</title>
		<link>http://elegantcode.com/2010/02/23/mspec-and-auto-mocking/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=mspec-and-auto-mocking</link>
		<comments>http://elegantcode.com/2010/02/23/mspec-and-auto-mocking/#comments</comments>
		<pubDate>Tue, 23 Feb 2010 20:38:54 +0000</pubDate>
		<dc:creator>Jan Van Ryswyck</dc:creator>
				<category><![CDATA[BDD]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/02/23/mspec-and-auto-mocking/</guid>
		<description><![CDATA[In my previous post, I explained how to get started with Machine.Specifications (or MSpec for short) and showed you how the syntax for context/specifications looks like when using this BDD framework. For this post, I want to show you how to use an auto mocking container (we’ll be using the one provided by StructureMap off [...]]]></description>
			<content:encoded><![CDATA[<p>In my <a href="http://elegantcode.com/2010/02/19/getting-started-with-machine-specifications-mspec/">previous post</a>, I explained how to get started with <a href="http://github.com/machine/machine.specifications">Machine.Specifications</a> (or MSpec for short) and showed you how the syntax for context/specifications looks like when using this BDD framework. For this post, I want to show you how to use an <a href="http://vanryswyckjan.blogspot.com/2008/01/automocking-container.html">auto mocking container</a> (we’ll be using the one provided by StructureMap off course).</p>  <p>We’ll use the same example as the one used in the previous post, but now we’ll deal with the message handler that makes a particular customer preferred.</p> <style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>  <pre class="csharpcode"><span class="rem">//</span>
<span class="rem">// Subject under test</span>
<span class="rem">//</span>
<span class="kwrd">public</span> <span class="kwrd">class</span> MakeCustomerPreferredMessageHandler
{
    <span class="kwrd">private</span> <span class="kwrd">readonly</span> ICustomerRepository&lt;ICanMakeCustomerPreferred&gt; _repository;

    <span class="kwrd">public</span> MakeCustomerPreferredMessageHandler(
        ICustomerRepository&lt;ICanMakeCustomerPreferred&gt; repository)
    {
        _repository = repository;
    }

    <span class="kwrd">public</span> <span class="kwrd">void</span> Handle(MakeCustomerPreferredMessage message)
    {
        var customer = _repository.Get(message.CustomerId);
        <span class="kwrd">if</span>(<span class="kwrd">null</span> == customer)
            <span class="kwrd">throw</span> <span class="kwrd">new</span> InvalidOperationException(
                <span class="str">&quot;No customer for specified identifier&quot;</span>);
        
        customer.MakePreferred();
        _repository.Save(customer);
    }
}</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>The <em>Customer</em> class implements a ‘<a href="http://martinfowler.com/bliki/RoleInterface.html">role interface’</a> called <em>ICanMakeCustomerPreferred</em>. We retrieve a customer from the repository and make it preferred. We throw an exception in case the customer cannot be found in the data store.</p>

<p>Here are the context/specifications for this easy example:</p>

<pre class="csharpcode">[Subject(<span class="str">&quot;Making a customer preferred&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_making_a_customer_preferred
    : context_specification&lt;MakeCustomerPreferredMessageHandler&gt;
{
    Establish context = () =&gt;
    {
        _message = <span class="kwrd">new</span> MakeCustomerPreferredMessage { CustomerId = 6412 };

        Repository.Stub(repository =&gt; repository.Get(_message.CustomerId))
            .Return(Customer);
    };

    Because of = () =&gt; 
        SUT.Handle(_message);
    
    It should_mark_the_customer_as_preferred = () =&gt;
        Customer.AssertWasCalled(customer =&gt; customer.MakePreferred());

    It should_save_the_customer_in_the_repository = () =&gt;
        Repository.AssertWasCalled(repository =&gt; repository.Save(Customer));

    <span class="kwrd">private</span> <span class="kwrd">static</span> ICanMakeCustomerPreferred Customer
    {
        get { <span class="kwrd">return</span> Dependency&lt;ICanMakeCustomerPreferred&gt;(); }
    }

    <span class="kwrd">private</span> <span class="kwrd">static</span> ICustomerRepository&lt;ICanMakeCustomerPreferred&gt; Repository
    {
        get { <span class="kwrd">return</span> Dependency&lt;ICustomerRepository&lt;ICanMakeCustomerPreferred&gt;&gt;(); }
    }

    <span class="kwrd">private</span> <span class="kwrd">static</span> MakeCustomerPreferredMessage _message;
}

[Subject(<span class="str">&quot;Making a customer preferred&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_making_an_unexisting_customer_preferred
    : context_specification&lt;MakeCustomerPreferredMessageHandler&gt;
{
    Establish context = () =&gt;   
    {
        _message = <span class="kwrd">new</span> MakeCustomerPreferredMessage() { CustomerId = 61544 };

        Dependency&lt;ICustomerRepository&lt;ICanMakeCustomerPreferred&gt;&gt;()
            .Stub(repository =&gt; repository.Get(_message.CustomerId))
            .Return(<span class="kwrd">null</span>);
    };

    Because of = () =&gt;
        _resultingException = Catch.Exception(() =&gt; SUT.Handle(_message));

    It should_result_in_an_error = () =&gt;
        _resultingException.ShouldBeOfType&lt;InvalidOperationException&gt;();

    <span class="kwrd">private</span> <span class="kwrd">static</span> MakeCustomerPreferredMessage _message;
    <span class="kwrd">private</span> <span class="kwrd">static</span> Exception _resultingException;
}</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>I want to point out that all fields and properties are made static. This is needed so that the anonymous methods can access them. I’m also using a base class for these specifications which I’ll show next. This base class uses an auto mocking container for providing the requested mocks and stubs through the <em>Dependency</em> and <em>Stub</em> methods. </p>

<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">abstract</span> <span class="kwrd">class</span> context_specification&lt;TSubjectUnderTest&gt;
    <span class="kwrd">where</span> TSubjectUnderTest : <span class="kwrd">class</span>
{
    <span class="kwrd">private</span> <span class="kwrd">static</span> IAutoMockingContainer&lt;TSubjectUnderTest&gt; _autoMockingContainer;
    <span class="kwrd">protected</span> <span class="kwrd">static</span> TSubjectUnderTest SUT { get; set; }

    Establish context = () =&gt;
    {
        _autoMockingContainer = <span class="kwrd">new</span> StructureMapAMC&lt;TSubjectUnderTest&gt;();
        SUT = _autoMockingContainer.Create();     
    };
    
    Cleanup stuff = () =&gt; 
    {
        SUT = <span class="kwrd">null</span>;
        _autoMockingContainer = <span class="kwrd">null</span>;
    };

    <span class="kwrd">protected</span> <span class="kwrd">static</span> TDependency Dependency&lt;TDependency&gt;()
        <span class="kwrd">where</span> TDependency : <span class="kwrd">class</span>
    {
        <span class="kwrd">return</span> _autoMockingContainer.GetMock&lt;TDependency&gt;();
    }

    <span class="kwrd">protected</span> <span class="kwrd">static</span> TStub Stub&lt;TStub&gt;()
        <span class="kwrd">where</span> TStub : <span class="kwrd">class</span>
    {
        <span class="kwrd">return</span> _autoMockingContainer.GetStub&lt;TStub&gt;();
    }
}

<span class="kwrd">public</span> <span class="kwrd">interface</span> IAutoMockingContainer&lt;TSubject&gt;
    <span class="kwrd">where</span> TSubject : <span class="kwrd">class</span>
{
    TSubject Create();
    TMock GetMock&lt;TMock&gt;() <span class="kwrd">where</span> TMock : <span class="kwrd">class</span>;
    TStub GetStub&lt;TStub&gt;() <span class="kwrd">where</span> TStub : <span class="kwrd">class</span>;
}

<span class="kwrd">public</span> <span class="kwrd">class</span> StructureMapAMC&lt;TSubject&gt; 
    : IAutoMockingContainer&lt;TSubject&gt;
    <span class="kwrd">where</span> TSubject : <span class="kwrd">class</span>
{
    <span class="kwrd">private</span> <span class="kwrd">readonly</span> RhinoAutoMocker&lt;TSubject&gt; _rhinoAutoMocker;

    <span class="kwrd">public</span> StructureMapAMC()
    {
        _rhinoAutoMocker = 
            <span class="kwrd">new</span> RhinoAutoMocker&lt;TSubject&gt;(MockMode.AAA);
    }

    <span class="kwrd">public</span> TSubject Create()
    {
        <span class="kwrd">return</span> _rhinoAutoMocker.ClassUnderTest;
    }

    <span class="kwrd">public</span> TMock GetMock&lt;TMock&gt;() 
        <span class="kwrd">where</span> TMock : <span class="kwrd">class</span>
    {
        <span class="kwrd">return</span> GetDependency&lt;TMock&gt;();
    }

    <span class="kwrd">public</span> TStub GetStub&lt;TStub&gt;() 
        <span class="kwrd">where</span> TStub : <span class="kwrd">class</span>
    {
        <span class="kwrd">return</span> GetDependency&lt;TStub&gt;();
    }

    <span class="kwrd">private</span> TDependency GetDependency&lt;TDependency&gt;() 
        <span class="kwrd">where</span> TDependency : <span class="kwrd">class</span>
    {
        <span class="kwrd">return</span> _rhinoAutoMocker.Get&lt;TDependency&gt;();
    }
}</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>Notice that I’m using the <em>Establish</em> and <em>Cleanup</em> delegates in the <em>context_specification</em> base class. This doesn’t prevent that these can be used again in derived context/specifications. MSpec ensures that the anonymous methods are called in the right order. This means that the <em>Establish</em> method of the base class is called before the <em>Establish</em> method of the derived context/specifications.&#160;&#160;&#160;&#160; </p>

<p>Absolutely no rocket science here, but I figured it might come in handy when you need it. For the next post I’ll try to demonstrate how to deal with reusable behaviors.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/02/23/mspec-and-auto-mocking/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Getting Started With Machine.Specifications (MSpec)</title>
		<link>http://elegantcode.com/2010/02/19/getting-started-with-machine-specifications-mspec/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=getting-started-with-machine-specifications-mspec</link>
		<comments>http://elegantcode.com/2010/02/19/getting-started-with-machine-specifications-mspec/#comments</comments>
		<pubDate>Fri, 19 Feb 2010 21:34:17 +0000</pubDate>
		<dc:creator>Jan Van Ryswyck</dc:creator>
				<category><![CDATA[BDD]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/02/19/getting-started-with-machine-specifications-mspec/</guid>
		<description><![CDATA[Its been a while since I evaluated and evolved my approach to BDD. The way I’ve been doing BDD up until now is described in this blog post which goes way back to 2008. Everyone has kind of their own style nowadays. Below you can find the code of two context/specifications for a method named [...]]]></description>
			<content:encoded><![CDATA[<p>Its been a while since I evaluated and evolved my approach to BDD. The way I’ve been doing BDD up until now is described in <a href="http://elegantcode.com/2008/10/25/refining-contextspecification-bdd-using-rhino-mocks-35/">this blog post</a> which goes way back to 2008. Everyone has kind of their own style nowadays. Below you can find the code of two context/specifications for a method named <em>MakePreferred</em> on a <em>Customer </em>class. This simple example clarifies the style that I’ve been following up until now.</p> <style type="text/css">


.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style><style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>  <pre class="csharpcode">[TestFixture]
<span class="kwrd">public</span> <span class="kwrd">class</span> When_making_a_regular_customer_preferred
    : ContextSpecification&lt;Customer&gt;
{
    <span class="kwrd">protected</span> <span class="kwrd">override</span> Customer Create_subject_under_test()
    {
        <span class="kwrd">return</span> <span class="kwrd">new</span> Customer(<span class="kwrd">new</span>[] { _order });
    }

    <span class="kwrd">protected</span> <span class="kwrd">override</span> <span class="kwrd">void</span> Establish_context()
    {
        _order = <span class="kwrd">new</span> Order(<span class="kwrd">new</span>[] { <span class="kwrd">new</span> OrderItem(12), 
                                   <span class="kwrd">new</span> OrderItem(16) });
                                   
        _totalAmountWithoutDiscount = _order.TotalAmount;
    }

    <span class="kwrd">protected</span> <span class="kwrd">override</span> <span class="kwrd">void</span> Because()
    {
        SUT.MakePreferred();
    }

    [Test]
    <span class="kwrd">public</span> <span class="kwrd">void</span> Then_the_customer_should_be_marked_as_preferred()
    {
        SUT.IsPreferred.ShouldBeTrue();
    }

    [Test]
    <span class="kwrd">public</span> <span class="kwrd">void</span> Then_a_ten_percent_discount_should_be_applied_to_all_outstanding_orders()
    {
        _order.TotalAmount.ShouldBeEqualTo(
            _totalAmountWithoutDiscount * 0.9);
    }

    <span class="kwrd">private</span> Order _order;
    <span class="kwrd">private</span> Double _totalAmountWithoutDiscount;
}

[TestFixture]
<span class="kwrd">public</span> <span class="kwrd">class</span> When_making_a_preferred_customer_preferred
    : ContextSpecification&lt;Customer&gt;
{
    <span class="kwrd">protected</span> <span class="kwrd">override</span> Customer Create_subject_under_test()
    {
        var customer = <span class="kwrd">new</span> Customer(<span class="kwrd">new</span>[] { _order });
        customer.MakePreferred();
        <span class="kwrd">return</span> customer;
    }

    <span class="kwrd">protected</span> <span class="kwrd">override</span> <span class="kwrd">void</span> Establish_context()
    {
        _order = <span class="kwrd">new</span> Order(<span class="kwrd">new</span>[] { <span class="kwrd">new</span> OrderItem(12), 
                                   <span class="kwrd">new</span> OrderItem(16) });
        _totalAmountWithoutDiscount = _order.TotalAmount;
    }

    <span class="kwrd">protected</span> <span class="kwrd">override</span> <span class="kwrd">void</span> Because()
    {
        SUT.MakePreferred();
    }

    [Test]
    <span class="kwrd">public</span> <span class="kwrd">void</span> Then_no_additional_discount_should_be_applied_to_the_outstanding_orders()
    {
        _order.TotalAmount.ShouldNotBeEqualTo(
            _totalAmountWithoutDiscount * 0.81);
    }

    <span class="kwrd">private</span> Order _order;
    <span class="kwrd">private</span> Double _totalAmountWithoutDiscount;
}

<span class="rem">//</span>
<span class="rem">// Subject under test</span>
<span class="rem">//</span>
<span class="kwrd">public</span> <span class="kwrd">class</span> Customer
{
    <span class="kwrd">private</span> <span class="kwrd">readonly</span> List&lt;Order&gt; _orders;
    <span class="kwrd">public</span> Boolean IsPreferred { get; <span class="kwrd">private</span> set; }

    <span class="kwrd">public</span> Customer(IEnumerable&lt;Order&gt; orders)
    {
        _orders = <span class="kwrd">new</span> List&lt;Order&gt;(orders);
    }

    <span class="kwrd">public</span> <span class="kwrd">void</span> MakePreferred()
    {
        <span class="kwrd">if</span>(IsPreferred)    
            <span class="kwrd">return</span>;
    
        IsPreferred = <span class="kwrd">true</span>;
        _orders.ForEach(order =&gt; order.ApplyDiscount(10));
    }
}</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>The bottom line of this example is that preferred customers get a 10 percent discount. Customers that are already preferred do not get an additional discount or otherwise we’re out of business ;-). </p>

<p>I’ve been pretty happy with this approach so far, although sometimes there were some quirks associated with this. So it was time for me to look beyond the horizon again, trying to look for ways to improve. </p>

<p><a href="http://github.com/machine/machine.specifications">Machine.Specifications</a> or MSpec for short is something that has been on my ‘cool-things-to-learn-list’ for quite some time now. As you will see later in this post, the syntax is a bit different as one would come to expect from a context/specification framework that targets the C# programming language. Its seems to be heavily inspired by Scott Bellware’s <a href="http://code.google.com/p/specunit-net/">SpecUnit framework</a> and <a href="http://rspec.info/">RSpec</a>.</p>

<p>Lets see how to set things up first. </p>

<p>The most obvious starting point is downloading the bits and bytes. You can grab the <a href="http://github.com/machine/machine.specifications">source code</a> from GitHub and build it or you can wuss out like I did and get the latest build from the <a href="http://teamcity.codebetter.com/login.html">TeamCity.CodeBetter.com</a> builder server (you can log on as a guest and search the artifacts for a latest build).&#160; </p>

<p>When you’re heavily addicted to <a href="http://www.testdriven.net/">TestDriven.NET</a> like I am, then its possible to keep using this wonderful Visual Studio add-in for running MSpec context/specifications. Just create a directory named <em>Machine.Specifications</em> in {$Program_Files}\TestDriven.NET 2.0 and copy the following files:</p>

<ul>
  <li>Machine.Specifications.dll</li>

  <li>Machine.Specifications.TDNetRunner.dll</li>

  <li>InstallTDNetRunner.bat</li>
</ul>

<ul>Run the InstallTDNetRunner.bat file and you’re able to run all MSpec context/specifications using TestDriven.NET.</ul>

<p>I also strongly encourage you to install the plugin for the Resharper test runner (if only to prevent some Resharper warnings later on). First step is to add a directory named <em>Plugins</em> to the <em>Bin</em> directory of Resharper ({$Program_Files}\JetBrains\ReSharper\v4.5\Bin\). Then create a directory named <em>Machine.Specifications</em> in the <em>Plugins</em> directory you just created and copy the following files:</p>

<ul>
  <li>Machine.Specifications.dll</li>

  <li>Machine.Specifications.ReSharperRunner.4.5.dll</li>

  <li>InstallResharperRunner.4.5.bat</li>
</ul>

<p>Run the InstallResharperRunner.4.5.bat file and you’re also able to run MSpec context/specifications using the Resharper test runner.</p>

<p>I’m not going to put this off any longer. Lets look at the code of the context/specifications shown earlier but completely revamped using the MSpec syntax:</p>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<pre class="csharpcode">[Subject(<span class="str">&quot;Making a customer preferred&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_a_regular_customer_is_made_preferred 
{
    Establish context = () =&gt;
    {
        _order = <span class="kwrd">new</span> Order(<span class="kwrd">new</span>[] { <span class="kwrd">new</span> OrderItem(12), 
                                   <span class="kwrd">new</span> OrderItem(16) });
        _totalAmountWithoutDiscount = _order.TotalAmount;

        SUT = <span class="kwrd">new</span> Customer(<span class="kwrd">new</span>[] { _order });
    };

    Because of = () =&gt; 
        SUT.MakePreferred();

    It should_mark_the_customer_as_preferred = () =&gt;
        SUT.IsPreferred.ShouldBeTrue();
        
    It should_apply_a_ten_percent_discount_to_all_outstanding_orders = () =&gt;
        _order.TotalAmount.ShouldEqual(_totalAmountWithoutDiscount * 0.9);      

    <span class="kwrd">private</span> <span class="kwrd">static</span> Customer SUT;
    
    <span class="kwrd">private</span> <span class="kwrd">static</span> Order _order;
    <span class="kwrd">private</span> <span class="kwrd">static</span> Double _totalAmountWithoutDiscount;
}

[Subject(<span class="str">&quot;Making a customer preferred&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_a_preferred_customer_is_made_preferred
{
    Establish context = () =&gt;
    {
        _order = <span class="kwrd">new</span> Order(<span class="kwrd">new</span>[] { <span class="kwrd">new</span> OrderItem(12), 
                                   <span class="kwrd">new</span> OrderItem(16) });
        _totalAmountWithoutDiscount = _order.TotalAmount;

        SUT = <span class="kwrd">new</span> Customer(<span class="kwrd">new</span>[] { _order });
        SUT.MakePreferred();
    };

    Because of = () =&gt;
        SUT.MakePreferred();

    It should_apply_no_additional_discount_to_the_outstanding_orders = () =&gt; 
        _order.TotalAmount.ShouldNotEqual(_totalAmountWithoutDiscount * 0.81);

    <span class="kwrd">private</span> <span class="kwrd">static</span> Customer SUT;

    <span class="kwrd">private</span> <span class="kwrd">static</span> Order _order;
    <span class="kwrd">private</span> <span class="kwrd">static</span> Double _totalAmountWithoutDiscount;
}</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>I warned you about the syntax, didn’t I :-). It only took me a couple of seconds to get used to this syntax but now I’m completely hooked. Instead of using methods and attributes, MSpec utilizes delegates and anonymous methods. But there’s more. </p>

<p>When using <a href="http://www.nunit.com/index.php">NUnit</a> for writing context/ specifications, the <em>Establish_context</em> and <em>Because</em> methods of the example shown earlier is executed before every observation (test). With MSpec, the <em>Establish</em> and <em>Because</em> anonymous methods are executed only once for every context no matter how many observations a particular context class contains. Big difference? Well, at first glance not but on second hand it does make <a href="http://elegantcode.com/2008/12/30/dont-sell-out-on-the-context-dude/">selling out on the context</a> a bit more difficult as it will probably blow up in your face sooner than later. You can force MSpec to execute the <em>Establish</em> and <em>Because</em> anonymous methods before every observation by applying the <em>SetupForEachSpecification</em> attribute to the context class, but I strongly encourage you to stay away from that unless absolutely needed.</p>

<p>Also notice that the fields in the contexts are now all static. This is needed so that the anonymous methods can access those.&#160;&#160;&#160;&#160;&#160; </p>

<p>Running these context/specifications using TestDriven.NET yields the following output in the output window of Visual Studio:</p>

<blockquote>
  <p><font face="Arial">Making a customer preferred, when a regular customer is made preferred
      <br />» should mark the customer as preferred

      <br />» should apply a ten percent discount to all outstanding orders</font></p>

  <p><font face="Arial">Making a customer preferred, when a preferred customer is made preferred
      <br />» should apply no additional discount to the outstanding orders</font></p>
</blockquote>

<p>What’s not to like? Well, the only downside so far is that Resharper was giving me some warnings about classes and fields not being used etc. … . Many of those warnings disappeared by registering the MSpec plugin for the Resharper test runner as I explained earlier.</p>

<p>So far, so good. I’ve got two more posts coming up on MSpec, so stay tuned.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/02/19/getting-started-with-machine-specifications-mspec/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Unity/Moq &#8211; AutoMocker or AutoMockingContainer</title>
		<link>http://elegantcode.com/2010/01/03/unitymoq-automocker-or-automockingcontainer/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=unitymoq-automocker-or-automockingcontainer</link>
		<comments>http://elegantcode.com/2010/01/03/unitymoq-automocker-or-automockingcontainer/#comments</comments>
		<pubDate>Sun, 03 Jan 2010 16:52:33 +0000</pubDate>
		<dc:creator>Jason Jarrett</dc:creator>
				<category><![CDATA[TDD]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Tools and Utilities]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/01/03/unitymoq-automocker-or-automockingcontainer/</guid>
		<description><![CDATA[What is an Auto Mocking Container? This post started to get a little long, so I won’t re-explain the concept. Joshua Flanagan wrote a nice overview at his Los Techies blog: Auto mocking Explained. My post is mainly here to describe the Unity version of an automocking container I threw together. In Jan 2009 I [...]]]></description>
			<content:encoded><![CDATA[<h4>What is an Auto Mocking Container?</h4>  <p>This post started to get a little long, so I won’t re-explain the concept.</p>  <p><a href="http://www.lostechies.com/blogs/joshuaflanagan/default.aspx">Joshua Flanagan</a> wrote a nice overview at his <a href="http://www.lostechies.com/">Los Techies</a> blog: <a href="http://www.lostechies.com/blogs/joshuaflanagan/archive/2009/02/03/auto-mocking-explained.aspx"><strong>Auto mocking Explained</strong></a>.</p>  <p>My post is mainly here to describe the Unity version of an automocking container I threw together.</p>  <h4>In Jan 2009 I blogged about my initial version of the Unity AutoMocker - Why am I blogging about it again?</h4>  <p>I originally wrote the AutoMocker for the Unity container a year ago (Jan 2009, in Silverlight), and finally got around to placing the code up in the <a href="http://code.google.com/p/moq-contrib/">moq-contrib</a> project in June of 2009.</p>  <p>I’m writing another post today in hopes to:</p>  <ol>   <li>Get some feedback on how this little snippet of code should continue. </li>    <li>Give a little more how-to/example code </li>    <li>Describe some updates I made since I originally created it.&#160; </li> </ol>  <h4>Where can I get it?</h4>  <p><strong>This is one part where I’d appreciate some feedback.</strong></p>  <p>I have two slightly different versions out there (currently).</p>  <p>I have one version at the <a href="http://code.google.com/p/elegantcode/source/browse/#svn/trunk/Coders/JasonJarrett/UnityAutoMocker">ElegantCode</a> repository where I was working on it, and the other I threw up at <a href="http://code.google.com/p/moq-contrib/">moq-contrib</a>.</p>  <p>The core of the UnityAutoMockContainer is the same in both places, it’s how the tests are separated out that differ.</p>  <p>In the <a href="http://code.google.com/p/elegantcode/source/browse/#svn/trunk/Coders/JasonJarrett/UnityAutoMocker">ElegantCode repository</a> it’s an all in one self contained single file (that you can copy into your own test project(s)). You can then setup a single test in your own testing framework that runs all internal automocker tests (in case you need to modify it yourself, and don’t want to break any existing functionality). EX: test</p>  <pre class="brush: csharp;">[Test]
public void Should_run_all_UnityAutoMockContainer_internal_tests()
{
    Moq.AutoMocking.SelfTesting.UnityAutoMockContainerFixture
        .RunAllTests(Console.WriteLine);
}</pre>

<p>I kind of like this format as it makes it easy to port between test libraries. Can’t say I like having the tests in the same file as the core, but it certainly is not a large chunk of code (so far) so it’s relatively small to maintain and definitely easier to manage as a single .cs file than another assembly (which would have to be version dependent on both Unity and Moq).</p>

<p>The <a href="http://code.google.com/p/moq-contrib/">moq-contrib</a> is definitely where I think this helper should end up (and it is there). I just happened to break the tests out into the Silverlight test project and the core is alone in a file. </p>

<p>It’s current state isn’t as easy to copy to a test library (Silverlight/Desktop/Unity 1.2/Unity 2.0) as the one at <a href="http://elegantcode.com/">ElegantCode</a>. <strong>What does anyone think?</strong> Should I put them all together in one file?</p>

<p>However it ends up (1. all in one file or two (1 test) (1 core)) it will continue to be maintained on the <a href="http://code.google.com/p/moq-contrib/">moq-contrib</a> project.</p>

<h4>What is the high level API of the container?</h4>

<p>It’s pretty simple, (currently) there are four methods on the container.</p>

<p><strong>Two for registering items with the container</strong>. Say you want to register an already created instance, or say you want to map an interface to a concrete class and _not_ have the container generate mocks automatically for special cases. </p>

<p>And <strong>two for pulling items out of the container</strong>. Whether you want a instance of T or a Mock&lt;T&gt;, it gives you ways to retrieve both.</p>

<blockquote>
  <p><a href="http://elegantcode.com/wp-content/uploads/2010/01/image.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://elegantcode.com/wp-content/uploads/2010/01/image_thumb.png" width="396" height="106" /></a> </p>
</blockquote>

<h4>How can I setup my own registrations with the container? </h4>

<p>Say I don’t want to have the container generate mocks for specific items and I want to supply specific configuration to the UnityContainer.</p>

<blockquote>
  <p>public UnityAutoMockContainer RegisterInstance&lt;TService&gt;(TService instance)</p>

  <p>public UnityAutoMockContainer Register&lt;TService, TImplementation&gt;() 
    <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; where TImplementation : TService</p>
</blockquote>

<p><strong>Note</strong>: both of these registration methods return the container itself so you can fluently stack registration. <strong>EX:</strong></p>

<pre class="brush: csharp;">AutoMockContainer
    .Register&lt;IServiceA, ServiceA&gt;()
    .Register&lt;IServiceB, ServiceB&gt;();</pre>

<p><strong>Let me know</strong>: I haven’t tested or played around with how this automocking container deals with any container specific xml configuration… So although I don’t think you should probably have that in a test assembly (stuff happens). Let me know if there are any issues.</p>

<h4>How do I get items out of the container?</h4>

<p>First is the Resolve&lt;T&gt;(). It will pull an item T out of the container. (Creating it if not already existing)</p>

<blockquote>
  <p>public T Resolve&lt;T&gt;()</p>
</blockquote>

<p>When T is an interface Resolve&lt;T&gt; (unless you setup registration specifically with the container) should return basically “(new Mock&lt;T&gt;()).Object”</p>

<p>When T is a concrete Class, the container should return an instance of T and any of it’s dependencies will be satisfied by mocks. (Note that T will not be any sort of mocked instance of T, unless you used the GetMock&lt;T&gt; as described below first)</p>

<blockquote>
  <p>public Mock&lt;T&gt; GetMock&lt;T&gt;() where T : class</p>
</blockquote>

<p>When T is an interface GetMock&lt;T&gt; should return basically “(new Mock&lt;T&gt;())” </p>

<p>When T is a concrete Class, the container should return a new Mock&lt;T&gt;() and any of it’s dependencies will be satisfied by mocks.</p>

<h4>How do I use the UnityAutoMockContainer?</h4>

<p>It’s pretty basic, you first create an instance of the UnityAutoMockContainer, and from there you can ask it for mocks of an (Interface, Class, or Abstract Class).</p>

<p>If you request an instance of a concrete class, or abstract class, the UnityAutoMockContainer will stuff mocks in for any constructor dependencies of your concrete class (if it can). You can then request from the container those same dependencies one at a time and either apply mocking setups or verifications.</p>

<blockquote>
  <p><strong>NOTE:</strong> Anything the container creates will live as a singleton instance in the container. So any other requests from the container will always return the originally created instance. Therefore, each distinct scenario in a test suite should have their own instances of the container.</p>
</blockquote>

<p>Below his an example of how you can leverage the container in some tests. Given this base fixture class…</p>

<pre class="brush: csharp;">public class FixtureBase
{
    private readonly UnityAutoMockContainer _autoMockContainer = new UnityAutoMockContainer();

    protected UnityAutoMockContainer AutoMockContainer
    {
        get { return _autoMockContainer; }
    }

    [TestFixtureSetUp]
    public void SetupContext_ALL()
    {
        Before_all_tests();
        Because();
    }

    [TestFixtureTearDown]
    public void TearDownContext_ALL()
    {
        After_all_tests();
    }

    protected virtual void Before_all_tests()
    {
    }

    protected virtual void Because()
    {
    }

    protected virtual void After_all_tests()
    {
    }
}</pre>

<p>If I were given the following system to test.</p>

<pre class="brush: csharp;">public interface IServiceA { void RunA(); }
public interface IServiceB { void RunB(); }

public class TestComponent
{
    public TestComponent(IServiceA serviceA, IServiceB serviceB)
    {
        ServiceA = serviceA;
        ServiceB = serviceB;
    }

    public IServiceA ServiceA { get; private set; }
    public IServiceB ServiceB { get; private set; }

    public void RunAll()
    {
        if (!HowDidItGo())
            return;
        ServiceA.RunA();
        ServiceB.RunB();
    }

    public virtual bool HowDidItGo()
    {
        // some really nasty untestable code
        return true;
    }
}</pre>

<p>The below example demonstrates simply verifying some behavior on the mocked dependencies of the system under test.</p>

<pre class="brush: csharp;">[TestFixture]
public class Example__how_to_pull_items_from_the_UnityAutoMockContainer_when_verifying_behavior_after_an_action_was_taken 
    : FixtureBase
{
    private TestComponent _testComponent;

    protected override void Before_all_tests()
    {
        base.Before_all_tests();
        _testComponent = AutoMockContainer.Resolve&lt;TestComponent&gt;();
    }

    protected override void Because()
    {
        _testComponent.RunAll();
    }

    [Test]
    public void Should_run_ServiceA_RunA()
    {
        AutoMockContainer
            .GetMock&lt;IServiceA&gt;()
            .Verify(v =&gt; v.RunA(), Times.Once());
    }

    [Test]
    public void Should_run_ServiceB_RunB()
    {
        AutoMockContainer
            .GetMock&lt;IServiceB&gt;()
            .Verify(v =&gt; v.RunB(), Times.Once());
    }
}</pre>

<p>Next, you may have noticed that the system under test had a complicated internal method (that may not necessarily be testable). You can use the AutoMocker to create the system under test as a Mock itself, so we can override some of the behavior. Here’s how you could quickly do that. </p>

<blockquote>
  <p><strong>Aside</strong>: I’m not saying this is a good practice or aids in good component design, just saying it’s possible</p>
</blockquote>

<pre class="brush: csharp;">[TestFixture]
public class Example__how_to_use_the_UnityAutoMockContainer_to_override_a_method_on_the_SystemUnderTest_to_test_a_certain_behavior
    : FixtureBase
{

    private TestComponent _testComponent;

    protected override void Before_all_tests()
    {
        base.Before_all_tests();
        var mockTestComponent = AutoMockContainer.GetMock&lt;TestComponent&gt;();

        mockTestComponent
            .Setup(s =&gt; s.HowDidItGo())
            .Returns(false);

        _testComponent = mockTestComponent.Object;
    }

    protected override void Because()
    {
        _testComponent.RunAll();
    }

    [Test]
    public void Should_run_ServiceA_RunA()
    {
        AutoMockContainer
            .GetMock&lt;IServiceA&gt;()
            .Verify(v =&gt; v.RunA(), Times.Never());
    }

    [Test]
    public void Should_run_ServiceB_RunB()
    {
        AutoMockContainer
            .GetMock&lt;IServiceB&gt;()
            .Verify(v =&gt; v.RunB(), Times.Never());
    }
}</pre>

<p>&#160;</p>

<p>It’s amazing how much redundant test setup code this little helper has saved me in my tests. I hope others can find some use with this as well.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/01/03/unitymoq-automocker-or-automockingcontainer/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>StatLight &#8211; Goes Open Source</title>
		<link>http://elegantcode.com/2009/12/10/statlight-goes-open-source/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=statlight-goes-open-source</link>
		<comments>http://elegantcode.com/2009/12/10/statlight-goes-open-source/#comments</comments>
		<pubDate>Fri, 11 Dec 2009 03:26:55 +0000</pubDate>
		<dc:creator>Jason Jarrett</dc:creator>
				<category><![CDATA[Esoterica]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[TDD]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Tools and Utilities]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/12/10/statlight-goes-open-source/</guid>
		<description><![CDATA[Although I made a very minor attempt at making StatLight a “for-sale” product, I knew when I started that open-source was most likely going to be my long term path for StatLight. What is it? (Silverlight Testing Automation Tool) StatLight is a tool developed for automating the setup, running, and gathering results of Silverlight unit [...]]]></description>
			<content:encoded><![CDATA[Although I made a very minor attempt at making <a href="http://statlight.net" target="_blank">StatLight</a> a “for-sale” product, I knew when I started that open-source was most likely going to be my long term path for <a href="http://statlight.net" target="_blank">StatLight</a>.
<h5>What is it? (Silverlight Testing Automation Tool)</h5>
StatLight is a tool developed for automating the setup, running, and gathering results of Silverlight unit tests. StatLight helps to speed up the feedback cycles while practicing<a href="http://en.wikipedia.org/wiki/Test-driven_development"> TDD</a>/<a href="http://en.wikipedia.org/wiki/Behavior_Driven_Development">BDD</a>/(insert your test style here) during Silverlight development.
<h5>Where can I get StatLight?</h5>
<a href="http://StatLight.CodePlex.com">http://StatLight.CodePlex.com</a>
<h4>Happy Coding !!!</h4>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/12/10/statlight-goes-open-source/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Wrapping up the StructureMap Automocking Container</title>
		<link>http://elegantcode.com/2009/11/30/wrapping-up-the-structuremap-automocking-container/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=wrapping-up-the-structuremap-automocking-container</link>
		<comments>http://elegantcode.com/2009/11/30/wrapping-up-the-structuremap-automocking-container/#comments</comments>
		<pubDate>Mon, 30 Nov 2009 07:21:43 +0000</pubDate>
		<dc:creator>Richard Cirerol</dc:creator>
				<category><![CDATA[TDD]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Unit Testing]]></category>
		<category><![CDATA[StructureMap; Automocking; MSpec;]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/11/30/wrapping-up-the-structuremap-automocking-container/</guid>
		<description><![CDATA[<p><font color="#804040"><strong>UPDATE</strong>: I apologize…the original wrapper did not allow injected dependencies.&#160; I have fixed this bug and updated the sample.</font></p> I have been using StructureMap.AutoMocking with MSpec (Machine.Specifications) and Rhino.Mocks for a few months now.  Although I am very comfortable with the patterns that emerge from using the frameworks together, introducing StructureMap.Automocking to other developers is sometimes challenging. I decided to wrap the details of the container to make the intention clearer and explanation easier.  I have started using this wrapper in my projects, and have found it makes building up specifications more efficient in my daily coding.]]></description>
			<content:encoded><![CDATA[<span style="color: #804040;"><strong>UPDATE</strong>: I apologize…the original wrapper did not allow injected dependencies.  I have fixed this bug and updated the sample.</span>

I have been using StructureMap.AutoMocking with MSpec (Machine.Specifications) and Rhino.Mocks for a few months now.  Although I am very comfortable with the patterns that emerge from using the frameworks together, introducing StructureMap.Automocking to other developers is sometimes challenging.

When viewing a specification or test set up with the Rhino.Mocks or Moq automocking container, what is being tested is not readily apparent.  Once the concept is explained and demonstrated, these same developers seem to have no issue with maintaining the specifications/tests.

I decided to wrap the details of the container to make the intention clearer and explanation easier.  I have started using this wrapper in my projects, and have found it makes building up specifications more efficient in my daily coding.

Let me know whether this is useful to you, or how it could be made more useful.
<h4>The Examples</h4>
Let’s contrive an example.  We’ll say we have a coffee machine that grinds its own beans before brewing. However, the hopper has to have beans before starting the grind.  Here is the basic specification:
<table border="1" cellspacing="0" cellpadding="2" width="533">
<tbody>
<tr>
<td width="117" valign="top">Action/Behavior</td>
<td width="414" valign="top">Prepare coffee grounds for 12 cups of coffee</td>
</tr>
<tr>
<td rowspan="2" width="117" valign="top">Expectations</td>
<td width="414" valign="top">Should check that hopper has beans (mock returns true)</td>
</tr>
<tr>
<td width="414" valign="top">Because hopper has beans, should ask grinder to grind enough beans for 12 cups of coffee</td>
</tr>
</tbody></table>
We could start without a container, using Rhino.Mocks to build up the CoffeeMachine dependencies manually:
<pre class="brush: csharp;">[Subject(typeof(CoffeeMachine),"using vanilla Rhino.Mocks")]
public class Example01_when_preparing_coffee_grounds
{
    Establish context = () =&gt;
        {
            Grinder = MockRepository.GenerateMock&lt;IGrinder&gt;();
            Hopper = MockRepository.GenerateMock&lt;IHopper&gt;();
            Hopper.Expect(x =&gt; x.HasBeans()).Return(true);
            CoffeeMachine = new CoffeeMachine(Grinder, Hopper);
        };

    Because of = () =&gt; _coffeeMachine.PrepareCoffeeGrounds(12);

    It should_check_if_hopper_has_beans = () =&gt; Hopper.VerifyAllExpectations();
    It should_grind_coffee = () =&gt; Grinder.AssertWasCalled(x =&gt; x.Grind(12));

    static IGrinder Grinder;
    static IHopper Hopper;
    static CoffeeMachine CoffeeMachine;
}</pre>
For those of you not familiar with the MSpec style, please refer to the following posts:
<ul>
	<li><a href="http://blog.wekeroad.com/blog/make-bdd-your-bff-2/" target="_blank">Make BDD Your BFF</a></li>
	<li><a href="http://www.lostechies.com/blogs/seanbiefeld/archive/2009/08/25/step-by-step-to-using-machine-specifications-with-resharper.aspx" target="_blank">Step by Step to Using MSpec (Machine.Specifications) with ReSharper</a></li>
	<li><a href="http://elegantcode.com/2009/07/05/mspec-take-2/" target="_blank">MSpec - Take 2</a></li>
	<li><a href="http://marcinobel.com/index.php/mspec-bdd-installer/" target="_blank">MSpec BDD framework installer</a></li>
	<li><strong>Updated! </strong>From the <a href="http://blog.cwa.me.uk/2009/11/30/the-morning-brew-487/" target="_blank">Morning Brew #487</a>: BDD with MSpec and Rhino Auto Mocks, parts  <a href="http://telldontask.wordpress.com/2009/11/10/bdd-with-mspec-and-rhino-auto-mocks/" target="_blank">1</a>, <a href="http://telldontask.wordpress.com/2009/11/19/bdd-with-mspec-and-rhino-auto-mocks-part-2/" target="_blank">2</a>, and <a href="http://telldontask.wordpress.com/2009/11/29/bdd-with-mspec-and-rhino-auto-mocks-part-3/" target="_blank">3</a>
Here is the same specification using the RhinoAutoMocker&lt;T&gt; class provided by StructureMap.AutoMocking:</li>
</ul>
<pre class="brush: csharp;">[Subject(typeof(CoffeeMachine),"using RhinoAutoMocker&lt;CoffeeMachine&gt;")]
public class Example02_when_preparing_coffee_grounds
{
    Establish context = () =&gt;
        {
            CoffeeMachine = new RhinoAutoMocker&lt;CoffeeMachine&gt;();
            Grinder = CoffeeMachine.Get&lt;IGrinder&gt;();
            Hopper = CoffeeMachine.Get&lt;IHopper&gt;();
            Hopper.Expect(x =&gt; x.HasBeans()).Return(true);
        };

    Because of = () =&gt; v.ClassUnderTest.PrepareCoffeeGrounds(12);

    It should_check_if_hopper_has_beans = () =&gt; Hopper.VerifyAllExpectations();
    It should_grind_coffee = () =&gt; Grinder.AssertWasCalled(x =&gt; x.Grind(12));

    static IGrinder Grinder;
    static IHopper Hopper;
    static RhinoAutoMocker&lt;CoffeeMachine&gt; CoffeeMachine;
}</pre>
Although I think this looks cleaner, the initialization of CoffeeMachine causes some confusion. Unfortunately, a common question would be, “Is RhinoAutoMocker&lt;CoffeeMachine&gt; creating a mocked version of CoffeeMachine?” Well, not exactly.

RhinoAutoMocker is an implementation of the AutoMocker base class which uses StructureMap to fill dependencies.  The RhinoAutoMocker implementation of the container uses Rhino.Mocks to generate all of dependencies of the target class, whereas the MoqAutoMocker implementation uses Moq.  (Optionally, the target class can be partially mocked in order to further isolate behavior.)  We then retrieve the class under test (in this case, CoffeeMachine) and its dependencies (IGrinder and IHopper) from the container for use.

If you do not need to setup any expectations in the specification, there is no need to retrieve the dependency from the container.  However, in this specification, we need both dependencies.

<em>(Incidentally, I do not like the ClassUnderTest name.  I may end up changing this to Instance, ClassInstance, TargetClass, or something similar.  Suggestions?)</em>

By moving the initialization of the RhinoAutoMocker to a base class, some of the chattiness of the context can be hidden.
<ul>
<pre class="brush: csharp;">[Subject(typeof(CoffeeMachine),"using RhinoAutoMocker base")]
public class Example03_when_preparing_coffee_grounds : with_rhinoautomocker
{
    Establish context = () =&gt; Hopper.Expect(x =&gt; x.HasBeans()).Return(true);

    Because of = () =&gt; CoffeeMachine.ClassUnderTest.PrepareCoffeeGrounds(12);

    It should_check_if_hopper_has_beans = () =&gt; Hopper.VerifyAllExpectations();
    It should_grind_coffee = () =&gt; Grinder.AssertWasCalled(x =&gt; x.Grind(12));

}

[Subject("using RhinoAutoMocker&lt;T&gt;")]
public class with_rhinoautomocker
{
    protected static IGrinder Grinder;
    protected static IHopper Hopper;
    protected static RhinoAutoMocker&lt;CoffeeMachine&gt; CoffeeMachine;

    Establish context = () =&gt;
    {
        CoffeeMachine = new RhinoAutoMocker&lt;CoffeeMachine&gt;();
        Grinder = CoffeeMachine.Get&lt;IGrinder&gt;();
        Hopper = CoffeeMachine.Get&lt;IHopper&gt;();
    };
}</pre>
However, we are still initializing and accessing the class in a less than optimal manner.To make the usage of the container a little more seamless, I decided to create a wrapper and factory for the AutoMocker.  Setup of the dependencies and expectations are done through an AutoMocker wrapper object.  The instance of the class under test is accessed through a ClassUnderTest object.
<h4>The Result</h4>
The specification (and base class) now look like this:
<pre class="brush: csharp;">[Subject(typeof(CoffeeMachine),"using coffee machine base")]
public class Example05_when_preparing_coffee_grounds : with_coffee_machine
{
    Establish context = () =&gt; Hopper.Expect(x =&gt; x.HasBeans()).Return(true);

    Because of = () =&gt; ClassUnderTest.PrepareCoffeeGrounds(12);

    It should_check_if_hopper_has_beans = () =&gt; Hopper.VerifyAllExpectations();
    It should_grind_coffee = () =&gt; Grinder.AssertWasCalled(x =&gt; x.Grind(12));
}

[Subject("using SpecificationFor&lt;CoffeeMachine&gt;")]
public class with_coffee_machine : SpecificationFor&lt;CoffeeMachine&gt;
{
    protected static IGrinder Grinder;
    protected static IHopper Hopper;

    public with_coffee_machine
    {
        Grinder = AutoMocker.Get&lt;IGrinder&gt;();
        Hopper = AutoMocker.Get&lt;IHopper&gt;();
    }
}</pre>
As you can see, the base class inherits from SpecificationFor&lt;T&gt;.  The default constructor uses Rhino.Mocks(MockMode.AAA) to generate the dependencies.  It then exposes a AutoMocker object, which is just the wrapper around the AutoMocker base class.  It also exposes a ClassUnderTest object.  If I didn’t need to use the dependencies, I could make the <em>Example05_when_preparing_coffee_grounds</em> class inherit from <em>SpecificationFor&lt;CoffeeMachine&gt; </em>instead of inheriting from the base class<em>.</em>
<h4>The Code</h4>
I have included the code for the wrapper below for your review.  The code and six examples are available on my <a href="http://codeprogression.googlecode.com/svn/trunk/CodeProgression.Framework.Testing" target="_blank">Google code repository</a>. The repository also includes an example using the MoqAutoMocker.  All the examples have the same assertions, but are built up using the different techniques.
<pre class="brush: csharp;">namespace CodeProgression.Framework.Testing
{
    public abstract class SpecificationFor&lt;T&gt; where T: class
    {
        protected static ClassUnderTest&lt;T&gt; Factory;

        // UPDATE 2009-12-21:
        //   Moved initialization here
        protected static T ClassUnderTest {get {return AutoMocker.Instance;} }

        protected SpecificationFor()
        {
            AutoMocker = AutoMockFactory.CreateTarget&lt;T&gt;();

            // UPDATE 2009-12-21:
            //    Initializing here prevented injected dependencies!
            // AutoMocker.PartialMockTheClassUnderTest();
            // ClassUnderTest = AutoMocker.Instance;
        }

        protected SpecificationFor(AutoMockType type)
        {
            AutoMocker = AutoMockFactory.CreateTarget&lt;T&gt;(type);

            // UPDATE 2009-12-21:
            // Initializing here prevented injected dependencies!
            // AutoMocker.PartialMockTheClassUnderTest();
            // ClassUnderTest = AutoMocker.Instance;
        }
    }

    public static class AutoMockFactory
    {
        public static ClassUnderTest&lt;TARGETCLASS&gt; CreateTarget&lt;TARGETCLASS&gt;() where TARGETCLASS : class
        {
            return CreateTarget&lt;TARGETCLASS&gt;(AutoMockType.RhinoMocksAAA);
        }

        public static ClassUnderTest&lt;TARGETCLASS&gt; CreateTarget&lt;TARGETCLASS&gt;(AutoMockType framework) where TARGETCLASS : class
        {
            AutoMocker&lt;TARGETCLASS&gt; mocker;
            ServiceLocator serviceLocator;
            switch (framework)
            {
                case AutoMockType.RhinoMocksAAA:
                    mocker = new RhinoAutoMocker&lt;TARGETCLASS&gt;(MockMode.AAA);
                    serviceLocator = new RhinoMocksAAAServiceLocator();
                    break;
                case AutoMockType.RhinoMocksClassic:
                    mocker = new RhinoAutoMocker&lt;TARGETCLASS&gt;(MockMode.RecordAndReplay);
                    serviceLocator = new RhinoMocksClassicServiceLocator();
                    break;
                case AutoMockType.Moq:
                    mocker = new MoqAutoMocker&lt;TARGETCLASS&gt;();
                    serviceLocator = new MoqServiceLocator();
                    break;
                default:
                    throw new ArgumentOutOfRangeException("framework");
            }
            return new ClassUnderTest&lt;TARGETCLASS&gt;(mocker, serviceLocator);
        }
    }

    public enum AutoMockType
    {
        Moq,
        RhinoMocksAAA,
        RhinoMocksClassic
    }

    public class ClassUnderTest&lt;TARGETCLASS&gt; where TARGETCLASS : class
    {
        readonly IAutoMocker&lt;TARGETCLASS&gt; _mocker;
        readonly ServiceLocator _serviceLocator;

        public ClassUnderTest(IAutoMocker&lt;TARGETCLASS&gt; mocker, ServiceLocator serviceLocator)
        {
            _mocker = mocker;
            _serviceLocator = serviceLocator;
        }

        public AutoMockedContainer Container
        {
            get { return _mocker.Container; }
        }

        public TARGETCLASS Instance
        {
            get { return _mocker.ClassUnderTest; }
        }

        public void MockObjectFactory()
        {
            _mocker.MockObjectFactory();
        }

        public void PartialMockTheClassUnderTest()
        {
            _mocker.PartialMockTheClassUnderTest();
        }

        public T Get&lt;T&gt;() where T : class
        {
            return _mocker.Get&lt;T&gt;();
        }

        public void Inject(Type pluginType, object stub)
        {
            _mocker.Inject(pluginType, stub);
        }

        public void Inject&lt;T&gt;(T target)
        {
            _mocker.Inject(target);
        }

        public T AddAdditionalMockFor&lt;T&gt;() where T : class
        {
            return _mocker.AddAdditionalMockFor&lt;T&gt;();
        }

        public void UseConcreteClassFor&lt;T&gt;()
        {
            _mocker.UseConcreteClassFor&lt;T&gt;();
        }

        public T[] CreateMockArrayFor&lt;T&gt;(int count) where T : class
        {
            return _mocker.CreateMockArrayFor&lt;T&gt;(count);
        }

        public void InjectArray&lt;T&gt;(T[] stubs)
        {
            _mocker.InjectArray(stubs);
        }

        public T Mock&lt;T&gt;() where T : class
        {
            return _serviceLocator.Service&lt;T&gt;();
        }
        public object Mock(Type serviceType)
        {
            return _serviceLocator.Service(serviceType);
        }
        public T PartialMock&lt;T&gt;() where T : class
        {
            return _serviceLocator.PartialMock&lt;T&gt;();
        }
    }
}</pre>
</ul>
<script type="text/javascript">// <![CDATA[
 var cirerolGaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."); document.write(unescape("%3Cscript src='" + cirerolGaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
// ]]&gt;</script>

<script type="text/javascript">// <![CDATA[
 var cirerolPageTracker = _gat._getTracker('UA-8257866-3'); cirerolPageTracker._initData(); cirerolPageTracker._trackPageview();
// ]]&gt;</script>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/11/30/wrapping-up-the-structuremap-automocking-container/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Integration Test Brought to you by Powershell &amp; NUnit &#8211; with a Little Specification Syntax for Flavoring</title>
		<link>http://elegantcode.com/2009/10/25/integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring</link>
		<comments>http://elegantcode.com/2009/10/25/integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring/#comments</comments>
		<pubDate>Mon, 26 Oct 2009 05:00:40 +0000</pubDate>
		<dc:creator>Jason Jarrett</dc:creator>
				<category><![CDATA[Esoterica]]></category>
		<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/10/25/integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring/</guid>
		<description><![CDATA[One of the tools I’ve used the last half of a year and really enjoyed is the C# specification extension methods when writing unit test assertions. If you’re looking for a little more background on the topic, I wrote about Fluent Specification Extensions in a past blog. Recently I wanted to execute a PowerShell script [...]]]></description>
			<content:encoded><![CDATA[One of the tools I’ve used the last half of a year and really enjoyed is the C# specification extension methods when writing unit test assertions. If you’re looking for a little more background on the topic, I wrote about <a href="http://staxmanade.blogspot.com/2009/02/fluent-specification-extensions.html">Fluent Specification Extensions</a> in a past blog.

Recently I wanted to execute a PowerShell script to do some automated <a href="http://en.wikipedia.org/wiki/Functional_testing">functional testing</a>. I wanted to execute an application and apply some assertions on the output of the software(basically running a console app, parse the xml output and assert on values in the output).
<blockquote>FYI: I’m very new to PowerShell, so any suggestions on how I implemented the below are welcome…</blockquote>
I’ve seen a couple examples of writing test assertions in PowerShell out there. One example is <a href="http://www.psunit.org/">PSUnit</a>; however, this seemed a little heavy for my needs and not quite the syntactic sugar I was looking for.

Besides the syntax flavor I was desiring, another thing I wanted to do was leverage the power of NUnit.Framework’s assertion capabilities. I like the error messages generated when strings and other objects fail the assertion.
<h5>Examples of end result ShouldLookLike()…</h5>
$true.ShouldBeTrue()
$false.ShouldBeFalse()
"a".ShouldEqual("a")
"a".ShouldNotEqual("b")
<h5><strong>Step 1</strong>: Figure out how to write a C# style <a href="http://msdn.microsoft.com/en-us/library/bb383977.aspx">extension method</a> in PowerShell.</h5>
<blockquote>I found a great blog post describing how to extend any PowerShell object to add extension methods.

<a href="http://bartdesmet.net/blogs/bart/archive/2007/09/06/extension-methods-in-windows-powershell.aspx">Extension Methods in Windows PowerShell</a></blockquote>
In short, to extend types in PowerShell leveraging the <a href="http://msdn.microsoft.com/en-us/library/ms714419(VS.85).aspx">Extended Type System</a>, you need to define them in an xml file and import the method definitions into the PowerShell runtime instance.

Below is PowerShell XML definition for my NUnit Specification Extensions.
<pre class="brush: xml;">&lt;?xml version="1.0" encoding="utf-16"?&gt;
&lt;Types&gt;
    &lt;Type&gt;
        &lt;Name&gt;System.Object&lt;/Name&gt;
        &lt;Members&gt;
            &lt;ScriptMethod&gt;
                &lt;Name&gt;ShouldBeFalse&lt;/Name&gt;
                &lt;Script&gt;
                    [NUnit.Framework.Assert]::IsFalse($this)
                &lt;/Script&gt;
            &lt;/ScriptMethod&gt;
            &lt;ScriptMethod&gt;
                &lt;Name&gt;ShouldBeTrue&lt;/Name&gt;
                &lt;Script&gt;
                    [NUnit.Framework.Assert]::IsTrue($this)
                &lt;/Script&gt;
            &lt;/ScriptMethod&gt;
            &lt;ScriptMethod&gt;
                &lt;Name&gt;ShouldEqual&lt;/Name&gt;
                &lt;Script&gt;
                    [NUnit.Framework.Assert]::AreEqual($args[0], $this)
                &lt;/Script&gt;
            &lt;/ScriptMethod&gt;
            &lt;ScriptMethod&gt;
                &lt;Name&gt;ShouldNotEqual&lt;/Name&gt;
                &lt;Script&gt;
                    [NUnit.Framework.Assert]::AreNotEqual($args[0], $this)
                &lt;/Script&gt;
            &lt;/ScriptMethod&gt;
        &lt;/Members&gt;
    &lt;/Type&gt;
&lt;/Types&gt;</pre>
<h4></h4>
Take the above XML and save it to a file…
<blockquote>NOTE: the file HAS to be saved with the extension <strong>.ps1xml</strong>

Ex: NunitSpecificationPowerShellExtensions<strong>.ps1xml</strong></blockquote>
<h4></h4>
<h5>Step 2: Load the extended type definition into the PowerShell runtime.</h5>
Once you’ve saved the XML extended types to a file, you need to load it into the PowerShell runtime by executing the command below.
<blockquote>
Update-TypeData -PrependPath NunitSpecificationPowerShellExtensions.ps1xml</blockquote>
Before executing the above statement…Let’s quickly look at a System.String’s members and properties – just to show you what the extension methods look like when applied inside of the runtime.<a href="http://elegantcode.com/wp-content/uploads/2009/10/image3.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" src="http://elegantcode.com/wp-content/uploads/2009/10/image_thumb2.png" border="0" alt="image" width="586" height="479" /></a>

After executing the Update-TypeData command you’ll notice there are a number of “ScriptMethod” MemberTypes added to the object.

<a href="http://elegantcode.com/wp-content/uploads/2009/10/image4.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" src="http://elegantcode.com/wp-content/uploads/2009/10/image_thumb3.png" border="0" alt="image" width="600" height="580" /></a>

Now if you try to execute one of those newly added extension methods, you may get the following error…

PS C:\&gt; $testVar.<strong>ShouldEqual</strong>("hello world")

Exception calling "ShouldEqual" with "1" argument(s): "<strong>Unable to find type [NUnit.Framework.Assert]: make sure that the

assembly containing this type is loaded.</strong>"

At line:1 char:21

+ $testVar.ShouldEqual &lt;&lt;&lt;&lt; ("hello world")

+ CategoryInfo          : NotSpecified: (:) [], MethodInvocationException

+ FullyQualifiedErrorId : ScriptMethodRuntimeException

This is because we need to load the NUnit.Framework assembly into the runtime before we can leverage the extension methods.
<blockquote>[System.Reflection.Assembly]::LoadFrom("C:\Program Files\NUnit 2.5.2\bin\net-2.0\framework\nunit.framework.dll") | Out-Null</blockquote>
Now that the extension methods have been defined and loaded into the runtime, NUnit.Framework is loaded, we can now use the methods on any object that inherits from System.Object (which, as far as I know, is everything in PowerShell).

And now, everything you need in one script (if you have the xml extended type file saved somewhere…)
<pre>#
# Update-TypeData -prependPath C:\Code\NunitSpecificationPowerShellExtensions.ps1xml
#

[System.Reflection.Assembly]::LoadFrom("C:\Program Files\NUnit 2.5.2\bin\net-2.0\framework\nunit.framework.dll") | Out-Null

$true.ShouldBeTrue()

$false.ShouldBeFalse()

"a".ShouldEqual("a")

"a".ShouldNotEqual("b")</pre>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/10/25/integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Visual Studio Team System for Small Teams</title>
		<link>http://elegantcode.com/2009/10/25/integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring</link>
		<comments>http://elegantcode.com/2009/10/25/integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring/#comments</comments>
		<pubDate>Mon, 26 Oct 2009 05:00:40 +0000</pubDate>
		<dc:creator>Jason Jarrett</dc:creator>
				<category><![CDATA[Esoterica]]></category>
		<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/10/25/integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring/</guid>
		<description><![CDATA[One of the tools I’ve used the last half of a year and really enjoyed is the C# specification extension methods when writing unit test assertions. If you’re looking for a little more background on the topic, I wrote about Fluent Specification Extensions in a past blog. Recently I wanted to execute a PowerShell script [...]]]></description>
			<content:encoded><![CDATA[One of the tools I’ve used the last half of a year and really enjoyed is the C# specification extension methods when writing unit test assertions. If you’re looking for a little more background on the topic, I wrote about <a href="http://staxmanade.blogspot.com/2009/02/fluent-specification-extensions.html">Fluent Specification Extensions</a> in a past blog.

Recently I wanted to execute a PowerShell script to do some automated <a href="http://en.wikipedia.org/wiki/Functional_testing">functional testing</a>. I wanted to execute an application and apply some assertions on the output of the software(basically running a console app, parse the xml output and assert on values in the output).
<blockquote>FYI: I’m very new to PowerShell, so any suggestions on how I implemented the below are welcome…</blockquote>
I’ve seen a couple examples of writing test assertions in PowerShell out there. One example is <a href="http://www.psunit.org/">PSUnit</a>; however, this seemed a little heavy for my needs and not quite the syntactic sugar I was looking for.

Besides the syntax flavor I was desiring, another thing I wanted to do was leverage the power of NUnit.Framework’s assertion capabilities. I like the error messages generated when strings and other objects fail the assertion.
<h5>Examples of end result ShouldLookLike()…</h5>
$true.ShouldBeTrue()
$false.ShouldBeFalse()
"a".ShouldEqual("a")
"a".ShouldNotEqual("b")
<h5><strong>Step 1</strong>: Figure out how to write a C# style <a href="http://msdn.microsoft.com/en-us/library/bb383977.aspx">extension method</a> in PowerShell.</h5>
<blockquote>I found a great blog post describing how to extend any PowerShell object to add extension methods.

<a href="http://bartdesmet.net/blogs/bart/archive/2007/09/06/extension-methods-in-windows-powershell.aspx">Extension Methods in Windows PowerShell</a></blockquote>
In short, to extend types in PowerShell leveraging the <a href="http://msdn.microsoft.com/en-us/library/ms714419(VS.85).aspx">Extended Type System</a>, you need to define them in an xml file and import the method definitions into the PowerShell runtime instance.

Below is PowerShell XML definition for my NUnit Specification Extensions.
<pre class="brush: xml;">&lt;?xml version="1.0" encoding="utf-16"?&gt;
&lt;Types&gt;
    &lt;Type&gt;
        &lt;Name&gt;System.Object&lt;/Name&gt;
        &lt;Members&gt;
            &lt;ScriptMethod&gt;
                &lt;Name&gt;ShouldBeFalse&lt;/Name&gt;
                &lt;Script&gt;
                    [NUnit.Framework.Assert]::IsFalse($this)
                &lt;/Script&gt;
            &lt;/ScriptMethod&gt;
            &lt;ScriptMethod&gt;
                &lt;Name&gt;ShouldBeTrue&lt;/Name&gt;
                &lt;Script&gt;
                    [NUnit.Framework.Assert]::IsTrue($this)
                &lt;/Script&gt;
            &lt;/ScriptMethod&gt;
            &lt;ScriptMethod&gt;
                &lt;Name&gt;ShouldEqual&lt;/Name&gt;
                &lt;Script&gt;
                    [NUnit.Framework.Assert]::AreEqual($args[0], $this)
                &lt;/Script&gt;
            &lt;/ScriptMethod&gt;
            &lt;ScriptMethod&gt;
                &lt;Name&gt;ShouldNotEqual&lt;/Name&gt;
                &lt;Script&gt;
                    [NUnit.Framework.Assert]::AreNotEqual($args[0], $this)
                &lt;/Script&gt;
            &lt;/ScriptMethod&gt;
        &lt;/Members&gt;
    &lt;/Type&gt;
&lt;/Types&gt;</pre>
<h4></h4>
Take the above XML and save it to a file…
<blockquote>NOTE: the file HAS to be saved with the extension <strong>.ps1xml</strong>

Ex: NunitSpecificationPowerShellExtensions<strong>.ps1xml</strong></blockquote>
<h4></h4>
<h5>Step 2: Load the extended type definition into the PowerShell runtime.</h5>
Once you’ve saved the XML extended types to a file, you need to load it into the PowerShell runtime by executing the command below.
<blockquote>
Update-TypeData -PrependPath NunitSpecificationPowerShellExtensions.ps1xml</blockquote>
Before executing the above statement…Let’s quickly look at a System.String’s members and properties – just to show you what the extension methods look like when applied inside of the runtime.<a href="http://elegantcode.com/wp-content/uploads/2009/10/image3.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" src="http://elegantcode.com/wp-content/uploads/2009/10/image_thumb2.png" border="0" alt="image" width="586" height="479" /></a>

After executing the Update-TypeData command you’ll notice there are a number of “ScriptMethod” MemberTypes added to the object.

<a href="http://elegantcode.com/wp-content/uploads/2009/10/image4.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" src="http://elegantcode.com/wp-content/uploads/2009/10/image_thumb3.png" border="0" alt="image" width="600" height="580" /></a>

Now if you try to execute one of those newly added extension methods, you may get the following error…

PS C:\&gt; $testVar.<strong>ShouldEqual</strong>("hello world")

Exception calling "ShouldEqual" with "1" argument(s): "<strong>Unable to find type [NUnit.Framework.Assert]: make sure that the

assembly containing this type is loaded.</strong>"

At line:1 char:21

+ $testVar.ShouldEqual &lt;&lt;&lt;&lt; ("hello world")

+ CategoryInfo          : NotSpecified: (:) [], MethodInvocationException

+ FullyQualifiedErrorId : ScriptMethodRuntimeException

This is because we need to load the NUnit.Framework assembly into the runtime before we can leverage the extension methods.
<blockquote>[System.Reflection.Assembly]::LoadFrom("C:\Program Files\NUnit 2.5.2\bin\net-2.0\framework\nunit.framework.dll") | Out-Null</blockquote>
Now that the extension methods have been defined and loaded into the runtime, NUnit.Framework is loaded, we can now use the methods on any object that inherits from System.Object (which, as far as I know, is everything in PowerShell).

And now, everything you need in one script (if you have the xml extended type file saved somewhere…)
<pre>#
# Update-TypeData -prependPath C:\Code\NunitSpecificationPowerShellExtensions.ps1xml
#

[System.Reflection.Assembly]::LoadFrom("C:\Program Files\NUnit 2.5.2\bin\net-2.0\framework\nunit.framework.dll") | Out-Null

$true.ShouldBeTrue()

$false.ShouldBeFalse()

"a".ShouldEqual("a")

"a".ShouldNotEqual("b")</pre>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/10/25/integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Elegant Code &#187; Unit Testing</title>
	<atom:link href="http://elegantcode.com/category/unit-testing/feed/" rel="self" type="application/rss+xml" />
	<link>http://elegantcode.com</link>
	<description></description>
	<lastBuildDate>Tue, 15 May 2012 10:00:00 +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>AutoTest.NET</title>
		<link>http://elegantcode.com/2010/11/30/autotest-net/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=autotest-net</link>
		<comments>http://elegantcode.com/2010/11/30/autotest-net/#comments</comments>
		<pubDate>Tue, 30 Nov 2010 11:00:00 +0000</pubDate>
		<dc:creator>Jan Van Ryswyck</dc:creator>
				<category><![CDATA[TDD]]></category>
		<category><![CDATA[Tools and Utilities]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/11/30/autotest-net/</guid>
		<description><![CDATA[I just want to quickly point out a tool that I’ve been playing with for a couple of days now, named AutoTest.NET. Its an open-source tool that originates from a popular tool in the Ruby community called ZenTest, which basically runs all your valuable unit tests when you save your source files or when you [...]]]></description>
			<content:encoded><![CDATA[<p>I just want to quickly point out a tool that I’ve been playing with for a couple of days now, named <a href="https://github.com/acken/AutoTest.Net" target="_blank">AutoTest.NET</a>. Its an open-source tool that originates from a popular tool in the Ruby community called <a href="http://www.zenspider.com/ZSS/Products/ZenTest/" target="_blank">ZenTest</a>, which basically runs all your valuable unit tests when you save your source files or when you build your code. It enables you to get feedback about your changes as soon as possible.</p>  <p>The project started out a couple of years ago on <a href="http://code.google.com/p/autotestnet/" target="_blank">Google code</a> and was first initiated by <a href="http://averyblog.com/" target="_blank">James Avery</a>. Contribution stopped at some point until recently where <a href="http://ackenpacken.blogspot.com/" target="_blank">Svein Arne Ackenhausen</a> forked the source code and <a href="https://github.com/acken/AutoTest.Net" target="_blank">put it on GitHub</a>. Now it runs both for .NET as well as Mono, with NUnit, MSTest and xUnit as the currently supported unit test frameworks. </p>  <p>Here’s a screenshot from the feedback window when all tests pass:</p>  <p><a href="http://elegantcode.com/wp-content/uploads/2010/11/Success.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="Success" border="0" alt="Success" src="http://elegantcode.com/wp-content/uploads/2010/11/Success_thumb.png" width="540" height="189" /></a> </p>  <p>And here you can see the same window after I broke one of my unit tests:</p>  <p><a href="http://elegantcode.com/wp-content/uploads/2010/11/Failure.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="Failure" border="0" alt="Failure" src="http://elegantcode.com/wp-content/uploads/2010/11/Failure_thumb.png" width="538" height="319" /></a> </p>  <p>Here you can see which particular unit test has been broken and by clicking the specified link you end up at the right source file in Visual Studio. </p>  <p>I encourage you to pick up this small tool and learn how it can facilitate your TDD flow. Take a look at <a href="https://github.com/acken/AutoTest.Net/wiki/Get-started!" target="_blank">this page</a> in order to get up-and-running in no time. Also don’t forget to provide the owner(s) of this project with some feedback that you might have. Svein has been very helpful over the last week answering all my stupid questions and remarks (and the Nobel price for this year’s most patient person goes to … ;-) ). </p>  <p>I would definitely like to see this tool becoming more popular, so go check it out.&#160;&#160; </p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/11/30/autotest-net/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>If Self-Documenting Code is the What, Unit Tests are the Why</title>
		<link>http://elegantcode.com/2010/04/25/if-self-documenting-code-is-the-what-unit-tests-are-the-why/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=if-self-documenting-code-is-the-what-unit-tests-are-the-why</link>
		<comments>http://elegantcode.com/2010/04/25/if-self-documenting-code-is-the-what-unit-tests-are-the-why/#comments</comments>
		<pubDate>Sun, 25 Apr 2010 19:09:04 +0000</pubDate>
		<dc:creator>John Sonmez</dc:creator>
				<category><![CDATA[Agile]]></category>
		<category><![CDATA[Architecture]]></category>
		<category><![CDATA[Craftsmanship]]></category>
		<category><![CDATA[Documentation]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/04/25/if-self-documenting-code-is-the-what-unit-tests-are-the-why/</guid>
		<description><![CDATA[It is not enough to just write code that is clean and self-documenting.  Eliminating comments and replacing them with clear variable and method names, will tell the reader of your code clearly what it is doing, but it will not properly express why it is doing it. If you recall from my original post on [...]]]></description>
			<content:encoded><![CDATA[It is not enough to just write code that is clean and self-documenting.  <a href="http://elegantcode.com/2010/04/18/eliminating-comments-the-road-to-clarity/">Eliminating comments</a> and replacing them with clear variable and method names, will tell the reader of your code clearly what it is doing, but it will not properly express why it is doing it.

If you recall from my <a href="http://elegantcode.com/2010/04/09/what-does-elegant-code-mean-to-me/">original post</a> on Elegant code, I stated that elegant code is:
<blockquote>Something that is simple yet effective, delivered with grace.</blockquote>
By writing self-documenting code we are hopefully able to achieve some of the aspects of simplicity and grace, but it tells us nothing about the effectiveness of the code.
<h2>Bringing the dead to life</h2>
<a href="http://elegantcode.com/wp-content/uploads/2010/04/zombies.jpg"><img style="border-right-width: 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; margin-left: auto; border-left-width: 0px; margin-right: auto" title="zombies" src="http://elegantcode.com/wp-content/uploads/2010/04/zombies_thumb.jpg" border="0" alt="zombies" width="441" height="295" /></a>

Throwing out comments is a debatable topic.  <a href="http://www.reddit.com/r/programming/comments/bsutx/">It raises quite a bit of controversy</a>, as you can see from some of the comments on my post about the subject.  The reason, perhaps, that so many people are so staunchly opposed to the idea, is because they are worried, and rightly so, that throwing out comments will reduce the documentation of what the code is doing.

Think about that for a second.  Is documentation of what the code is doing important?  It better be.  What we are trying to accomplish by writing self-documenting code instead of comments, is to take the vessel, which is the code itself, and make that same vessel be the documentation of what the code does.  It is by doing this that we creating a living representation of the functionality of the code.  Comments are akin to a dead representation of the functionality of the code because they do not change automatically with the code.

I diverge to talk about comments so that I can draw a parallel to another form of documentation which is valuable and should be considered necessary.  That other set of documentation is requirements.  Have you ever written requirements documents?  Have you ever captured requirements from the customer and put them into UML diagrams, or perhaps plopped them into some templated Word document, which is never updated again, and no one reads, because no one trusts it is correct?  Wouldn’t it be great if we would replace that dead document or set of documents, with a living one?

The good news is we can, and some of us have.  And I fully expect this recommendation will be just as controversial, because <strong>I am suggesting that we don’t have to write low level specifications of the system at all, instead we can write good unit tests. </strong>When we do this, we are taking a dead form of document and bringing it to life.
<h2>Unit tests tell us why and how our code is effective</h2>
If
<pre class="csharpcode">i = 5;  // Widget count defaults to five.</pre>
is replaced with
<pre class="csharpcode">widgetCount = DEFAULT_WIDGET_COUNT;</pre>
<!--.csharpcode, .csharpcode pre { 	font-size: small; 	color: black; 	font-family: consolas, "Courier New", courier, monospace; 	background-color: #ffffff; 	/*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt  { 	background-color: #f4f4f4; 	width: 100%; 	margin: 0em; } .csharpcode .lnum { color: #606060; } -->

then
<blockquote><span style="background-color: #ffffff;">1.1.5 When a new widget is created, the widget count should be increased by one.</span></blockquote>
is replaced with
<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">void</span> When_NewWidgetIsCreated_Then_WidgetCountIsIncreasedByOne()
{
     WidgetFactory.Count = 3;
     WidgetFactory.CreateNew();
     assertEquals(4, WidgetFactory.Count);
}</pre>
The unit test is replacing the low level requirement, which is somewhat open to interpretation and untied to the code, with an absolute and completely tied-to-the-code, specific requirement.

The unit test is telling us why our code is built the way it is.  It is telling us what requirement that particular structure of code is trying to address.  <strong>It is telling us what end result that code is trying to accomplish and what the expectations are on the results of a given condition.</strong>

The unit test is telling us how the code is to be used in order to achieve its result.  It is serving as a living reference to the syntax and use of the code we built.  <strong>Instead of providing instructions on how to use our API, we are providing a living example, and proof that it will indeed work.</strong> Examples are often much more effective than instructions anyway.
<h2>What exactly are we replacing?</h2>
At this point we are not trying to replace all the documentation of the system (at this point).

With self-documenting code, we sought to eliminate comments, and replace them with good variable and method names.

With unit tests, we seek to eliminate technical documentation and requirements of the system, that is targeted at a developer or technical audience.

We are NOT trying to eliminate high level specifications of the system, or use cases. <strong>Unit tests DO NOT replace that kind of documentation! </strong>We will talk about replacing that kind of documentation when we talk about automated functional or system tests.

Simply put, any kind of documentation that you would give to a developer so they understand how the system works and how to use the code or APIs, can be easily replaced by writing good unit tests.

Our simple goal is to replace the “dead” documentation (meaning that it does not update automatically with the thing it is documenting), with “living” documentation in the form of unit tests.

One last point.  I want to be clear that I am not saying that having unit tests automatically results in the ability to replace technical documentation.  Just like having long-named methods and variables doesn’t automatically replace the need for comments.  It is a matter of the quality of the unit tests that are written, just as it is a matter of the quality of the self-documenting code.
<h5>As always, you can subscribe to this <a href="http://feeds2.feedburner.com/ElegantCode">RSS feed</a> to follow my posts on elegant code.  Feel free to check out my main personal blog at <a href="http://simpleprogrammer.com">http://simpleprogrammer.com</a>, which has a wider range of posts, updated 2-3 times a week.  Also, you can follow me on twitter <a href="http://twitter.com/jsonmez">here</a>.</h5>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/04/25/if-self-documenting-code-is-the-what-unit-tests-are-the-why/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Behaviors with MSpec</title>
		<link>http://elegantcode.com/2010/02/26/behaviors-with-mspec/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=behaviors-with-mspec</link>
		<comments>http://elegantcode.com/2010/02/26/behaviors-with-mspec/#comments</comments>
		<pubDate>Fri, 26 Feb 2010 23:33:28 +0000</pubDate>
		<dc:creator>Jan Van Ryswyck</dc:creator>
				<category><![CDATA[BDD]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/02/26/behaviors-with-mspec/</guid>
		<description><![CDATA[In my previous posts, I showed the syntax for context/specifications using Machine.Specifications (or MSpec for short) and how to use an auto mocking container in conjunction with this excellent Behavior-Driven Development (BDD) framework. For this post, I want to show you one of the nice features of MSpec called behaviors. Suppose we have to create [...]]]></description>
			<content:encoded><![CDATA[<p>In my previous posts, I showed the <a href="http://elegantcode.com/2010/02/19/getting-started-with-machine-specifications-mspec/">syntax for context/specifications</a> using <a href="http://github.com/machine/machine.specifications">Machine.Specifications</a> (or MSpec for short) and <a href="http://elegantcode.com/2010/02/23/mspec-and-auto-mocking">how to use an auto mocking container</a> in conjunction with this excellent Behavior-Driven Development (BDD) framework. For this post, I want to show you one of the nice features of MSpec called <em>behaviors</em>.</p>  <p>Suppose we have to create some sort of specification that validates the format of an e-mail address. We typically use some regular expression in order to ensure that a specified e-mail address is properly formatted.</p>  <pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">class</span> EmailSpecification
{
    <span class="kwrd">private</span> <span class="kwrd">const</span> String EmailRegexPattern = <span class="str">@&quot;.. SOME_REGEX_PATTERN ...&quot;</span>;

    <span class="kwrd">public</span> Boolean IsSatisfiedBy(String candidate)
    {
        var regex = <span class="kwrd">new</span> Regex(EmailRegexPattern);
        <span class="kwrd">return</span> regex.IsMatch(candidate);
    }
}</pre>
<style type="text/css">

.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>I guess this is pretty common and straightforward. One way to provide some unit tests for this particular piece of code is to check a whole number of e-mail addresses that either pass or fail the specification. The following example shows only a couple of scenarios:</p>

<pre class="csharpcode">[TestFixture]
<span class="kwrd">public</span> <span class="kwrd">class</span> When_validating_an_email
    : ContextSpecification&lt;EmailSpecification&gt;
{
    <span class="kwrd">protected</span> <span class="kwrd">override</span> EmailSpecification Create_subject_under_test()
    {
        <span class="kwrd">return</span> <span class="kwrd">new</span> EmailSpecification();
    }

    [Test]
    <span class="kwrd">public</span> <span class="kwrd">void</span> ShouldBeSatisfied()
    {
        Assert.That(SUT.IsSatisfiedBy(<span class="str">&quot;one2@three.com&quot;</span>));
        Assert.That(SUT.IsSatisfiedBy(<span class="str">&quot;one@two3.com&quot;</span>));
    }

    [Test]
    <span class="kwrd">public</span> <span class="kwrd">void</span> ShouldNotBeSatisfied()
    {
        Assert.That(SUT.IsSatisfiedBy(<span class="str">&quot;one_two.com&quot;</span>), Is.False);
        Assert.That(SUT.IsSatisfiedBy(<span class="str">&quot;one_two@&quot;</span>), Is.False);
    }
}</pre>
<style type="text/css">

.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>A slightly more concise approach for these kind of unit tests can be accomplished by utilizing a feature of any decent unit test framework called <em>row tests. </em>With this approach we can, at the very least, reduce the number of asserts we have to write for each unit test.<em>&#160;</em></p>

<pre class="csharpcode">[TestFixture]
<span class="kwrd">public</span> <span class="kwrd">class</span> When_validating_an_email__approach_2
    : ContextSpecification&lt;EmailSpecification&gt;
{
    <span class="kwrd">protected</span> <span class="kwrd">override</span> EmailSpecification Create_subject_under_test()
    {
        <span class="kwrd">return</span> <span class="kwrd">new</span> EmailSpecification();
    }

    [RowTest]
    [Row(<span class="str">&quot;one2@three.com&quot;</span>)]
    [Row(<span class="str">&quot;one@two3.com&quot;</span>)]
    <span class="kwrd">public</span> <span class="kwrd">void</span> ShouldBeSatisfied(String email)
    {
        Assert.That(SUT.IsSatisfiedBy(email));
    }

    [RowTest]
    [Row(<span class="str">&quot;one_two.com&quot;</span>)]
    [Row(<span class="str">&quot;one_two@&quot;</span>)]
    <span class="kwrd">public</span> <span class="kwrd">void</span> ShouldNotBeSatisfied(String email)
    {
        Assert.That(SUT.IsSatisfiedBy(email), Is.False);
    }
}</pre>
<style type="text/css">

.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>Notice that I explicitly called both of these approaches <em>unit tests</em> as they don’t have much to do with BDD in my opinion. I’m not saying that using regular unit tests is a bad thing, but with&#160; behavior-driven development context is king. So these unit tests are perfect examples of ‘<a href="http://elegantcode.com/2008/12/30/dont-sell-out-on-the-context-dude/">context betrayal</a>’ when following the BDD approach. </p>

<p>Lets see what MSpec can bring to the table for these kind of scenarios:</p>

<pre class="csharpcode">[Subject(<span class="kwrd">typeof</span>(EmailSpecification), <span class="str">&quot;is satisfied&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_validating_an_email_address_with_a_number_in_the_local_part
    : email_specification_specs
{
    Establish context = () =&gt;
        EmailAddress = <span class="str">&quot;one2@three.com&quot;</span>;

    Behaves_like&lt;SatisfiedSpecificationBehavior&gt; a_satisfied_specification;
}

[Subject(<span class="kwrd">typeof</span>(EmailSpecification), <span class="str">&quot;is satisfied&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_validating_an_email_address_with_a_number_in_the_domain_name
    : email_specification_specs
{
    Establish context = () =&gt;
        EmailAddress = <span class="str">&quot;one@two3.com&quot;</span>;

    Behaves_like&lt;SatisfiedSpecificationBehavior&gt; a_satisfied_specification;
}

[Subject(<span class="kwrd">typeof</span>(EmailSpecification), <span class="str">&quot;is satisfied&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_validating_an_email_address_without_an_At_sign
    : email_specification_specs
{
    Establish context = () =&gt;
        EmailAddress = <span class="str">&quot;one_two.com&quot;</span>;

    Behaves_like&lt;UnsatisfiedSpecificationBehavior&gt; an_unsatisfied_specification;
}

[Subject(<span class="kwrd">typeof</span>(EmailSpecification), <span class="str">&quot;is satisfied&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_validating_an_email_address_without_a_domain
    : email_specification_specs
{
    Establish context = () =&gt;
        EmailAddress = <span class="str">&quot;one_two@&quot;</span>;

    Behaves_like&lt;UnsatisfiedSpecificationBehavior&gt; an_unsatisfied_specification;
}</pre>
<style type="text/css">

.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>In order to escape ‘context betrayal’, we’ve split up every context into a separate context/specification. In order to reduce the amount of effort caused by duplicate code, we stripped the context setup to the bare minimum (just a particular e-mail address in this case). The observations are isolated into MSpec behaviors which provides a very readable description of their outcome. Lets take a look at what is needed in order to get these <em>behaviors</em> to work.</p>

<p>But first lets take at look at the abstract base class that we’ve used for the context/specifications we’ve just shown.</p>

<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">abstract</span> <span class="kwrd">class</span> email_specification_specs
{
    Establish context = () =&gt;
    {
        SUT = <span class="kwrd">new</span> EmailSpecification();
    };

    Because of = () =&gt;
        Result = SUT.IsSatisfiedBy(EmailAddress);

    <span class="kwrd">protected</span> <span class="kwrd">static</span> Boolean Result;
    <span class="kwrd">protected</span> <span class="kwrd">static</span> String EmailAddress { get; set; }
    <span class="kwrd">protected</span> <span class="kwrd">static</span> EmailSpecification SUT { get; set; }
}</pre>

<p><style type="text/css">

.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style></p>

<p>&#160;</p>

<p>We abstracted as much as possible into this base class in order to remove duplication in the context/specifications. The creation of the subject-under-test and the calling of its <em>IsSatisfiedBy</em> method, but the important one is the declaration of the <em>Result</em> field. This field contains the outcome of the <em>IsSatisfiedBy</em> method. Finally, lets have a look at the behaviors themselves:</p>

<pre class="csharpcode">[Behaviors]
<span class="kwrd">public</span> <span class="kwrd">class</span> SatisfiedSpecificationBehavior
{
    <span class="kwrd">protected</span> <span class="kwrd">static</span> Boolean Result;
    
    It should_satisfy_the_specification = () =&gt;
        Result.ShouldBeTrue();
}

[Behaviors]
<span class="kwrd">public</span> <span class="kwrd">class</span> UnsatisfiedSpecificationBehavior
{
    <span class="kwrd">protected</span> <span class="kwrd">static</span> Boolean Result;

    It should_not_satisfy_the_specification = () =&gt;
        Result.ShouldBeFalse();
}</pre>
<style type="text/css">

.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>In order to create an MSpec behavior, we just have to create a separate class that we decorate with the <em>Behaviors</em> attribute. Also notice that we have the same declaration of the <em>Result</em> field. MSpec ensures that this field gets initialized with the value of the other <em>Result</em> field that is set in the base class of the context/specifications. Note that you don’t necessarily need to put this field in a base class. You can have that field in every context/specification if you’d like (not sure why) as long as the names match with the fields used in the defined behaviors.</p>

<p>I personally like the way how the MSpec contributors tried to solve testing the same logic with different input patterns and the syntax they provided to back this up.&#160;&#160; </p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/02/26/behaviors-with-mspec/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>MSpec and Auto Mocking</title>
		<link>http://elegantcode.com/2010/02/23/mspec-and-auto-mocking/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=mspec-and-auto-mocking</link>
		<comments>http://elegantcode.com/2010/02/23/mspec-and-auto-mocking/#comments</comments>
		<pubDate>Tue, 23 Feb 2010 20:38:54 +0000</pubDate>
		<dc:creator>Jan Van Ryswyck</dc:creator>
				<category><![CDATA[BDD]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/02/23/mspec-and-auto-mocking/</guid>
		<description><![CDATA[In my previous post, I explained how to get started with Machine.Specifications (or MSpec for short) and showed you how the syntax for context/specifications looks like when using this BDD framework. For this post, I want to show you how to use an auto mocking container (we’ll be using the one provided by StructureMap off [...]]]></description>
			<content:encoded><![CDATA[<p>In my <a href="http://elegantcode.com/2010/02/19/getting-started-with-machine-specifications-mspec/">previous post</a>, I explained how to get started with <a href="http://github.com/machine/machine.specifications">Machine.Specifications</a> (or MSpec for short) and showed you how the syntax for context/specifications looks like when using this BDD framework. For this post, I want to show you how to use an <a href="http://vanryswyckjan.blogspot.com/2008/01/automocking-container.html">auto mocking container</a> (we’ll be using the one provided by StructureMap off course).</p>  <p>We’ll use the same example as the one used in the previous post, but now we’ll deal with the message handler that makes a particular customer preferred.</p> <style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>  <pre class="csharpcode"><span class="rem">//</span>
<span class="rem">// Subject under test</span>
<span class="rem">//</span>
<span class="kwrd">public</span> <span class="kwrd">class</span> MakeCustomerPreferredMessageHandler
{
    <span class="kwrd">private</span> <span class="kwrd">readonly</span> ICustomerRepository&lt;ICanMakeCustomerPreferred&gt; _repository;

    <span class="kwrd">public</span> MakeCustomerPreferredMessageHandler(
        ICustomerRepository&lt;ICanMakeCustomerPreferred&gt; repository)
    {
        _repository = repository;
    }

    <span class="kwrd">public</span> <span class="kwrd">void</span> Handle(MakeCustomerPreferredMessage message)
    {
        var customer = _repository.Get(message.CustomerId);
        <span class="kwrd">if</span>(<span class="kwrd">null</span> == customer)
            <span class="kwrd">throw</span> <span class="kwrd">new</span> InvalidOperationException(
                <span class="str">&quot;No customer for specified identifier&quot;</span>);
        
        customer.MakePreferred();
        _repository.Save(customer);
    }
}</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>The <em>Customer</em> class implements a ‘<a href="http://martinfowler.com/bliki/RoleInterface.html">role interface’</a> called <em>ICanMakeCustomerPreferred</em>. We retrieve a customer from the repository and make it preferred. We throw an exception in case the customer cannot be found in the data store.</p>

<p>Here are the context/specifications for this easy example:</p>

<pre class="csharpcode">[Subject(<span class="str">&quot;Making a customer preferred&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_making_a_customer_preferred
    : context_specification&lt;MakeCustomerPreferredMessageHandler&gt;
{
    Establish context = () =&gt;
    {
        _message = <span class="kwrd">new</span> MakeCustomerPreferredMessage { CustomerId = 6412 };

        Repository.Stub(repository =&gt; repository.Get(_message.CustomerId))
            .Return(Customer);
    };

    Because of = () =&gt; 
        SUT.Handle(_message);
    
    It should_mark_the_customer_as_preferred = () =&gt;
        Customer.AssertWasCalled(customer =&gt; customer.MakePreferred());

    It should_save_the_customer_in_the_repository = () =&gt;
        Repository.AssertWasCalled(repository =&gt; repository.Save(Customer));

    <span class="kwrd">private</span> <span class="kwrd">static</span> ICanMakeCustomerPreferred Customer
    {
        get { <span class="kwrd">return</span> Dependency&lt;ICanMakeCustomerPreferred&gt;(); }
    }

    <span class="kwrd">private</span> <span class="kwrd">static</span> ICustomerRepository&lt;ICanMakeCustomerPreferred&gt; Repository
    {
        get { <span class="kwrd">return</span> Dependency&lt;ICustomerRepository&lt;ICanMakeCustomerPreferred&gt;&gt;(); }
    }

    <span class="kwrd">private</span> <span class="kwrd">static</span> MakeCustomerPreferredMessage _message;
}

[Subject(<span class="str">&quot;Making a customer preferred&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_making_an_unexisting_customer_preferred
    : context_specification&lt;MakeCustomerPreferredMessageHandler&gt;
{
    Establish context = () =&gt;   
    {
        _message = <span class="kwrd">new</span> MakeCustomerPreferredMessage() { CustomerId = 61544 };

        Dependency&lt;ICustomerRepository&lt;ICanMakeCustomerPreferred&gt;&gt;()
            .Stub(repository =&gt; repository.Get(_message.CustomerId))
            .Return(<span class="kwrd">null</span>);
    };

    Because of = () =&gt;
        _resultingException = Catch.Exception(() =&gt; SUT.Handle(_message));

    It should_result_in_an_error = () =&gt;
        _resultingException.ShouldBeOfType&lt;InvalidOperationException&gt;();

    <span class="kwrd">private</span> <span class="kwrd">static</span> MakeCustomerPreferredMessage _message;
    <span class="kwrd">private</span> <span class="kwrd">static</span> Exception _resultingException;
}</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>I want to point out that all fields and properties are made static. This is needed so that the anonymous methods can access them. I’m also using a base class for these specifications which I’ll show next. This base class uses an auto mocking container for providing the requested mocks and stubs through the <em>Dependency</em> and <em>Stub</em> methods. </p>

<pre class="csharpcode"><span class="kwrd">public</span> <span class="kwrd">abstract</span> <span class="kwrd">class</span> context_specification&lt;TSubjectUnderTest&gt;
    <span class="kwrd">where</span> TSubjectUnderTest : <span class="kwrd">class</span>
{
    <span class="kwrd">private</span> <span class="kwrd">static</span> IAutoMockingContainer&lt;TSubjectUnderTest&gt; _autoMockingContainer;
    <span class="kwrd">protected</span> <span class="kwrd">static</span> TSubjectUnderTest SUT { get; set; }

    Establish context = () =&gt;
    {
        _autoMockingContainer = <span class="kwrd">new</span> StructureMapAMC&lt;TSubjectUnderTest&gt;();
        SUT = _autoMockingContainer.Create();     
    };
    
    Cleanup stuff = () =&gt; 
    {
        SUT = <span class="kwrd">null</span>;
        _autoMockingContainer = <span class="kwrd">null</span>;
    };

    <span class="kwrd">protected</span> <span class="kwrd">static</span> TDependency Dependency&lt;TDependency&gt;()
        <span class="kwrd">where</span> TDependency : <span class="kwrd">class</span>
    {
        <span class="kwrd">return</span> _autoMockingContainer.GetMock&lt;TDependency&gt;();
    }

    <span class="kwrd">protected</span> <span class="kwrd">static</span> TStub Stub&lt;TStub&gt;()
        <span class="kwrd">where</span> TStub : <span class="kwrd">class</span>
    {
        <span class="kwrd">return</span> _autoMockingContainer.GetStub&lt;TStub&gt;();
    }
}

<span class="kwrd">public</span> <span class="kwrd">interface</span> IAutoMockingContainer&lt;TSubject&gt;
    <span class="kwrd">where</span> TSubject : <span class="kwrd">class</span>
{
    TSubject Create();
    TMock GetMock&lt;TMock&gt;() <span class="kwrd">where</span> TMock : <span class="kwrd">class</span>;
    TStub GetStub&lt;TStub&gt;() <span class="kwrd">where</span> TStub : <span class="kwrd">class</span>;
}

<span class="kwrd">public</span> <span class="kwrd">class</span> StructureMapAMC&lt;TSubject&gt; 
    : IAutoMockingContainer&lt;TSubject&gt;
    <span class="kwrd">where</span> TSubject : <span class="kwrd">class</span>
{
    <span class="kwrd">private</span> <span class="kwrd">readonly</span> RhinoAutoMocker&lt;TSubject&gt; _rhinoAutoMocker;

    <span class="kwrd">public</span> StructureMapAMC()
    {
        _rhinoAutoMocker = 
            <span class="kwrd">new</span> RhinoAutoMocker&lt;TSubject&gt;(MockMode.AAA);
    }

    <span class="kwrd">public</span> TSubject Create()
    {
        <span class="kwrd">return</span> _rhinoAutoMocker.ClassUnderTest;
    }

    <span class="kwrd">public</span> TMock GetMock&lt;TMock&gt;() 
        <span class="kwrd">where</span> TMock : <span class="kwrd">class</span>
    {
        <span class="kwrd">return</span> GetDependency&lt;TMock&gt;();
    }

    <span class="kwrd">public</span> TStub GetStub&lt;TStub&gt;() 
        <span class="kwrd">where</span> TStub : <span class="kwrd">class</span>
    {
        <span class="kwrd">return</span> GetDependency&lt;TStub&gt;();
    }

    <span class="kwrd">private</span> TDependency GetDependency&lt;TDependency&gt;() 
        <span class="kwrd">where</span> TDependency : <span class="kwrd">class</span>
    {
        <span class="kwrd">return</span> _rhinoAutoMocker.Get&lt;TDependency&gt;();
    }
}</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>Notice that I’m using the <em>Establish</em> and <em>Cleanup</em> delegates in the <em>context_specification</em> base class. This doesn’t prevent that these can be used again in derived context/specifications. MSpec ensures that the anonymous methods are called in the right order. This means that the <em>Establish</em> method of the base class is called before the <em>Establish</em> method of the derived context/specifications.&#160;&#160;&#160;&#160; </p>

<p>Absolutely no rocket science here, but I figured it might come in handy when you need it. For the next post I’ll try to demonstrate how to deal with reusable behaviors.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/02/23/mspec-and-auto-mocking/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Getting Started With Machine.Specifications (MSpec)</title>
		<link>http://elegantcode.com/2010/02/19/getting-started-with-machine-specifications-mspec/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=getting-started-with-machine-specifications-mspec</link>
		<comments>http://elegantcode.com/2010/02/19/getting-started-with-machine-specifications-mspec/#comments</comments>
		<pubDate>Fri, 19 Feb 2010 21:34:17 +0000</pubDate>
		<dc:creator>Jan Van Ryswyck</dc:creator>
				<category><![CDATA[BDD]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/02/19/getting-started-with-machine-specifications-mspec/</guid>
		<description><![CDATA[Its been a while since I evaluated and evolved my approach to BDD. The way I’ve been doing BDD up until now is described in this blog post which goes way back to 2008. Everyone has kind of their own style nowadays. Below you can find the code of two context/specifications for a method named [...]]]></description>
			<content:encoded><![CDATA[<p>Its been a while since I evaluated and evolved my approach to BDD. The way I’ve been doing BDD up until now is described in <a href="http://elegantcode.com/2008/10/25/refining-contextspecification-bdd-using-rhino-mocks-35/">this blog post</a> which goes way back to 2008. Everyone has kind of their own style nowadays. Below you can find the code of two context/specifications for a method named <em>MakePreferred</em> on a <em>Customer </em>class. This simple example clarifies the style that I’ve been following up until now.</p> <style type="text/css">


.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style><style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>  <pre class="csharpcode">[TestFixture]
<span class="kwrd">public</span> <span class="kwrd">class</span> When_making_a_regular_customer_preferred
    : ContextSpecification&lt;Customer&gt;
{
    <span class="kwrd">protected</span> <span class="kwrd">override</span> Customer Create_subject_under_test()
    {
        <span class="kwrd">return</span> <span class="kwrd">new</span> Customer(<span class="kwrd">new</span>[] { _order });
    }

    <span class="kwrd">protected</span> <span class="kwrd">override</span> <span class="kwrd">void</span> Establish_context()
    {
        _order = <span class="kwrd">new</span> Order(<span class="kwrd">new</span>[] { <span class="kwrd">new</span> OrderItem(12), 
                                   <span class="kwrd">new</span> OrderItem(16) });
                                   
        _totalAmountWithoutDiscount = _order.TotalAmount;
    }

    <span class="kwrd">protected</span> <span class="kwrd">override</span> <span class="kwrd">void</span> Because()
    {
        SUT.MakePreferred();
    }

    [Test]
    <span class="kwrd">public</span> <span class="kwrd">void</span> Then_the_customer_should_be_marked_as_preferred()
    {
        SUT.IsPreferred.ShouldBeTrue();
    }

    [Test]
    <span class="kwrd">public</span> <span class="kwrd">void</span> Then_a_ten_percent_discount_should_be_applied_to_all_outstanding_orders()
    {
        _order.TotalAmount.ShouldBeEqualTo(
            _totalAmountWithoutDiscount * 0.9);
    }

    <span class="kwrd">private</span> Order _order;
    <span class="kwrd">private</span> Double _totalAmountWithoutDiscount;
}

[TestFixture]
<span class="kwrd">public</span> <span class="kwrd">class</span> When_making_a_preferred_customer_preferred
    : ContextSpecification&lt;Customer&gt;
{
    <span class="kwrd">protected</span> <span class="kwrd">override</span> Customer Create_subject_under_test()
    {
        var customer = <span class="kwrd">new</span> Customer(<span class="kwrd">new</span>[] { _order });
        customer.MakePreferred();
        <span class="kwrd">return</span> customer;
    }

    <span class="kwrd">protected</span> <span class="kwrd">override</span> <span class="kwrd">void</span> Establish_context()
    {
        _order = <span class="kwrd">new</span> Order(<span class="kwrd">new</span>[] { <span class="kwrd">new</span> OrderItem(12), 
                                   <span class="kwrd">new</span> OrderItem(16) });
        _totalAmountWithoutDiscount = _order.TotalAmount;
    }

    <span class="kwrd">protected</span> <span class="kwrd">override</span> <span class="kwrd">void</span> Because()
    {
        SUT.MakePreferred();
    }

    [Test]
    <span class="kwrd">public</span> <span class="kwrd">void</span> Then_no_additional_discount_should_be_applied_to_the_outstanding_orders()
    {
        _order.TotalAmount.ShouldNotBeEqualTo(
            _totalAmountWithoutDiscount * 0.81);
    }

    <span class="kwrd">private</span> Order _order;
    <span class="kwrd">private</span> Double _totalAmountWithoutDiscount;
}

<span class="rem">//</span>
<span class="rem">// Subject under test</span>
<span class="rem">//</span>
<span class="kwrd">public</span> <span class="kwrd">class</span> Customer
{
    <span class="kwrd">private</span> <span class="kwrd">readonly</span> List&lt;Order&gt; _orders;
    <span class="kwrd">public</span> Boolean IsPreferred { get; <span class="kwrd">private</span> set; }

    <span class="kwrd">public</span> Customer(IEnumerable&lt;Order&gt; orders)
    {
        _orders = <span class="kwrd">new</span> List&lt;Order&gt;(orders);
    }

    <span class="kwrd">public</span> <span class="kwrd">void</span> MakePreferred()
    {
        <span class="kwrd">if</span>(IsPreferred)    
            <span class="kwrd">return</span>;
    
        IsPreferred = <span class="kwrd">true</span>;
        _orders.ForEach(order =&gt; order.ApplyDiscount(10));
    }
}</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>The bottom line of this example is that preferred customers get a 10 percent discount. Customers that are already preferred do not get an additional discount or otherwise we’re out of business ;-). </p>

<p>I’ve been pretty happy with this approach so far, although sometimes there were some quirks associated with this. So it was time for me to look beyond the horizon again, trying to look for ways to improve. </p>

<p><a href="http://github.com/machine/machine.specifications">Machine.Specifications</a> or MSpec for short is something that has been on my ‘cool-things-to-learn-list’ for quite some time now. As you will see later in this post, the syntax is a bit different as one would come to expect from a context/specification framework that targets the C# programming language. Its seems to be heavily inspired by Scott Bellware’s <a href="http://code.google.com/p/specunit-net/">SpecUnit framework</a> and <a href="http://rspec.info/">RSpec</a>.</p>

<p>Lets see how to set things up first. </p>

<p>The most obvious starting point is downloading the bits and bytes. You can grab the <a href="http://github.com/machine/machine.specifications">source code</a> from GitHub and build it or you can wuss out like I did and get the latest build from the <a href="http://teamcity.codebetter.com/login.html">TeamCity.CodeBetter.com</a> builder server (you can log on as a guest and search the artifacts for a latest build).&#160; </p>

<p>When you’re heavily addicted to <a href="http://www.testdriven.net/">TestDriven.NET</a> like I am, then its possible to keep using this wonderful Visual Studio add-in for running MSpec context/specifications. Just create a directory named <em>Machine.Specifications</em> in {$Program_Files}\TestDriven.NET 2.0 and copy the following files:</p>

<ul>
  <li>Machine.Specifications.dll</li>

  <li>Machine.Specifications.TDNetRunner.dll</li>

  <li>InstallTDNetRunner.bat</li>
</ul>

<ul>Run the InstallTDNetRunner.bat file and you’re able to run all MSpec context/specifications using TestDriven.NET.</ul>

<p>I also strongly encourage you to install the plugin for the Resharper test runner (if only to prevent some Resharper warnings later on). First step is to add a directory named <em>Plugins</em> to the <em>Bin</em> directory of Resharper ({$Program_Files}\JetBrains\ReSharper\v4.5\Bin\). Then create a directory named <em>Machine.Specifications</em> in the <em>Plugins</em> directory you just created and copy the following files:</p>

<ul>
  <li>Machine.Specifications.dll</li>

  <li>Machine.Specifications.ReSharperRunner.4.5.dll</li>

  <li>InstallResharperRunner.4.5.bat</li>
</ul>

<p>Run the InstallResharperRunner.4.5.bat file and you’re also able to run MSpec context/specifications using the Resharper test runner.</p>

<p>I’m not going to put this off any longer. Lets look at the code of the context/specifications shown earlier but completely revamped using the MSpec syntax:</p>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<pre class="csharpcode">[Subject(<span class="str">&quot;Making a customer preferred&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_a_regular_customer_is_made_preferred 
{
    Establish context = () =&gt;
    {
        _order = <span class="kwrd">new</span> Order(<span class="kwrd">new</span>[] { <span class="kwrd">new</span> OrderItem(12), 
                                   <span class="kwrd">new</span> OrderItem(16) });
        _totalAmountWithoutDiscount = _order.TotalAmount;

        SUT = <span class="kwrd">new</span> Customer(<span class="kwrd">new</span>[] { _order });
    };

    Because of = () =&gt; 
        SUT.MakePreferred();

    It should_mark_the_customer_as_preferred = () =&gt;
        SUT.IsPreferred.ShouldBeTrue();
        
    It should_apply_a_ten_percent_discount_to_all_outstanding_orders = () =&gt;
        _order.TotalAmount.ShouldEqual(_totalAmountWithoutDiscount * 0.9);      

    <span class="kwrd">private</span> <span class="kwrd">static</span> Customer SUT;
    
    <span class="kwrd">private</span> <span class="kwrd">static</span> Order _order;
    <span class="kwrd">private</span> <span class="kwrd">static</span> Double _totalAmountWithoutDiscount;
}

[Subject(<span class="str">&quot;Making a customer preferred&quot;</span>)]
<span class="kwrd">public</span> <span class="kwrd">class</span> when_a_preferred_customer_is_made_preferred
{
    Establish context = () =&gt;
    {
        _order = <span class="kwrd">new</span> Order(<span class="kwrd">new</span>[] { <span class="kwrd">new</span> OrderItem(12), 
                                   <span class="kwrd">new</span> OrderItem(16) });
        _totalAmountWithoutDiscount = _order.TotalAmount;

        SUT = <span class="kwrd">new</span> Customer(<span class="kwrd">new</span>[] { _order });
        SUT.MakePreferred();
    };

    Because of = () =&gt;
        SUT.MakePreferred();

    It should_apply_no_additional_discount_to_the_outstanding_orders = () =&gt; 
        _order.TotalAmount.ShouldNotEqual(_totalAmountWithoutDiscount * 0.81);

    <span class="kwrd">private</span> <span class="kwrd">static</span> Customer SUT;

    <span class="kwrd">private</span> <span class="kwrd">static</span> Order _order;
    <span class="kwrd">private</span> <span class="kwrd">static</span> Double _totalAmountWithoutDiscount;
}</pre>
<style type="text/css">
.csharpcode, .csharpcode pre
{
	font-size: small;
	color: black;
	font-family: consolas, "Courier New", courier, monospace;
	background-color: #ffffff;
	/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt 
{
	background-color: #f4f4f4;
	width: 100%;
	margin: 0em;
}
.csharpcode .lnum { color: #606060; }</style>

<p>&#160;</p>

<p>I warned you about the syntax, didn’t I :-). It only took me a couple of seconds to get used to this syntax but now I’m completely hooked. Instead of using methods and attributes, MSpec utilizes delegates and anonymous methods. But there’s more. </p>

<p>When using <a href="http://www.nunit.com/index.php">NUnit</a> for writing context/ specifications, the <em>Establish_context</em> and <em>Because</em> methods of the example shown earlier is executed before every observation (test). With MSpec, the <em>Establish</em> and <em>Because</em> anonymous methods are executed only once for every context no matter how many observations a particular context class contains. Big difference? Well, at first glance not but on second hand it does make <a href="http://elegantcode.com/2008/12/30/dont-sell-out-on-the-context-dude/">selling out on the context</a> a bit more difficult as it will probably blow up in your face sooner than later. You can force MSpec to execute the <em>Establish</em> and <em>Because</em> anonymous methods before every observation by applying the <em>SetupForEachSpecification</em> attribute to the context class, but I strongly encourage you to stay away from that unless absolutely needed.</p>

<p>Also notice that the fields in the contexts are now all static. This is needed so that the anonymous methods can access those.&#160;&#160;&#160;&#160;&#160; </p>

<p>Running these context/specifications using TestDriven.NET yields the following output in the output window of Visual Studio:</p>

<blockquote>
  <p><font face="Arial">Making a customer preferred, when a regular customer is made preferred
      <br />» should mark the customer as preferred

      <br />» should apply a ten percent discount to all outstanding orders</font></p>

  <p><font face="Arial">Making a customer preferred, when a preferred customer is made preferred
      <br />» should apply no additional discount to the outstanding orders</font></p>
</blockquote>

<p>What’s not to like? Well, the only downside so far is that Resharper was giving me some warnings about classes and fields not being used etc. … . Many of those warnings disappeared by registering the MSpec plugin for the Resharper test runner as I explained earlier.</p>

<p>So far, so good. I’ve got two more posts coming up on MSpec, so stay tuned.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/02/19/getting-started-with-machine-specifications-mspec/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Unity/Moq &#8211; AutoMocker or AutoMockingContainer</title>
		<link>http://elegantcode.com/2010/01/03/unitymoq-automocker-or-automockingcontainer/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=unitymoq-automocker-or-automockingcontainer</link>
		<comments>http://elegantcode.com/2010/01/03/unitymoq-automocker-or-automockingcontainer/#comments</comments>
		<pubDate>Sun, 03 Jan 2010 16:52:33 +0000</pubDate>
		<dc:creator>Jason Jarrett</dc:creator>
				<category><![CDATA[TDD]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Tools and Utilities]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2010/01/03/unitymoq-automocker-or-automockingcontainer/</guid>
		<description><![CDATA[What is an Auto Mocking Container? This post started to get a little long, so I won’t re-explain the concept. Joshua Flanagan wrote a nice overview at his Los Techies blog: Auto mocking Explained. My post is mainly here to describe the Unity version of an automocking container I threw together. In Jan 2009 I [...]]]></description>
			<content:encoded><![CDATA[<h4>What is an Auto Mocking Container?</h4>  <p>This post started to get a little long, so I won’t re-explain the concept.</p>  <p><a href="http://www.lostechies.com/blogs/joshuaflanagan/default.aspx">Joshua Flanagan</a> wrote a nice overview at his <a href="http://www.lostechies.com/">Los Techies</a> blog: <a href="http://www.lostechies.com/blogs/joshuaflanagan/archive/2009/02/03/auto-mocking-explained.aspx"><strong>Auto mocking Explained</strong></a>.</p>  <p>My post is mainly here to describe the Unity version of an automocking container I threw together.</p>  <h4>In Jan 2009 I blogged about my initial version of the Unity AutoMocker - Why am I blogging about it again?</h4>  <p>I originally wrote the AutoMocker for the Unity container a year ago (Jan 2009, in Silverlight), and finally got around to placing the code up in the <a href="http://code.google.com/p/moq-contrib/">moq-contrib</a> project in June of 2009.</p>  <p>I’m writing another post today in hopes to:</p>  <ol>   <li>Get some feedback on how this little snippet of code should continue. </li>    <li>Give a little more how-to/example code </li>    <li>Describe some updates I made since I originally created it.&#160; </li> </ol>  <h4>Where can I get it?</h4>  <p><strong>This is one part where I’d appreciate some feedback.</strong></p>  <p>I have two slightly different versions out there (currently).</p>  <p>I have one version at the <a href="http://code.google.com/p/elegantcode/source/browse/#svn/trunk/Coders/JasonJarrett/UnityAutoMocker">ElegantCode</a> repository where I was working on it, and the other I threw up at <a href="http://code.google.com/p/moq-contrib/">moq-contrib</a>.</p>  <p>The core of the UnityAutoMockContainer is the same in both places, it’s how the tests are separated out that differ.</p>  <p>In the <a href="http://code.google.com/p/elegantcode/source/browse/#svn/trunk/Coders/JasonJarrett/UnityAutoMocker">ElegantCode repository</a> it’s an all in one self contained single file (that you can copy into your own test project(s)). You can then setup a single test in your own testing framework that runs all internal automocker tests (in case you need to modify it yourself, and don’t want to break any existing functionality). EX: test</p>  <pre class="brush: csharp;">[Test]
public void Should_run_all_UnityAutoMockContainer_internal_tests()
{
    Moq.AutoMocking.SelfTesting.UnityAutoMockContainerFixture
        .RunAllTests(Console.WriteLine);
}</pre>

<p>I kind of like this format as it makes it easy to port between test libraries. Can’t say I like having the tests in the same file as the core, but it certainly is not a large chunk of code (so far) so it’s relatively small to maintain and definitely easier to manage as a single .cs file than another assembly (which would have to be version dependent on both Unity and Moq).</p>

<p>The <a href="http://code.google.com/p/moq-contrib/">moq-contrib</a> is definitely where I think this helper should end up (and it is there). I just happened to break the tests out into the Silverlight test project and the core is alone in a file. </p>

<p>It’s current state isn’t as easy to copy to a test library (Silverlight/Desktop/Unity 1.2/Unity 2.0) as the one at <a href="http://elegantcode.com/">ElegantCode</a>. <strong>What does anyone think?</strong> Should I put them all together in one file?</p>

<p>However it ends up (1. all in one file or two (1 test) (1 core)) it will continue to be maintained on the <a href="http://code.google.com/p/moq-contrib/">moq-contrib</a> project.</p>

<h4>What is the high level API of the container?</h4>

<p>It’s pretty simple, (currently) there are four methods on the container.</p>

<p><strong>Two for registering items with the container</strong>. Say you want to register an already created instance, or say you want to map an interface to a concrete class and _not_ have the container generate mocks automatically for special cases. </p>

<p>And <strong>two for pulling items out of the container</strong>. Whether you want a instance of T or a Mock&lt;T&gt;, it gives you ways to retrieve both.</p>

<blockquote>
  <p><a href="http://elegantcode.com/wp-content/uploads/2010/01/image.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://elegantcode.com/wp-content/uploads/2010/01/image_thumb.png" width="396" height="106" /></a> </p>
</blockquote>

<h4>How can I setup my own registrations with the container? </h4>

<p>Say I don’t want to have the container generate mocks for specific items and I want to supply specific configuration to the UnityContainer.</p>

<blockquote>
  <p>public UnityAutoMockContainer RegisterInstance&lt;TService&gt;(TService instance)</p>

  <p>public UnityAutoMockContainer Register&lt;TService, TImplementation&gt;() 
    <br />&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; where TImplementation : TService</p>
</blockquote>

<p><strong>Note</strong>: both of these registration methods return the container itself so you can fluently stack registration. <strong>EX:</strong></p>

<pre class="brush: csharp;">AutoMockContainer
    .Register&lt;IServiceA, ServiceA&gt;()
    .Register&lt;IServiceB, ServiceB&gt;();</pre>

<p><strong>Let me know</strong>: I haven’t tested or played around with how this automocking container deals with any container specific xml configuration… So although I don’t think you should probably have that in a test assembly (stuff happens). Let me know if there are any issues.</p>

<h4>How do I get items out of the container?</h4>

<p>First is the Resolve&lt;T&gt;(). It will pull an item T out of the container. (Creating it if not already existing)</p>

<blockquote>
  <p>public T Resolve&lt;T&gt;()</p>
</blockquote>

<p>When T is an interface Resolve&lt;T&gt; (unless you setup registration specifically with the container) should return basically “(new Mock&lt;T&gt;()).Object”</p>

<p>When T is a concrete Class, the container should return an instance of T and any of it’s dependencies will be satisfied by mocks. (Note that T will not be any sort of mocked instance of T, unless you used the GetMock&lt;T&gt; as described below first)</p>

<blockquote>
  <p>public Mock&lt;T&gt; GetMock&lt;T&gt;() where T : class</p>
</blockquote>

<p>When T is an interface GetMock&lt;T&gt; should return basically “(new Mock&lt;T&gt;())” </p>

<p>When T is a concrete Class, the container should return a new Mock&lt;T&gt;() and any of it’s dependencies will be satisfied by mocks.</p>

<h4>How do I use the UnityAutoMockContainer?</h4>

<p>It’s pretty basic, you first create an instance of the UnityAutoMockContainer, and from there you can ask it for mocks of an (Interface, Class, or Abstract Class).</p>

<p>If you request an instance of a concrete class, or abstract class, the UnityAutoMockContainer will stuff mocks in for any constructor dependencies of your concrete class (if it can). You can then request from the container those same dependencies one at a time and either apply mocking setups or verifications.</p>

<blockquote>
  <p><strong>NOTE:</strong> Anything the container creates will live as a singleton instance in the container. So any other requests from the container will always return the originally created instance. Therefore, each distinct scenario in a test suite should have their own instances of the container.</p>
</blockquote>

<p>Below his an example of how you can leverage the container in some tests. Given this base fixture class…</p>

<pre class="brush: csharp;">public class FixtureBase
{
    private readonly UnityAutoMockContainer _autoMockContainer = new UnityAutoMockContainer();

    protected UnityAutoMockContainer AutoMockContainer
    {
        get { return _autoMockContainer; }
    }

    [TestFixtureSetUp]
    public void SetupContext_ALL()
    {
        Before_all_tests();
        Because();
    }

    [TestFixtureTearDown]
    public void TearDownContext_ALL()
    {
        After_all_tests();
    }

    protected virtual void Before_all_tests()
    {
    }

    protected virtual void Because()
    {
    }

    protected virtual void After_all_tests()
    {
    }
}</pre>

<p>If I were given the following system to test.</p>

<pre class="brush: csharp;">public interface IServiceA { void RunA(); }
public interface IServiceB { void RunB(); }

public class TestComponent
{
    public TestComponent(IServiceA serviceA, IServiceB serviceB)
    {
        ServiceA = serviceA;
        ServiceB = serviceB;
    }

    public IServiceA ServiceA { get; private set; }
    public IServiceB ServiceB { get; private set; }

    public void RunAll()
    {
        if (!HowDidItGo())
            return;
        ServiceA.RunA();
        ServiceB.RunB();
    }

    public virtual bool HowDidItGo()
    {
        // some really nasty untestable code
        return true;
    }
}</pre>

<p>The below example demonstrates simply verifying some behavior on the mocked dependencies of the system under test.</p>

<pre class="brush: csharp;">[TestFixture]
public class Example__how_to_pull_items_from_the_UnityAutoMockContainer_when_verifying_behavior_after_an_action_was_taken 
    : FixtureBase
{
    private TestComponent _testComponent;

    protected override void Before_all_tests()
    {
        base.Before_all_tests();
        _testComponent = AutoMockContainer.Resolve&lt;TestComponent&gt;();
    }

    protected override void Because()
    {
        _testComponent.RunAll();
    }

    [Test]
    public void Should_run_ServiceA_RunA()
    {
        AutoMockContainer
            .GetMock&lt;IServiceA&gt;()
            .Verify(v =&gt; v.RunA(), Times.Once());
    }

    [Test]
    public void Should_run_ServiceB_RunB()
    {
        AutoMockContainer
            .GetMock&lt;IServiceB&gt;()
            .Verify(v =&gt; v.RunB(), Times.Once());
    }
}</pre>

<p>Next, you may have noticed that the system under test had a complicated internal method (that may not necessarily be testable). You can use the AutoMocker to create the system under test as a Mock itself, so we can override some of the behavior. Here’s how you could quickly do that. </p>

<blockquote>
  <p><strong>Aside</strong>: I’m not saying this is a good practice or aids in good component design, just saying it’s possible</p>
</blockquote>

<pre class="brush: csharp;">[TestFixture]
public class Example__how_to_use_the_UnityAutoMockContainer_to_override_a_method_on_the_SystemUnderTest_to_test_a_certain_behavior
    : FixtureBase
{

    private TestComponent _testComponent;

    protected override void Before_all_tests()
    {
        base.Before_all_tests();
        var mockTestComponent = AutoMockContainer.GetMock&lt;TestComponent&gt;();

        mockTestComponent
            .Setup(s =&gt; s.HowDidItGo())
            .Returns(false);

        _testComponent = mockTestComponent.Object;
    }

    protected override void Because()
    {
        _testComponent.RunAll();
    }

    [Test]
    public void Should_run_ServiceA_RunA()
    {
        AutoMockContainer
            .GetMock&lt;IServiceA&gt;()
            .Verify(v =&gt; v.RunA(), Times.Never());
    }

    [Test]
    public void Should_run_ServiceB_RunB()
    {
        AutoMockContainer
            .GetMock&lt;IServiceB&gt;()
            .Verify(v =&gt; v.RunB(), Times.Never());
    }
}</pre>

<p>&#160;</p>

<p>It’s amazing how much redundant test setup code this little helper has saved me in my tests. I hope others can find some use with this as well.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2010/01/03/unitymoq-automocker-or-automockingcontainer/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>StatLight &#8211; Goes Open Source</title>
		<link>http://elegantcode.com/2009/12/10/statlight-goes-open-source/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=statlight-goes-open-source</link>
		<comments>http://elegantcode.com/2009/12/10/statlight-goes-open-source/#comments</comments>
		<pubDate>Fri, 11 Dec 2009 03:26:55 +0000</pubDate>
		<dc:creator>Jason Jarrett</dc:creator>
				<category><![CDATA[Esoterica]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[TDD]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Tools and Utilities]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/12/10/statlight-goes-open-source/</guid>
		<description><![CDATA[Although I made a very minor attempt at making StatLight a “for-sale” product, I knew when I started that open-source was most likely going to be my long term path for StatLight. What is it? (Silverlight Testing Automation Tool) StatLight is a tool developed for automating the setup, running, and gathering results of Silverlight unit [...]]]></description>
			<content:encoded><![CDATA[Although I made a very minor attempt at making <a href="http://statlight.net" target="_blank">StatLight</a> a “for-sale” product, I knew when I started that open-source was most likely going to be my long term path for <a href="http://statlight.net" target="_blank">StatLight</a>.
<h5>What is it? (Silverlight Testing Automation Tool)</h5>
StatLight is a tool developed for automating the setup, running, and gathering results of Silverlight unit tests. StatLight helps to speed up the feedback cycles while practicing<a href="http://en.wikipedia.org/wiki/Test-driven_development"> TDD</a>/<a href="http://en.wikipedia.org/wiki/Behavior_Driven_Development">BDD</a>/(insert your test style here) during Silverlight development.
<h5>Where can I get StatLight?</h5>
<a href="http://StatLight.CodePlex.com">http://StatLight.CodePlex.com</a>
<h4>Happy Coding !!!</h4>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/12/10/statlight-goes-open-source/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Wrapping up the StructureMap Automocking Container</title>
		<link>http://elegantcode.com/2009/11/30/wrapping-up-the-structuremap-automocking-container/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=wrapping-up-the-structuremap-automocking-container</link>
		<comments>http://elegantcode.com/2009/11/30/wrapping-up-the-structuremap-automocking-container/#comments</comments>
		<pubDate>Mon, 30 Nov 2009 07:21:43 +0000</pubDate>
		<dc:creator>Richard Cirerol</dc:creator>
				<category><![CDATA[TDD]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Unit Testing]]></category>
		<category><![CDATA[StructureMap; Automocking; MSpec;]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/11/30/wrapping-up-the-structuremap-automocking-container/</guid>
		<description><![CDATA[<p><font color="#804040"><strong>UPDATE</strong>: I apologize…the original wrapper did not allow injected dependencies.&#160; I have fixed this bug and updated the sample.</font></p> I have been using StructureMap.AutoMocking with MSpec (Machine.Specifications) and Rhino.Mocks for a few months now.  Although I am very comfortable with the patterns that emerge from using the frameworks together, introducing StructureMap.Automocking to other developers is sometimes challenging. I decided to wrap the details of the container to make the intention clearer and explanation easier.  I have started using this wrapper in my projects, and have found it makes building up specifications more efficient in my daily coding.]]></description>
			<content:encoded><![CDATA[<span style="color: #804040;"><strong>UPDATE</strong>: I apologize…the original wrapper did not allow injected dependencies.  I have fixed this bug and updated the sample.</span>

I have been using StructureMap.AutoMocking with MSpec (Machine.Specifications) and Rhino.Mocks for a few months now.  Although I am very comfortable with the patterns that emerge from using the frameworks together, introducing StructureMap.Automocking to other developers is sometimes challenging.

When viewing a specification or test set up with the Rhino.Mocks or Moq automocking container, what is being tested is not readily apparent.  Once the concept is explained and demonstrated, these same developers seem to have no issue with maintaining the specifications/tests.

I decided to wrap the details of the container to make the intention clearer and explanation easier.  I have started using this wrapper in my projects, and have found it makes building up specifications more efficient in my daily coding.

Let me know whether this is useful to you, or how it could be made more useful.
<h4>The Examples</h4>
Let’s contrive an example.  We’ll say we have a coffee machine that grinds its own beans before brewing. However, the hopper has to have beans before starting the grind.  Here is the basic specification:
<table border="1" cellspacing="0" cellpadding="2" width="533">
<tbody>
<tr>
<td width="117" valign="top">Action/Behavior</td>
<td width="414" valign="top">Prepare coffee grounds for 12 cups of coffee</td>
</tr>
<tr>
<td rowspan="2" width="117" valign="top">Expectations</td>
<td width="414" valign="top">Should check that hopper has beans (mock returns true)</td>
</tr>
<tr>
<td width="414" valign="top">Because hopper has beans, should ask grinder to grind enough beans for 12 cups of coffee</td>
</tr>
</tbody></table>
We could start without a container, using Rhino.Mocks to build up the CoffeeMachine dependencies manually:
<pre class="brush: csharp;">[Subject(typeof(CoffeeMachine),"using vanilla Rhino.Mocks")]
public class Example01_when_preparing_coffee_grounds
{
    Establish context = () =&gt;
        {
            Grinder = MockRepository.GenerateMock&lt;IGrinder&gt;();
            Hopper = MockRepository.GenerateMock&lt;IHopper&gt;();
            Hopper.Expect(x =&gt; x.HasBeans()).Return(true);
            CoffeeMachine = new CoffeeMachine(Grinder, Hopper);
        };

    Because of = () =&gt; _coffeeMachine.PrepareCoffeeGrounds(12);

    It should_check_if_hopper_has_beans = () =&gt; Hopper.VerifyAllExpectations();
    It should_grind_coffee = () =&gt; Grinder.AssertWasCalled(x =&gt; x.Grind(12));

    static IGrinder Grinder;
    static IHopper Hopper;
    static CoffeeMachine CoffeeMachine;
}</pre>
For those of you not familiar with the MSpec style, please refer to the following posts:
<ul>
	<li><a href="http://blog.wekeroad.com/blog/make-bdd-your-bff-2/" target="_blank">Make BDD Your BFF</a></li>
	<li><a href="http://www.lostechies.com/blogs/seanbiefeld/archive/2009/08/25/step-by-step-to-using-machine-specifications-with-resharper.aspx" target="_blank">Step by Step to Using MSpec (Machine.Specifications) with ReSharper</a></li>
	<li><a href="http://elegantcode.com/2009/07/05/mspec-take-2/" target="_blank">MSpec - Take 2</a></li>
	<li><a href="http://marcinobel.com/index.php/mspec-bdd-installer/" target="_blank">MSpec BDD framework installer</a></li>
	<li><strong>Updated! </strong>From the <a href="http://blog.cwa.me.uk/2009/11/30/the-morning-brew-487/" target="_blank">Morning Brew #487</a>: BDD with MSpec and Rhino Auto Mocks, parts  <a href="http://telldontask.wordpress.com/2009/11/10/bdd-with-mspec-and-rhino-auto-mocks/" target="_blank">1</a>, <a href="http://telldontask.wordpress.com/2009/11/19/bdd-with-mspec-and-rhino-auto-mocks-part-2/" target="_blank">2</a>, and <a href="http://telldontask.wordpress.com/2009/11/29/bdd-with-mspec-and-rhino-auto-mocks-part-3/" target="_blank">3</a>
Here is the same specification using the RhinoAutoMocker&lt;T&gt; class provided by StructureMap.AutoMocking:</li>
</ul>
<pre class="brush: csharp;">[Subject(typeof(CoffeeMachine),"using RhinoAutoMocker&lt;CoffeeMachine&gt;")]
public class Example02_when_preparing_coffee_grounds
{
    Establish context = () =&gt;
        {
            CoffeeMachine = new RhinoAutoMocker&lt;CoffeeMachine&gt;();
            Grinder = CoffeeMachine.Get&lt;IGrinder&gt;();
            Hopper = CoffeeMachine.Get&lt;IHopper&gt;();
            Hopper.Expect(x =&gt; x.HasBeans()).Return(true);
        };

    Because of = () =&gt; v.ClassUnderTest.PrepareCoffeeGrounds(12);

    It should_check_if_hopper_has_beans = () =&gt; Hopper.VerifyAllExpectations();
    It should_grind_coffee = () =&gt; Grinder.AssertWasCalled(x =&gt; x.Grind(12));

    static IGrinder Grinder;
    static IHopper Hopper;
    static RhinoAutoMocker&lt;CoffeeMachine&gt; CoffeeMachine;
}</pre>
Although I think this looks cleaner, the initialization of CoffeeMachine causes some confusion. Unfortunately, a common question would be, “Is RhinoAutoMocker&lt;CoffeeMachine&gt; creating a mocked version of CoffeeMachine?” Well, not exactly.

RhinoAutoMocker is an implementation of the AutoMocker base class which uses StructureMap to fill dependencies.  The RhinoAutoMocker implementation of the container uses Rhino.Mocks to generate all of dependencies of the target class, whereas the MoqAutoMocker implementation uses Moq.  (Optionally, the target class can be partially mocked in order to further isolate behavior.)  We then retrieve the class under test (in this case, CoffeeMachine) and its dependencies (IGrinder and IHopper) from the container for use.

If you do not need to setup any expectations in the specification, there is no need to retrieve the dependency from the container.  However, in this specification, we need both dependencies.

<em>(Incidentally, I do not like the ClassUnderTest name.  I may end up changing this to Instance, ClassInstance, TargetClass, or something similar.  Suggestions?)</em>

By moving the initialization of the RhinoAutoMocker to a base class, some of the chattiness of the context can be hidden.
<ul>
<pre class="brush: csharp;">[Subject(typeof(CoffeeMachine),"using RhinoAutoMocker base")]
public class Example03_when_preparing_coffee_grounds : with_rhinoautomocker
{
    Establish context = () =&gt; Hopper.Expect(x =&gt; x.HasBeans()).Return(true);

    Because of = () =&gt; CoffeeMachine.ClassUnderTest.PrepareCoffeeGrounds(12);

    It should_check_if_hopper_has_beans = () =&gt; Hopper.VerifyAllExpectations();
    It should_grind_coffee = () =&gt; Grinder.AssertWasCalled(x =&gt; x.Grind(12));

}

[Subject("using RhinoAutoMocker&lt;T&gt;")]
public class with_rhinoautomocker
{
    protected static IGrinder Grinder;
    protected static IHopper Hopper;
    protected static RhinoAutoMocker&lt;CoffeeMachine&gt; CoffeeMachine;

    Establish context = () =&gt;
    {
        CoffeeMachine = new RhinoAutoMocker&lt;CoffeeMachine&gt;();
        Grinder = CoffeeMachine.Get&lt;IGrinder&gt;();
        Hopper = CoffeeMachine.Get&lt;IHopper&gt;();
    };
}</pre>
However, we are still initializing and accessing the class in a less than optimal manner.To make the usage of the container a little more seamless, I decided to create a wrapper and factory for the AutoMocker.  Setup of the dependencies and expectations are done through an AutoMocker wrapper object.  The instance of the class under test is accessed through a ClassUnderTest object.
<h4>The Result</h4>
The specification (and base class) now look like this:
<pre class="brush: csharp;">[Subject(typeof(CoffeeMachine),"using coffee machine base")]
public class Example05_when_preparing_coffee_grounds : with_coffee_machine
{
    Establish context = () =&gt; Hopper.Expect(x =&gt; x.HasBeans()).Return(true);

    Because of = () =&gt; ClassUnderTest.PrepareCoffeeGrounds(12);

    It should_check_if_hopper_has_beans = () =&gt; Hopper.VerifyAllExpectations();
    It should_grind_coffee = () =&gt; Grinder.AssertWasCalled(x =&gt; x.Grind(12));
}

[Subject("using SpecificationFor&lt;CoffeeMachine&gt;")]
public class with_coffee_machine : SpecificationFor&lt;CoffeeMachine&gt;
{
    protected static IGrinder Grinder;
    protected static IHopper Hopper;

    public with_coffee_machine
    {
        Grinder = AutoMocker.Get&lt;IGrinder&gt;();
        Hopper = AutoMocker.Get&lt;IHopper&gt;();
    }
}</pre>
As you can see, the base class inherits from SpecificationFor&lt;T&gt;.  The default constructor uses Rhino.Mocks(MockMode.AAA) to generate the dependencies.  It then exposes a AutoMocker object, which is just the wrapper around the AutoMocker base class.  It also exposes a ClassUnderTest object.  If I didn’t need to use the dependencies, I could make the <em>Example05_when_preparing_coffee_grounds</em> class inherit from <em>SpecificationFor&lt;CoffeeMachine&gt; </em>instead of inheriting from the base class<em>.</em>
<h4>The Code</h4>
I have included the code for the wrapper below for your review.  The code and six examples are available on my <a href="http://codeprogression.googlecode.com/svn/trunk/CodeProgression.Framework.Testing" target="_blank">Google code repository</a>. The repository also includes an example using the MoqAutoMocker.  All the examples have the same assertions, but are built up using the different techniques.
<pre class="brush: csharp;">namespace CodeProgression.Framework.Testing
{
    public abstract class SpecificationFor&lt;T&gt; where T: class
    {
        protected static ClassUnderTest&lt;T&gt; Factory;

        // UPDATE 2009-12-21:
        //   Moved initialization here
        protected static T ClassUnderTest {get {return AutoMocker.Instance;} }

        protected SpecificationFor()
        {
            AutoMocker = AutoMockFactory.CreateTarget&lt;T&gt;();

            // UPDATE 2009-12-21:
            //    Initializing here prevented injected dependencies!
            // AutoMocker.PartialMockTheClassUnderTest();
            // ClassUnderTest = AutoMocker.Instance;
        }

        protected SpecificationFor(AutoMockType type)
        {
            AutoMocker = AutoMockFactory.CreateTarget&lt;T&gt;(type);

            // UPDATE 2009-12-21:
            // Initializing here prevented injected dependencies!
            // AutoMocker.PartialMockTheClassUnderTest();
            // ClassUnderTest = AutoMocker.Instance;
        }
    }

    public static class AutoMockFactory
    {
        public static ClassUnderTest&lt;TARGETCLASS&gt; CreateTarget&lt;TARGETCLASS&gt;() where TARGETCLASS : class
        {
            return CreateTarget&lt;TARGETCLASS&gt;(AutoMockType.RhinoMocksAAA);
        }

        public static ClassUnderTest&lt;TARGETCLASS&gt; CreateTarget&lt;TARGETCLASS&gt;(AutoMockType framework) where TARGETCLASS : class
        {
            AutoMocker&lt;TARGETCLASS&gt; mocker;
            ServiceLocator serviceLocator;
            switch (framework)
            {
                case AutoMockType.RhinoMocksAAA:
                    mocker = new RhinoAutoMocker&lt;TARGETCLASS&gt;(MockMode.AAA);
                    serviceLocator = new RhinoMocksAAAServiceLocator();
                    break;
                case AutoMockType.RhinoMocksClassic:
                    mocker = new RhinoAutoMocker&lt;TARGETCLASS&gt;(MockMode.RecordAndReplay);
                    serviceLocator = new RhinoMocksClassicServiceLocator();
                    break;
                case AutoMockType.Moq:
                    mocker = new MoqAutoMocker&lt;TARGETCLASS&gt;();
                    serviceLocator = new MoqServiceLocator();
                    break;
                default:
                    throw new ArgumentOutOfRangeException("framework");
            }
            return new ClassUnderTest&lt;TARGETCLASS&gt;(mocker, serviceLocator);
        }
    }

    public enum AutoMockType
    {
        Moq,
        RhinoMocksAAA,
        RhinoMocksClassic
    }

    public class ClassUnderTest&lt;TARGETCLASS&gt; where TARGETCLASS : class
    {
        readonly IAutoMocker&lt;TARGETCLASS&gt; _mocker;
        readonly ServiceLocator _serviceLocator;

        public ClassUnderTest(IAutoMocker&lt;TARGETCLASS&gt; mocker, ServiceLocator serviceLocator)
        {
            _mocker = mocker;
            _serviceLocator = serviceLocator;
        }

        public AutoMockedContainer Container
        {
            get { return _mocker.Container; }
        }

        public TARGETCLASS Instance
        {
            get { return _mocker.ClassUnderTest; }
        }

        public void MockObjectFactory()
        {
            _mocker.MockObjectFactory();
        }

        public void PartialMockTheClassUnderTest()
        {
            _mocker.PartialMockTheClassUnderTest();
        }

        public T Get&lt;T&gt;() where T : class
        {
            return _mocker.Get&lt;T&gt;();
        }

        public void Inject(Type pluginType, object stub)
        {
            _mocker.Inject(pluginType, stub);
        }

        public void Inject&lt;T&gt;(T target)
        {
            _mocker.Inject(target);
        }

        public T AddAdditionalMockFor&lt;T&gt;() where T : class
        {
            return _mocker.AddAdditionalMockFor&lt;T&gt;();
        }

        public void UseConcreteClassFor&lt;T&gt;()
        {
            _mocker.UseConcreteClassFor&lt;T&gt;();
        }

        public T[] CreateMockArrayFor&lt;T&gt;(int count) where T : class
        {
            return _mocker.CreateMockArrayFor&lt;T&gt;(count);
        }

        public void InjectArray&lt;T&gt;(T[] stubs)
        {
            _mocker.InjectArray(stubs);
        }

        public T Mock&lt;T&gt;() where T : class
        {
            return _serviceLocator.Service&lt;T&gt;();
        }
        public object Mock(Type serviceType)
        {
            return _serviceLocator.Service(serviceType);
        }
        public T PartialMock&lt;T&gt;() where T : class
        {
            return _serviceLocator.PartialMock&lt;T&gt;();
        }
    }
}</pre>
</ul>
<script type="text/javascript">// <![CDATA[
 var cirerolGaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."); document.write(unescape("%3Cscript src='" + cirerolGaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
// ]]&gt;</script>

<script type="text/javascript">// <![CDATA[
 var cirerolPageTracker = _gat._getTracker('UA-8257866-3'); cirerolPageTracker._initData(); cirerolPageTracker._trackPageview();
// ]]&gt;</script>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/11/30/wrapping-up-the-structuremap-automocking-container/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Integration Test Brought to you by Powershell &amp; NUnit &#8211; with a Little Specification Syntax for Flavoring</title>
		<link>http://elegantcode.com/2009/10/25/integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring</link>
		<comments>http://elegantcode.com/2009/10/25/integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring/#comments</comments>
		<pubDate>Mon, 26 Oct 2009 05:00:40 +0000</pubDate>
		<dc:creator>Jason Jarrett</dc:creator>
				<category><![CDATA[Esoterica]]></category>
		<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/10/25/integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring/</guid>
		<description><![CDATA[One of the tools I’ve used the last half of a year and really enjoyed is the C# specification extension methods when writing unit test assertions. If you’re looking for a little more background on the topic, I wrote about Fluent Specification Extensions in a past blog. Recently I wanted to execute a PowerShell script [...]]]></description>
			<content:encoded><![CDATA[One of the tools I’ve used the last half of a year and really enjoyed is the C# specification extension methods when writing unit test assertions. If you’re looking for a little more background on the topic, I wrote about <a href="http://staxmanade.blogspot.com/2009/02/fluent-specification-extensions.html">Fluent Specification Extensions</a> in a past blog.

Recently I wanted to execute a PowerShell script to do some automated <a href="http://en.wikipedia.org/wiki/Functional_testing">functional testing</a>. I wanted to execute an application and apply some assertions on the output of the software(basically running a console app, parse the xml output and assert on values in the output).
<blockquote>FYI: I’m very new to PowerShell, so any suggestions on how I implemented the below are welcome…</blockquote>
I’ve seen a couple examples of writing test assertions in PowerShell out there. One example is <a href="http://www.psunit.org/">PSUnit</a>; however, this seemed a little heavy for my needs and not quite the syntactic sugar I was looking for.

Besides the syntax flavor I was desiring, another thing I wanted to do was leverage the power of NUnit.Framework’s assertion capabilities. I like the error messages generated when strings and other objects fail the assertion.
<h5>Examples of end result ShouldLookLike()…</h5>
$true.ShouldBeTrue()
$false.ShouldBeFalse()
"a".ShouldEqual("a")
"a".ShouldNotEqual("b")
<h5><strong>Step 1</strong>: Figure out how to write a C# style <a href="http://msdn.microsoft.com/en-us/library/bb383977.aspx">extension method</a> in PowerShell.</h5>
<blockquote>I found a great blog post describing how to extend any PowerShell object to add extension methods.

<a href="http://bartdesmet.net/blogs/bart/archive/2007/09/06/extension-methods-in-windows-powershell.aspx">Extension Methods in Windows PowerShell</a></blockquote>
In short, to extend types in PowerShell leveraging the <a href="http://msdn.microsoft.com/en-us/library/ms714419(VS.85).aspx">Extended Type System</a>, you need to define them in an xml file and import the method definitions into the PowerShell runtime instance.

Below is PowerShell XML definition for my NUnit Specification Extensions.
<pre class="brush: xml;">&lt;?xml version="1.0" encoding="utf-16"?&gt;
&lt;Types&gt;
    &lt;Type&gt;
        &lt;Name&gt;System.Object&lt;/Name&gt;
        &lt;Members&gt;
            &lt;ScriptMethod&gt;
                &lt;Name&gt;ShouldBeFalse&lt;/Name&gt;
                &lt;Script&gt;
                    [NUnit.Framework.Assert]::IsFalse($this)
                &lt;/Script&gt;
            &lt;/ScriptMethod&gt;
            &lt;ScriptMethod&gt;
                &lt;Name&gt;ShouldBeTrue&lt;/Name&gt;
                &lt;Script&gt;
                    [NUnit.Framework.Assert]::IsTrue($this)
                &lt;/Script&gt;
            &lt;/ScriptMethod&gt;
            &lt;ScriptMethod&gt;
                &lt;Name&gt;ShouldEqual&lt;/Name&gt;
                &lt;Script&gt;
                    [NUnit.Framework.Assert]::AreEqual($args[0], $this)
                &lt;/Script&gt;
            &lt;/ScriptMethod&gt;
            &lt;ScriptMethod&gt;
                &lt;Name&gt;ShouldNotEqual&lt;/Name&gt;
                &lt;Script&gt;
                    [NUnit.Framework.Assert]::AreNotEqual($args[0], $this)
                &lt;/Script&gt;
            &lt;/ScriptMethod&gt;
        &lt;/Members&gt;
    &lt;/Type&gt;
&lt;/Types&gt;</pre>
<h4></h4>
Take the above XML and save it to a file…
<blockquote>NOTE: the file HAS to be saved with the extension <strong>.ps1xml</strong>

Ex: NunitSpecificationPowerShellExtensions<strong>.ps1xml</strong></blockquote>
<h4></h4>
<h5>Step 2: Load the extended type definition into the PowerShell runtime.</h5>
Once you’ve saved the XML extended types to a file, you need to load it into the PowerShell runtime by executing the command below.
<blockquote>
Update-TypeData -PrependPath NunitSpecificationPowerShellExtensions.ps1xml</blockquote>
Before executing the above statement…Let’s quickly look at a System.String’s members and properties – just to show you what the extension methods look like when applied inside of the runtime.<a href="http://elegantcode.com/wp-content/uploads/2009/10/image3.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" src="http://elegantcode.com/wp-content/uploads/2009/10/image_thumb2.png" border="0" alt="image" width="586" height="479" /></a>

After executing the Update-TypeData command you’ll notice there are a number of “ScriptMethod” MemberTypes added to the object.

<a href="http://elegantcode.com/wp-content/uploads/2009/10/image4.png"><img style="border-bottom: 0px; border-left: 0px; display: inline; border-top: 0px; border-right: 0px" title="image" src="http://elegantcode.com/wp-content/uploads/2009/10/image_thumb3.png" border="0" alt="image" width="600" height="580" /></a>

Now if you try to execute one of those newly added extension methods, you may get the following error…

PS C:\&gt; $testVar.<strong>ShouldEqual</strong>("hello world")

Exception calling "ShouldEqual" with "1" argument(s): "<strong>Unable to find type [NUnit.Framework.Assert]: make sure that the

assembly containing this type is loaded.</strong>"

At line:1 char:21

+ $testVar.ShouldEqual &lt;&lt;&lt;&lt; ("hello world")

+ CategoryInfo          : NotSpecified: (:) [], MethodInvocationException

+ FullyQualifiedErrorId : ScriptMethodRuntimeException

This is because we need to load the NUnit.Framework assembly into the runtime before we can leverage the extension methods.
<blockquote>[System.Reflection.Assembly]::LoadFrom("C:\Program Files\NUnit 2.5.2\bin\net-2.0\framework\nunit.framework.dll") | Out-Null</blockquote>
Now that the extension methods have been defined and loaded into the runtime, NUnit.Framework is loaded, we can now use the methods on any object that inherits from System.Object (which, as far as I know, is everything in PowerShell).

And now, everything you need in one script (if you have the xml extended type file saved somewhere…)
<pre>#
# Update-TypeData -prependPath C:\Code\NunitSpecificationPowerShellExtensions.ps1xml
#

[System.Reflection.Assembly]::LoadFrom("C:\Program Files\NUnit 2.5.2\bin\net-2.0\framework\nunit.framework.dll") | Out-Null

$true.ShouldBeTrue()

$false.ShouldBeFalse()

"a".ShouldEqual("a")

"a".ShouldNotEqual("b")</pre>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/10/25/integration-test-brought-to-you-by-powershell-nunit-with-a-little-specification-syntax-for-flavoring/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Visual Studio Team System for Small Teams</title>
		<link>http://elegantcode.com/2009/08/24/visual-studio-team-system-for-small-teams/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=visual-studio-team-system-for-small-teams</link>
		<comments>http://elegantcode.com/2009/08/24/visual-studio-team-system-for-small-teams/#comments</comments>
		<pubDate>Mon, 24 Aug 2009 23:27:41 +0000</pubDate>
		<dc:creator>David Starr</dc:creator>
				<category><![CDATA[ALM]]></category>
		<category><![CDATA[Craftsmanship]]></category>
		<category><![CDATA[Source Control]]></category>
		<category><![CDATA[Team System]]></category>
		<category><![CDATA[Tools and Utilities]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://elegantcode.com/2009/08/24/visual-studio-team-system-for-small-teams/</guid>
		<description><![CDATA[There was a recent brouhaha on Twitter and in some blogs about the appropriateness of Team System in small teams. The gist of the discussion was simply that there are a lot of alternatives to TFS and VSTS tooling and many of them come cheaper out of the box. In many cases, free! Duh. I [...]]]></description>
			<content:encoded><![CDATA[<p>There was a recent brouhaha on Twitter and in some blogs about the appropriateness of Team System in small teams. The gist of the discussion was simply that there are a lot of alternatives to TFS and VSTS tooling and many of them come cheaper out of the box. In many cases, free!</p>  <p>Duh.</p>  <p>I have worked with Team System quite a bit and with alternatives just as much. With a lot of experience behind me on this, I feel confident I can make a legitimate case for using Team System in a small team.</p>  <p>I consider a small team a development organization of fewer than 10 people.</p>  <h3>Some Context and Disclosure</h3>  <ul>   <li>I am a Team System MVP </li>    <li>I use Team System on a daily basis </li>    <li>I use SVN+Team City on a daily basis </li>    <li>I care more about pragmatism and craftsmanship than tooling, and that means focusing on how to use tools, not just the tools themselves </li>    <li>I have been present on day one of a brand new team </li>    <li>I have been in a team that has grown quickly over a short time </li> </ul>  <h3>Focus on the Work</h3>  <p>What happens when teams squabble about tools instead of just getting on with it? Lots of churn and wasted energy, is my experience. </p>  <p>I can report having seen small teams succeed and fail. The success or failure in both cases obviously has a lot more to do with leadership and business than developer tools, but I can also say the way companies approach developer tooling can have a lot to do with culture.</p>  <p>Any startup or small team simply <em>must</em> be focused to succeed. This can also be extremely difficult to achieve. A small team simply doesn’t have the capacity or depth to be distracted with issues not pertaining to delivering product. Paradoxically, team members are often wearing several hats. That is, everyone is doing a little of everything. That can quickly trend to entropy, because no one ends focusing on the work at hand.</p>  <p>The last thing I want to do on day 1 of a new team, or very often in a small teams, is visit tooling. Not deliberately making choices about tooling, though, will eventually bite you. Hard. How many of us are in organizations with over 2 brands of source control systems because new ones were added in an ad-hoc manor? I’ve been there. How many unit test frameworks are being used? I have been on a team that used 4 at once. Think that caused some problems?</p>  <p>As team lead, I care far less about optimizations of specific tools, and far more about a cohesive and fluid process enabling flow within the team. I care a great deal that there is a single source of truth for requirements and very little that we are using the coolest new unit test framework.</p>  <p>Often, focusing on work simply means implementing a system of tools and getting past the discussion. Have you ever heard developers purse fight over text editors? Now, there’s a constructive use of energy. The same thing can happen when geeks whip out their favorite source control, merge tools, unit testing frameworks, Visual Studio add-ins, logging library, laptop brand, or bug tracking system. </p>  <p>Point number one is let’s get past the time suck of the my-NAnt-is-better-than-your-MS-Build and just prescribe a toolset so we can get on with the real business of our team. </p>  <h3>Team System is Like a Box of Tools at Sears</h3>  <p>When I go to Sears and browse the Craftsman (or DeWalt) tools, I usually see some interesting little specialty tools. I might buy a funky swivel socket or a single ratchet, but I rarely browse the aisle with the large all-in-one kits. The reason I don’t browse the kit aisle is because my father-in-law bought be a basic Craftsman starter kit almost 20 years ago and my collection of tools has grown over time. </p>  <p>I don’t still have all of the tools in that original kit, but I do still have many of them. Further, my need for hand tools have gotten more specialized over time. Also, I am making a bit more money than I was when I married my wife, so I may spend extra for a special-purpose hammer rather than always relying on the one that came in the original kit.</p>  <p>Without that original kit, though, I would never have been able to even get started. No, it didn’t have every tool I would ever need, but it had almost everything I needed right then.</p>  <p>Team System is much the same. A team can absolutely hit the ground running with the rich toolset VSTS provides. Maybe you’ll augment the toolbox over time. Maybe you’ll even change tools (can anyone say [TestClass]?) but the kit that comes in the box really can provide most of what a small team needs to get going, and do it in a single solution.</p>  <p>That’s huge. </p>  <p>As soon as I start looking around to sub-optimize my hammer or my source control, I am going to start slowing the team down. GIT? SVN? PerForce? There are a ton of options for source control, each with their strengths and weaknesses. It’s freaking source control. Get on with it. I mean, how sexy can a hammer be?</p>  <h3>It May Not Cost What You Think</h3>  <p>You can buy a big toolkit at Sears for far less than it costs to buy all the tools individually. Further, buying the toolkit for the person without tools is a good move because they will have all the basics covered in a single purchase. </p>  <p>Craftsman Toolkits are a favorite gift of mine for graduates and newlyweds for this very reason.</p>  <p>Microsoft has the same insight that Sears had. If a person gets accustomed to Craftsman by selling the kit cheaply, they’ll be a customer for life. This is the exact idea behind the BizSpark program. If you aren’t familiar with it, BizSpark is a Microsoft program that allows free (that’s right, free!) access to all developer tools, operating systems, and other software for startups.</p>  <p>Is your company less than 2 years old? Do you make software? If yes, you qualify, I kid you not.</p>  <h3>Integration Matters</h3>  <p>Even if you are paying full price (which you shouldn’t :) ) I believe the value of VSTS is still there. The productivity loss involved in setting up a system of disparate and non-integrated developer tools is tremendous. I have been there and done that.</p>  <p>I know SVN is good. I know Team City is good. I also know that setting up a basic Continuous Integration build in Team System is stupid simple. And the real money shot comes with Work Item management. How many teams out there are using work item management systems or defect tracking systems they hate?</p>  <p>Well, we all are. </p>  <p>So, we may as well have one that works right in the IDE and allows me to tie check ins to work I am performing. The context switching that occurs in non-integrated systems of reporting, SCC, build, and work item management is HUGE. Huge! No really. </p>  <h3>Get On With It</h3>  <p>The people involved in the recent online Team System kerfuffle are folks I would consider in the top 1% of developer talent. Quite frankly, it makes a lot of sense to me that people at that level will have replaced their hammer from the kit with one that has an ergonomic grip.</p>  <p>That said, there are a lot of startups and small teams in entropy out there. For those folks, I firmly believe that standardizing on an integrated toolset for the development team is a bigger savings than “free like a puppy” solutions that can work well, but with more churn.</p>  <p>Now quit fussing about source control and learn how to use a decent ORM, people.</p>]]></content:encoded>
			<wfw:commentRss>http://elegantcode.com/2009/08/24/visual-studio-team-system-for-small-teams/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
	</channel>
</rss>

