<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss 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/" xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">

<channel>
	<title>Thoughtology » AutoFixture</title>
	
	<link>http://megakemp.wordpress.com</link>
	<description>The art of thinking about technology</description>
	<lastBuildDate>Fri, 24 Feb 2012 20:44:41 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain="megakemp.wordpress.com" port="80" path="/?rsscloud=notify" registerProcedure="" protocol="http-post" />
<image>
		<url>http://1.gravatar.com/blavatar/3c23d5ca864e4cdac09348530fb3a7c6?s=96&amp;d=http%3A%2F%2Fs2.wp.com%2Fi%2Fbuttonw-com.png</url>
		<title>Thoughtology » AutoFixture</title>
		<link>http://megakemp.wordpress.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://megakemp.wordpress.com/osd.xml" title="Thoughtology" />
	
		<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/thoughtology/autofixture" /><feedburner:info uri="thoughtology/autofixture" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://megakemp.wordpress.com/?pushpress=hub" /><item>
		<title>Keep your unit tests DRY with AutoFixture Customizations</title>
		<link>http://feedproxy.google.com/~r/thoughtology/autofixture/~3/zs8CUAcmx4s/</link>
		<comments>http://megakemp.wordpress.com/2011/12/15/keep-your-unit-tests-dry-with-autofixture-customizations/#comments</comments>
		<pubDate>Thu, 15 Dec 2011 13:51:54 +0000</pubDate>
		<dc:creator>Enrico Campidoglio</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[AutoFixture]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Unit testing]]></category>

		<guid isPermaLink="false">http://megakemp.wordpress.com/?p=942</guid>
		<description><![CDATA[When I first incorporated AutoFixture as part of my daily unit testing workflow, I noticed how a consistent usage pattern had started to emerge. This pattern can be roughly summarized in three steps: Initialize an instance of the Fixture class. Configure the way different types of objects involved in the test should be created by [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=megakemp.wordpress.com&amp;blog=4633671&amp;post=942&amp;subd=megakemp&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>When I first incorporated <a href="http://autofixture.codeplex.com">AutoFixture</a> as part of my daily unit testing workflow, I noticed how a consistent usage pattern had started to emerge.<br />
This pattern can be roughly summarized in three steps:</p>
<ol>
<li><strong>Initialize</strong> an instance of the <code>Fixture</code> class.</li>
<li><strong>Configure</strong> the way different types of objects involved in the test should be created by using the <code>Build&lt;T&gt;</code> method.</li>
<li><strong>Create</strong> the actual objects with the <code>CreateAnonymous&lt;T&gt;</code> or <code>CreateMany&lt;T&gt;</code> methods.</li>
</ol>
<p>As a result, my unit tests had started to look a lot like this:</p>
<p><pre class="brush: csharp; light: true;">
[Test]
public void WhenGettingAListOfPublishedPostsThenItShouldOnlyIncludeThose()
{
    // Step 1: Initialize the Fixture
    var fixture = new Fixture();

    // Step 2: Configure the object creation
    var draft = fixture.Build&lt;Post&gt;()
        .With(a =&gt; a.IsDraft = true)
        .CreateAnonymous();
    var publishedPost = fixture.Build&lt;Post&gt;()
        .With(a =&gt; a.IsDraft = false)
        .CreateAnonymous();
    fixture.Register&lt;IEnumerable&lt;Post&gt;&gt;(() =&gt; new[] { draft, publishedPost });

    // Step 3: Create the anonymous objects
    var posts = fixture.CreateMany&lt;Post&gt;();

   // Act and Assert...
}
</pre></p>
<p>In this particular configuration, AutoFixture will satisfy all requests for <code>IEnumerable&lt;Post&gt;</code> types by returning the same array with exactly two <code>Post</code> objects: one with the <code>IsDraft</code> property set to <code>True</code> and one with the same property set to <code>False</code>.</p>
<p>At that point I felt pretty satisfied with the way things were shaping up: I had managed to replace entire blocks of boring object initialization code with a couple of calls to the AutoFixture API, my unit tests were getting smaller and all was good.</p>
<h2>Duplication creeps in</h2>
<p>After a while though, the configuration lines created in <em>Step 2</em> started to repeat themselves across multiple unit tests. This was naturally due to the fact that <strong>different unit tests sometimes shared a common set of object states in their test scenario</strong>. Things weren&#8217;t so DRY anymore and suddenly it wasn&#8217;t uncommon to find code like this in the test suite:</p>
<p><pre class="brush: csharp; highlight: [2,18]; light: true;">
[Test]
public void WhenGettingAListOfPublishedPostsThenItShouldOnlyIncludeThose()
{
    var fixture = new Fixture();
    var draft = fixture.Build&lt;Post&gt;()
        .With(a =&gt; a.IsDraft = true)
        .CreateAnonymous();
    var publishedPost = fixture.Build&lt;Post&gt;()
        .With(a =&gt; a.IsDraft = false)
        .CreateAnonymous();
    fixture.Register&lt;IEnumerable&lt;Post&gt;&gt;(() =&gt; new[] { draft, publishedPost });
    var posts = fixture.CreateMany&lt;Post&gt;();

    // Act and Assert...
}

[Test]
public void WhenGettingAListOfDraftsThenItShouldOnlyIncludeThose()
{
    var fixture = new Fixture();
    var draft = fixture.Build&lt;Post&gt;()
        .With(a =&gt; a.IsDraft = true)
        .CreateAnonymous();
    var publishedPost = fixture.Build&lt;Post&gt;()
        .With(a =&gt; a.IsDraft = false)
        .CreateAnonymous();
    fixture.Register&lt;IEnumerable&lt;Post&gt;&gt;(() =&gt; new[] { draft, publishedPost });
    var posts = fixture.CreateMany&lt;Post&gt;();

    // Different Act and Assert...
}
</pre></p>
<p>See how these two tests share the same initial state even though they verify completely different behaviors? Such blatant duplication in the test code is a problem, since it inhibits the ability to make changes.<br />
Luckily a solution was just around the corner as I discovered <a href="http://blog.ploeh.dk/2011/03/18/EncapsulatingAutoFixtureCustomizations.aspx">customizations</a>.</p>
<h2>Customizing your way out</h2>
<p>A customization is a pretty general term. However, put in the context of AutoFixture it assumes a specific definition:</p>
<div style="border-bottom:#e6db55 1px solid;border-left:#e6db55 1px solid;background-color:rgb(255,251,204);border-top:#e6db55 1px solid;border-right:#e6db55 1px solid;padding:10px;">
A <strong>customization</strong> is a group of settings that, when applied to a given <code>Fixture</code>, control the way AutoFixture will create anonymous instances of the types requested through that <code>Fixture</code>.</div>
<p>What that means is that I could take all the boilerplate configuration code produced during <em>Step 2</em> and move it out of my unit tests into a single place, that is a customization. That allowed me to <strong>specify only once how different objects needed to be created for a given scenario</strong>, and reuse that across multiple tests.</p>
<p><pre class="brush: csharp; light: true;">
public class MixedDraftsAndPublishedPostsCustomization : ICustomization
{
    public void Customize(IFixture fixture)
    {
        var draft = fixture.Build&lt;Post&gt;()
            .With(a =&gt; a.IsDraft = true)
            .CreateAnonymous();
        var publishedPost = fixture.Build&lt;Post&gt;()
            .With(a =&gt; a.IsDraft = false)
            .CreateAnonymous();
        fixture.Register&lt;IEnumerable&lt;Post&gt;&gt;(() =&gt; new[] { draft, publishedPost });
    }
}
</pre></p>
<p>As you can see, <code>ICustomization</code> is nothing more than a <a href="http://martinfowler.com/bliki/RoleInterface.html">role interface</a> that describes how a <code>Fixture</code> should be set up. In order to apply a customization to a specific <code>Fixture</code> instance, you&#8217;ll simply have to call the <code>Fixture.Customize(ICustomization)</code> method, like shown in the example below.<br />
This newly won encapsulation allowed me to rewrite my unit tests in a much more terse way:</p>
<p><pre class="brush: csharp; light: true;">
[Test]
public void WhenGettingAListOfDraftsThenItShouldOnlyIncludeThose()
{
    // Step 1: Initialize the Fixture
    var fixture = new Fixture();

    // Step 2: Apply the customization for the test scenario
    fixture.Customize(new MixedDraftsAndPublishedPostsCustomization());

    // Step 3: Create the anonymous objects
    var posts = fixture.CreateMany&lt;Post&gt;();

    // Act and Assert...
}
</pre></p>
<p>The configuration logic now exists only in one place, namely a class whose name clearly describes the kind of test data it will produce.<br />If applied consistently, this approach will in time <strong>build up a library of customizations, each representative of a given situation or scenario</strong>. Assuming that they are created at the proper level of granularity, these customizations could even be composed to form more complex scenarios.</p>
<h2>Conclusion</h2>
<p>Customizations in <a href="http://autofixture.codeplex.com">AutoFixture</a> are a pretty powerful concept in of themselves, but they become even more effective when <strong>mapped directly to test scenarios</strong>. In fact, they represent a natural place to specify which objects are involved in a given scenario and the state they are supposed to be in. You can use them to remove duplication in your test code and, in time, build up a library of self-documenting modules, which describe the different contexts in which the system&#8217;s behavior is being verified.</p>
<br />Filed under: <a href='http://megakemp.wordpress.com/category/net/'>.NET</a>, <a href='http://megakemp.wordpress.com/category/software-development/'>Software Development</a> Tagged: <a href='http://megakemp.wordpress.com/tag/net/'>.NET</a>, <a href='http://megakemp.wordpress.com/tag/autofixture/'>AutoFixture</a>, <a href='http://megakemp.wordpress.com/tag/c/'>C#</a>, <a href='http://megakemp.wordpress.com/tag/unit-testing/'>Unit testing</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/megakemp.wordpress.com/942/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/megakemp.wordpress.com/942/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/megakemp.wordpress.com/942/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/megakemp.wordpress.com/942/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/megakemp.wordpress.com/942/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/megakemp.wordpress.com/942/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/megakemp.wordpress.com/942/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/megakemp.wordpress.com/942/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/megakemp.wordpress.com/942/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/megakemp.wordpress.com/942/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/megakemp.wordpress.com/942/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/megakemp.wordpress.com/942/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/megakemp.wordpress.com/942/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/megakemp.wordpress.com/942/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=megakemp.wordpress.com&amp;blog=4633671&amp;post=942&amp;subd=megakemp&amp;ref=&amp;feed=1" width="1" height="1" /><img src="http://feeds.feedburner.com/~r/thoughtology/autofixture/~4/zs8CUAcmx4s" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://megakemp.wordpress.com/2011/12/15/keep-your-unit-tests-dry-with-autofixture-customizations/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/e1ad202622fb9b5ed28dde7b4cf255ab?s=96&amp;d=identicon&amp;r=G" medium="image">
			<media:title type="html">megakemp</media:title>
		</media:content>
	<feedburner:origLink>http://megakemp.wordpress.com/2011/12/15/keep-your-unit-tests-dry-with-autofixture-customizations/</feedburner:origLink></item>
		<item>
		<title>Behavior changes in AutoFixture 2.2 – Anonymous numbers</title>
		<link>http://feedproxy.google.com/~r/thoughtology/autofixture/~3/dpD67WAg3RI/</link>
		<comments>http://megakemp.wordpress.com/2011/09/06/behavior-changes-in-autofixture-2-2-anonymous-numbers/#comments</comments>
		<pubDate>Tue, 06 Sep 2011 15:40:34 +0000</pubDate>
		<dc:creator>Enrico Campidoglio</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[AutoFixture]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Unit testing]]></category>

		<guid isPermaLink="false">http://megakemp.wordpress.com/?p=892</guid>
		<description><![CDATA[Now that AutoFixture 2.2 is approaching on the horizon, it&#8217;s a good time to start talking about some of the changes that were made to the underlying behavior of some existing APIs. I&#8217;ll start off this series of posts by focusing on the new generation strategy for anonymous numbers. The good old fashioned way Before [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=megakemp.wordpress.com&amp;blog=4633671&amp;post=892&amp;subd=megakemp&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Now that <a href="http://twitter.com/#!/ploeh/status/109005068581343232">AutoFixture 2.2 is approaching on the horizon</a>, it&#8217;s a good time to start talking about some of the changes that were made to the underlying behavior of some existing APIs. I&#8217;ll start off this series of posts by focusing on the new generation strategy for anonymous numbers.</p>
<h2>The good old fashioned way</h2>
<p>Before I jump into the details of what exactly has been changed and how, allow me to set up a little bit of stage:</p>
<div style="border-bottom:#e6db55 1px solid;border-left:#e6db55 1px solid;background-color:rgb(255,251,204);border-top:#e6db55 1px solid;border-right:#e6db55 1px solid;padding:10px;">A key part of AutoFixture&#8217;s mission statement is to make the process of authoring unit tests faster by providing an easy way of creating test values (or &#8220;<em>specimens</em>&#8220;) for the variables involved in the test. The goal of providing values that are as neutral as possible to the test scenario at hand is achieved by employing <a href="http://blog.ploeh.dk/2009/03/05/ConstrainedNonDeterminism.aspx">&#8220;constrained non-deterministic&#8221;</a> generation algorithms.</div>
<p>Put in simple terms, this essentially means that <strong>AutoFixture will come up with test values at run time that can be considered &#8220;random&#8221; within some predefined bounds</strong>. These bounds are imposed at the lowest level by the variable&#8217;s own data type: a string is a string, a number is a number and so on. More constraints, however, can be added at a higher level, based on any semantics the variable may have in the specific test scenario. For example a string can&#8217;t be longer than 20 characters or a number must be between 1 and 100.</p>
<p>AutoFixture comes with a set of built-in generation algorithms that can produce test values for all the primitive types included in the .NET Framework. The algorithm for numeric types has historically been based on individually incremented sequences, one for each numeric data type. Let&#8217;s look at an example that illustrates this:</p>
<p><pre class="brush: csharp; gutter: false;">
var fixture = new Fixture();
Console.WriteLine(&quot;Byte specimen is {0}, {1}&quot;,
    fixture.CreateAnonymous&lt;byte&gt;(),
    fixture.CreateAnonymous&lt;byte&gt;());
Console.WriteLine(&quot;Int32 specimen is {0}, {1}&quot;,
    fixture.CreateAnonymous&lt;int&gt;(),
    fixture.CreateAnonymous&lt;int&gt;());
Console.WriteLine(&quot;Single specimen is {0}, {1}&quot;,
    fixture.CreateAnonymous&lt;float&gt;(),
    fixture.CreateAnonymous&lt;float&gt;());

// The output will be:
// Byte specimen is 1, 2
// Int32 specimen is 1, 2
// Single specimen is 1, 2
</pre></p>
<p>The key point here is that <strong>AutoFixture will only guarantee unique numeric specimens within the scope of a specific data type</strong>. Now, you may wonder how this would be a problem. Well, it certainly isn&#8217;t in itself, but if you asked AutoFixture to give you an anonymous instance of a class with multiple properties of different numeric types, you would get something like this:</p>
<p><pre class="brush: csharp; gutter: false;">
public class NumericBag
{
    public byte ByteValue { get; set; }
    public int Int32Value { get; set; }
    public float SingleValue { get; set; }
}

var fixture = new Fixture();
var specimen = fixture.CreateAnonymous&lt;NumericBag&gt;();
Console.WriteLine(&quot;ByteValue property is {0}&quot;, specimen.ByteValue);
Console.WriteLine(&quot;Int32Value property is {0}&quot;, specimen.Int32Value);
Console.WriteLine(&quot;SingleValue property is {0}&quot;, specimen.SingleValue);

// The output will be:
// ByteValue property is 1
// Int32Value property is 1
// SingleValue property is 1
</pre></p>
<p>We can agree that the end result doesn&#8217;t exactly live up to the expectation of anonymous values being &#8220;random&#8221;. Starting from version 2.2, however, this behavior is due to change.</p>
<h2>The fresh new way</h2>
<p>AutoFixture has taken a different approach to numeric specimen generation and <strong>will now by default return unique values across all numeric types</strong>. Running our first example in AutoFixture 2.2 will therefore yield a very different result:</p>
<p><pre class="brush: csharp; gutter: false; highlight: [13,14,15];">
var fixture = new Fixture();
Console.WriteLine(&quot;Byte specimen is {0}, {1}&quot;,
    fixture.CreateAnonymous&lt;byte&gt;(),
    fixture.CreateAnonymous&lt;byte&gt;());
Console.WriteLine(&quot;Int32 specimen is {0}, {1}&quot;,
    fixture.CreateAnonymous&lt;int&gt;(),
    fixture.CreateAnonymous&lt;int&gt;());
Console.WriteLine(&quot;Single specimen is {0}, {1}&quot;,
    fixture.CreateAnonymous&lt;float&gt;(),
    fixture.CreateAnonymous&lt;float&gt;());

// The output will be:
// Byte specimen is 1, 2
// Int32 specimen is 3, 4
// Single specimen is 5, 6
</pre></p>
<p>In other words, AutoFixture is being a little more &#8220;non-deterministic&#8221; when it comes to numeric test values. Take for example the following scenario:</p>
<p><pre class="brush: csharp; gutter: false; highlight: [15,16,17];">
public class NumericBag
{
    public byte ByteValue { get; set; }
    public int Int32Value { get; set; }
    public float SingleValue { get; set; }
}

var fixture = new Fixture();
var specimen = fixture.CreateAnonymous&lt;NumericBag&gt;();
Console.WriteLine(&quot;ByteValue property is {0}&quot;, specimen.ByteValue);
Console.WriteLine(&quot;Int32Value property is {0}&quot;, specimen.Int32Value);
Console.WriteLine(&quot;SingleValue property is {0}&quot;, specimen.SingleValue);

// The output will be:
// ByteValue property is 1
// Int32Value property is 2
// SingleValue property is 3
</pre></p>
<p>See how all the numeric properties on the generated object have different values? That&#8217;s what I&#8217;m talking about.</p>
<p>Now, in theory, this shouldn&#8217;t be considered a breaking change. I say this because AutoFixture is all about <a href="http://blogs.msdn.com/b/ploeh/archive/2008/11/17/anonymous-variables.aspx">anonymous variables</a>, which, by definition, can&#8217;t be expected to have specific values during a test run. So, as long as you&#8217;ve played by this rule, the new behavior shouldn&#8217;t impact any of your existing tests.</p>
<p>However, if this does turn out to be a problem or you simply prefer the old way of doing things, you shouldn&#8217;t feel left out in the cold. The <strong>previous behavior is still in the box, packaged up in a nice customization</strong> unambiguously named <code>NumericSequencePerTypeCustomization</code>. The simple act of adding it to a Fixture instance will restore things the way they were:</p>
<p><pre class="brush: csharp; gutter: false;">
var fixture = new Fixture();
fixture.Customize(new NumericSequencePerTypeCustomization());
</pre></p>
<p>If you wish to try this out today, I encourage you to go head and grab the latest build off of <a href="http://teamcity.codebetter.com/project.html;jsessionid=C212815CFF41DFCD2E93DDDECABF1668?projectId=project129&amp;tab=projectOverview">AutoFixture&#8217;s project page on Team City</a>. Enjoy.</p>
<br />Filed under: <a href='http://megakemp.wordpress.com/category/net/'>.NET</a>, <a href='http://megakemp.wordpress.com/category/software-development/'>Software Development</a> Tagged: <a href='http://megakemp.wordpress.com/tag/net/'>.NET</a>, <a href='http://megakemp.wordpress.com/tag/autofixture/'>AutoFixture</a>, <a href='http://megakemp.wordpress.com/tag/c/'>C#</a>, <a href='http://megakemp.wordpress.com/tag/unit-testing/'>Unit testing</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/megakemp.wordpress.com/892/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/megakemp.wordpress.com/892/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/megakemp.wordpress.com/892/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/megakemp.wordpress.com/892/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/megakemp.wordpress.com/892/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/megakemp.wordpress.com/892/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/megakemp.wordpress.com/892/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/megakemp.wordpress.com/892/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/megakemp.wordpress.com/892/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/megakemp.wordpress.com/892/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/megakemp.wordpress.com/892/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/megakemp.wordpress.com/892/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/megakemp.wordpress.com/892/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/megakemp.wordpress.com/892/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=megakemp.wordpress.com&amp;blog=4633671&amp;post=892&amp;subd=megakemp&amp;ref=&amp;feed=1" width="1" height="1" /><img src="http://feeds.feedburner.com/~r/thoughtology/autofixture/~4/dpD67WAg3RI" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://megakemp.wordpress.com/2011/09/06/behavior-changes-in-autofixture-2-2-anonymous-numbers/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/e1ad202622fb9b5ed28dde7b4cf255ab?s=96&amp;d=identicon&amp;r=G" medium="image">
			<media:title type="html">megakemp</media:title>
		</media:content>
	<feedburner:origLink>http://megakemp.wordpress.com/2011/09/06/behavior-changes-in-autofixture-2-2-anonymous-numbers/</feedburner:origLink></item>
		<item>
		<title>Anonymous delegates in AutoFixture</title>
		<link>http://feedproxy.google.com/~r/thoughtology/autofixture/~3/UKai-KJmba8/</link>
		<comments>http://megakemp.wordpress.com/2011/08/01/anonymous-delegates-in-autofixture/#comments</comments>
		<pubDate>Mon, 01 Aug 2011 21:16:40 +0000</pubDate>
		<dc:creator>Enrico Campidoglio</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Software Development]]></category>
		<category><![CDATA[AutoFixture]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Unit testing]]></category>

		<guid isPermaLink="false">https://megakemp.wordpress.com/?p=720</guid>
		<description><![CDATA[I’m excited to announce that AutoFixture now officially supports delegates in the main trunk up on CodePlex. If you aren&#8217;t familiar with AutoFixture, let me give you the pitch: AutoFixture is an open source framework for .NET designed to minimize the &#8216;Arrange&#8217; phase of your unit tests. Its primary goal is to allow developers to [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=megakemp.wordpress.com&amp;blog=4633671&amp;post=720&amp;subd=megakemp&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>I’m excited to announce that <a href="http://autofixture.codeplex.com">AutoFixture</a> now officially supports delegates in the <a href="http://autofixture.codeplex.com/SourceControl/changeset/changes/48b0ea5a7f15">main trunk</a> up on CodePlex.</p>
<p>If you aren&#8217;t familiar with AutoFixture, let me give you the pitch:</p>
<div style="border-bottom:#e6db55 1px solid;border-left:#e6db55 1px solid;background-color:rgb(255,251,204);border-top:#e6db55 1px solid;border-right:#e6db55 1px solid;padding:10px;"><strong>AutoFixture</strong> is an open source framework for .NET designed to minimize the &#8216;Arrange&#8217; phase of your unit tests. Its primary goal is to allow developers to focus on what is being tested rather than how to setup the test scenario, by making it easier to create object graphs containing test data.</div>
<p>Does this sound interesting to you? In that case head over to the <a href="http://autofixture.codeplex.com">AutoFixture CodePlex site</a> and find out more. You’ll be glad you did.</p>
<p>For those of you already familiar with AutoFixture, the newly added support for delegates means that every time AutoFixture is asked to create an anonymous instance of a delegate type (or more precisely a <em>delegate specimen</em>), it will actually return one, instead of throwing an exception.</p>
<p>So, you’ll be able to say things like:</p>
<p><pre class="brush: csharp; gutter: false;">
public delegate void MyDelegate();

var fixture = new Fixture();
var delegateSpecimen = fixture.CreateAnonymous&lt;MyDelegate&gt;();
</pre></p>
<p>and get back <strong>a delegate pointing to a dynamically generated method</strong>, whose signature matches the one of the requested delegate type. In other words AutoFixture will satisfy the requests for delegates by providing a <em>method specimen</em>.</p>
<p>That’s cool, but it may leave you wondering: what on Earth does a method specimen do when it gets invoked? Well, in order to answer that question, we need to look at the signature of the delegate that was requested in the first place. The rule basically says:</p>
<div style="border-bottom:#e6db55 1px solid;border-left:#e6db55 1px solid;background-color:rgb(255,251,204);padding-right:10px;border-top:#e6db55 1px solid;border-right:#e6db55 1px solid;">
<ul>
<li>If the signature of the requested delegate <strong>has a return value</strong> (i.e. it’s a <em>function</em>), the method specimen will always return an anonymous value of the return type.</li>
<li>If the signature of the requested delegate <strong>doesn’t have a return value</strong> (i.e. it’s an <em>action</em>) the returned method specimen will have an empty body.</li>
</ul>
</div>
<p>This principle is best illustrated by examples. Consider the following code snippet:</p>
<p><pre class="brush: csharp; gutter: false;">
var fixture = new Fixture();
var funcSpecimen = fixture.CreateAnonymous&lt;Func&lt;string&gt;&gt;();
var result = funcSpecimen();

// result = &quot;fd95320f-0a37-42be-bd49-3afbbe089d9d&quot;
</pre></p>
<p>In this example, since the signature of the requested delegate has a return value of type <a href="http://msdn.microsoft.com/en-us/library/system.string.aspx">String</a>, the <font face="Consolas">result</font> variable will contain an anonymous string value, which in AutoFixture usually translates into a GUID.<br />On the other hand, if requested delegate didn&#8217;t have a return value, invoking the anonymous delegate would do just about nothing:</p>
<p><pre class="brush: csharp; gutter: false;">
var fixture = new Fixture();
var actionSpecimen = fixture.CreateAnonymous&lt;Action&lt;string&gt;&gt;();
actionSpecimen(&quot;whatever&quot;); // no-op
</pre></p>
<p>Note that in both cases <strong>any input arguments passed to the anonymous delegate will be ignored</strong>, since they don&#8217;t have any impact on the generated method specimen.</p>
<p>Now, if you’re using AutoFixture from <a href="http://nuget.org/List/Packages/AutoFixture">its NuGet package</a> (which, by the way, you should) you’ll have to wait until the next release to get this feature. However, taking advantage of it with the current version of AutoFixture requires a minimal amount of effort. Just <a href="http://autofixture.codeplex.com/SourceControl/changeset/view/493eecec7784#Src%2fAutoFixture%2fKernel%2fDelegateGenerator.cs">grab the DelegateGenerator.cs class from AutoFixture&#8217;s main trunk</a> on CodePlex and include it in your project. You’ll then be able to add support for delegates to your Fixture instance by simply saying:</p>
<p><pre class="brush: csharp; gutter: false;">
var fixture = new Fixture();
fixture.Customizations.Add(new DelegateGenerator());
</pre></p>
<p>You can even <a href="http://blog.ploeh.dk/2011/03/18/EncapsulatingAutoFixtureCustomizations.aspx">wrap that up in a Customization</a> to make it more centralized and keep your test library <a href="http://en.wikipedia.org/wiki/Don't_repeat_yourself">DRY</a>:</p>
<p><pre class="brush: csharp; gutter: false;">
public class DelegateCustomization : ICustomization
{
    public void Customize(IFixture fixture)
    {
        if (fixture == null)
        {
            throw new ArgumentNullException(&quot;fixture&quot;);
        }

        fixture.Customizations.Add(new DelegateGenerator());
    }
}
</pre></p>
<p>Before finishing this off, let me give you a more concrete example that shows how this is useful in a real world scenario. Keeping in mind that delegates offer a pretty terse way to implement the <a href="http://sourcemaking.com/design_patterns/strategy">Strategy Design Pattern</a> in .NET, consider this implementation of the <a href="http://msdn.microsoft.com/en-us/library/ms132151.aspx">IEqualityComparer&lt;T&gt; interface</a>:</p>
<p><pre class="brush: csharp; gutter: false;">
public class EqualityComparer&lt;T&gt; : IEqualityComparer&lt;T&gt;
{
    private readonly Func&lt;T, T, bool&gt; equalityStrategy;
    private readonly Func&lt;T, int&gt; hashCodeStrategy;

    public EqualityComparer(Func&lt;T, T, bool&gt; equalityStrategy, Func&lt;T, int&gt; hashCodeStrategy)
    {
        if (equalityStrategy == null)
        {
            throw new ArgumentNullException(&quot;equalityStrategy&quot;);
        }

        if (hashCodeStrategy == null)
        {
            throw new ArgumentNullException(&quot;hashCodeStrategy&quot;);
        }

        this.equalityStrategy = equalityStrategy;
        this.hashCodeStrategy = hashCodeStrategy;
    }

    public bool Equals(T x, T y)
    {
        return equalityStrategy(x, y);
    }

    public int GetHashCode(T obj)
    {
        return hashCodeStrategy(obj);
    }
}
</pre></p>
<p>That&#8217;s a nice flexible class that, by allowing to specify the comparison logic in the form of delegates, is suitable in different scenarios. Before the support for delegates was added, however, having AutoFixture play along with this class in the context of unit testing would be quite problematic. The tests would, in fact, fail consistently with a <a href="http://msdn.microsoft.com/en-us/library/system.notsupportedexception.aspx">NotSupportedException</a>, since the constructor of the <font face="Consolas">EqualityComparer</font> class requires the creation of two delegates.<br />Luckily, this is not a problem anymore.</p>
<br />Filed under: <a href='http://megakemp.wordpress.com/category/net/'>.NET</a>, <a href='http://megakemp.wordpress.com/category/software-development/'>Software Development</a> Tagged: <a href='http://megakemp.wordpress.com/tag/net/'>.NET</a>, <a href='http://megakemp.wordpress.com/tag/autofixture/'>AutoFixture</a>, <a href='http://megakemp.wordpress.com/tag/c/'>C#</a>, <a href='http://megakemp.wordpress.com/tag/unit-testing/'>Unit testing</a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/megakemp.wordpress.com/720/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/megakemp.wordpress.com/720/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/megakemp.wordpress.com/720/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/megakemp.wordpress.com/720/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/megakemp.wordpress.com/720/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/megakemp.wordpress.com/720/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/megakemp.wordpress.com/720/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/megakemp.wordpress.com/720/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/megakemp.wordpress.com/720/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/megakemp.wordpress.com/720/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/megakemp.wordpress.com/720/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/megakemp.wordpress.com/720/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/megakemp.wordpress.com/720/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/megakemp.wordpress.com/720/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=megakemp.wordpress.com&amp;blog=4633671&amp;post=720&amp;subd=megakemp&amp;ref=&amp;feed=1" width="1" height="1" /><img src="http://feeds.feedburner.com/~r/thoughtology/autofixture/~4/UKai-KJmba8" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://megakemp.wordpress.com/2011/08/01/anonymous-delegates-in-autofixture/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/e1ad202622fb9b5ed28dde7b4cf255ab?s=96&amp;d=identicon&amp;r=G" medium="image">
			<media:title type="html">megakemp</media:title>
		</media:content>
	<feedburner:origLink>http://megakemp.wordpress.com/2011/08/01/anonymous-delegates-in-autofixture/</feedburner:origLink></item>
	</channel>
</rss>

