<?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>Dude, where is my Kaizen? &#187; xUnit</title>
	<atom:link href="http://www.bjoernrochel.de/category/testing/unittestfx/xunit-unittestfx/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.bjoernrochel.de</link>
	<description>Björn Rochel&#039;s weblog</description>
	<lastBuildDate>Mon, 21 Jun 2010 07:26:00 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.1</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>xUnit.BDDExtensions now runs with xUnit 1.5 final</title>
		<link>http://www.bjoernrochel.de/2009/09/09/xunitbddextensions-now-runs-with-xunit-15-final/</link>
		<comments>http://www.bjoernrochel.de/2009/09/09/xunitbddextensions-now-runs-with-xunit-15-final/#comments</comments>
		<pubDate>Wed, 09 Sep 2009 21:25:33 +0000</pubDate>
		<dc:creator>BjRo</dc:creator>
				<category><![CDATA[xUnit]]></category>
		<category><![CDATA[xUnit.BDDExtensions]]></category>

		<guid isPermaLink="false">http://www.bjoernrochel.de/?p=551</guid>
		<description><![CDATA[I&#8217;ve just upgraded the trunk to the final 1.5 version of xUnit released last week. This update now allows BDDExtensions to be used with the latest version independant resharper runner for xUnit from xunitcontrib.
Current Version is 1.0.1.16. You can download it here or get the latest sources from the trunk.
Happy specifying . . .
]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve just upgraded the trunk to the final 1.5 version of xUnit released last week. This update now allows BDDExtensions to be used with the latest version independant resharper runner for xUnit from xunitcontrib.</p>
<p>Current Version is 1.0.1.16. You can download it <a href="http://xunitbddextensions.googlecode.com/files/xunit.bddextensions.1.0.1.16.zip">here</a> or get the latest sources from the <a href="http://xunitbddextensions.googlecode.com/svn/trunk/">trunk</a>.</p>
<p>Happy specifying . . .</p>
]]></content:encoded>
			<wfw:commentRss>http://www.bjoernrochel.de/2009/09/09/xunitbddextensions-now-runs-with-xunit-15-final/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Dude, I can do reports</title>
		<link>http://www.bjoernrochel.de/2009/07/05/dude-i-can-do-reports/</link>
		<comments>http://www.bjoernrochel.de/2009/07/05/dude-i-can-do-reports/#comments</comments>
		<pubDate>Sun, 05 Jul 2009 11:54:49 +0000</pubDate>
		<dc:creator>BjRo</dc:creator>
				<category><![CDATA[BDD]]></category>
		<category><![CDATA[xUnit]]></category>
		<category><![CDATA[xUnit.BDDExtensions]]></category>

		<guid isPermaLink="false">http://www.bjoernrochel.de/2009/07/05/dude-i-can-do-reports/</guid>
		<description><![CDATA[Over the past days I finally managed to spend some time with xUnit.BDDExtensions. I can&#8217;t possibly describe how good coming back to xUnit.net feels after working with MSTest in my last project. The speed, the extensibility model.&#160; It&#8217;s simply not comparable. MSTest is certainly a great tool in case you haven&#8217;t worked with a unit [...]]]></description>
			<content:encoded><![CDATA[<p>Over the past days I finally managed to spend some time with <em>xUnit.BDDExtensions</em>. I can&#8217;t possibly describe how good coming back to <em>xUnit.net</em> feels after working with <em>MSTest</em> in my last project. The speed, the extensibility model.&#160; It&#8217;s simply not comparable. <em>MSTest</em> is certainly a great tool in case you haven&#8217;t worked with a unit test framework before and it&#8217;s integration into Visual Studio is definitely a plus, too. However once you&#8217;ve got <em>Resharper</em> or <em>Gallio</em> installed the integration aspect isn&#8217;t really the big deal any more. Anyway, you can find several changes in the current trunk (<a href="http://code.google.com/p/xunitbddextensions/" target="_blank">(http://code.google.com/p/xunitbddextensions/)</a>. </p>
<h4>The biggest addition is the new ReportGenerator</h4>
<p>I&#8217;ve wanted this for quite a while now but never really found the time to implement it. After running the <em>RunBuild.cmd</em> in the &quot;Build&quot; folder of the trunk you&#8217;ll find the .exe in the &quot;Deploy&quot; folder. It&#8217;s still a bit raw but exactly what I need for my current client (yes, you heard right. <em>xUnit.BDDExtensions</em> is currently being picked up at my current client <img src='http://www.bjoernrochel.de/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> ) </p>
<p>Here are the current console arguments: </p>
<p><em>/assembly</em> configures the spec assembly to extract a report from one or more assemblies. </p>
<blockquote><p>ReportGenerator.exe /assembly:SomeSpecAssembly      <br />ReportGenerator.exe /assembly:C:\Test\SomeSpecAssembly.dll       <br />ReportGenerator.exe /assembly:&#8217;C:\Path with spaces\SomeSpecAssembly.dll&#8217; ReportGenerator.exe /assembly:SomeSpecAssembly /assembly:SomeOtherSpecAssembly</p>
</blockquote>
<p><em>/generator</em> configures the generator to use. There are currently two generators implemented. One building an ASCII .txt file which looks like <a href="http://www.bjoernrochel.de/wp-content/uploads/2009/07/xunitbddextensionsreportingspecs.txt" target="_blank">this</a>. In order to use it you have to run the generator with </p>
<blockquote><p>ReportGenerator.exe /assembly:SomeSpecAssembly /generator:Text </p>
</blockquote>
<p>The other creating an HTML file which looks like <a href="http://www.bjoernrochel.de/wp-content/uploads/2009/07/xunitbddextensionsreportingspecs.html" target="_blank">this</a>. This is the default generator which is used when you omit the <em>/generator</em> argument. </p>
<p>The files created by the generator are created on a per assembly basis and named like the assembly with the suffix .html or .txt. By default they are created in the same directory the generator is run from. </p>
<p>You can change this by configuring a different folder via <em>/path</em>. </p>
<blockquote><p>ReportGenerator.exe /assembly:C:\Test\SomeSpecAssembly.dll /path:C:\temp </p>
</blockquote>
<h3></h3>
<h4>The deployment has changed slightly</h4>
<p>The build script now merges <em>xUnit.BDDExtensions</em> to a single assembly (the external Rhino.Mocks assembly is not needed any more). Same applies to the <em>ReportGenerator</em> which uses <em>StructureMap</em> and <em>NVelocity</em> internally.    </p>
<h4>Some small changes to the API </h4>
<ul>
<li><em>Dependency&lt;TDependency&gt;()</em> has been marked as obsolete in <em>InstanceContextSpecification&lt;T&gt;</em> and <em>StaticContextSpecification</em>. </li>
<li><em>AutoDependency&lt;TDependency&gt;()</em> has been marked as obsolete in <em>InstanceContextSpecification&lt;T&gt;</em>. </li>
<li><em>An&lt;TDependency&gt;() and </em><em>Some&lt;TDependency&gt;()</em> have been added to both <em>InstanceCOntextSpecification&lt;T&gt;</em> and <em>StaticContextSpecification</em>. </li>
<li><em>The&lt;TDependency&gt;() has been added to <em>InstanceCOntextSpecification&lt;T&gt;</em></em>, </li>
</ul>
<p>Its mostly naming which has been changed. Some discussions at my current client made me realize that    <br />it&#8217;s easier to describe the behavior of xUnit.BDDExtensions to developers who haven&#8217;t used the tool before with <em>An&lt;ICar&gt;()</em> in favor of <em>Dependency&lt;ICar&gt;()</em> and <em>The&lt;ICar&gt;()</em> in favor of <em>AutoDependency&lt;ICar&gt;()</em>. </p>
<p><em>An&lt;TDependency&gt;() </em>returns a new dynamic stub object every time it&#8217;s called. <em>The&lt;TDependency&gt;()</em> behaves differently. BDDExtensions has AutoMocking support built-in. Once you let the framework create your test object you&#8217;re able to access the automatically injected dynamic stubs with this method. Last but not least <em>Some&lt;TDependency&gt;()</em> provides the same behavior as <em>An&lt;T&gt;()</em>. It only returns a collection of newly created stub objects. </p>
<p>I&#8217;m going to write a more detailed documentation of the current version soon. So in case you&#8217;re interested in the BDDExtensions, stay tuned . . . </p>
]]></content:encoded>
			<wfw:commentRss>http://www.bjoernrochel.de/2009/07/05/dude-i-can-do-reports/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Verifying indirect outputs with Rhino.Mocks in xUnit.BDDExtensions</title>
		<link>http://www.bjoernrochel.de/2009/01/30/verifying-indirect-outputs-with-rhinomocks-in-xunitbddextensions/</link>
		<comments>http://www.bjoernrochel.de/2009/01/30/verifying-indirect-outputs-with-rhinomocks-in-xunitbddextensions/#comments</comments>
		<pubDate>Fri, 30 Jan 2009 21:51:31 +0000</pubDate>
		<dc:creator>BjRo</dc:creator>
				<category><![CDATA[BDD]]></category>
		<category><![CDATA[xUnit]]></category>
		<category><![CDATA[xUnit.BDDExtensions]]></category>

		<guid isPermaLink="false">http://www.bjoernrochel.de/?p=258</guid>
		<description><![CDATA[This  post by Sean Feldman was kind of an eye opener to me. It introduced me to a feature of Rhino.Mocks I wasn&#8217;t really aware of and helped to solve a problem I was never able to solve in a really satisfying way.

As you might know xUnit.BDDExtensions is using Rhino.Mocks behind the scenes, but [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://weblogs.asp.net/sfeldman/archive/2009/01/29/factory-per-dto.aspx" target="_blank">This </a> post by Sean Feldman was kind of an eye opener to me. It introduced me to a feature of Rhino.Mocks I wasn&#8217;t really aware of and helped to solve a problem I was never able to solve in a really satisfying way.</p>
<p>
As you might know xUnit.BDDExtensions is using Rhino.Mocks behind the scenes, but hides a lot of the mechanics of the library. This was done in order to eliminate a lot of the ceremony in a specification, so that a writer of a specification could focus on its essence (Quote MASHUP from JP and Jeremy D. Miller <img src='http://www.bjoernrochel.de/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' />  ).  However, especially when configuring and verifying behaviors Rhino.Mocks still shines through (with all its power).
</p>
<p>So let&#8217;s take a closer look at the problem I&#8217;m referring to. It has to do with specifications which observe indirect outputs. The following code is part of a little object-to-object-mapper I wrote some months ago. </p>
<pre class="brush: csharp">
public class ExpressionBasedWriter&lt;Target, PropertyType&gt; : IWriteStrategy&lt;Target&gt;
{
	private readonly IExpressionHandler expressionHandler;
	private readonly MemberExpression memberExpression;

	public ExpressionBasedWriter(
		Expression&lt;Func&gt; memberSelector,
		IExpressionHandler expressionHandler)
	{
		this.memberExpression = (MemberExpression) memberSelector.Body;
		this.expressionHandler = expressionHandler;
	}

        public void WriteTo(Target instance, object value)
	{
		expressionHandler.Handle(new HandlerContext
                {
                      TargetInstanceType = instance.GetType(),
                      TargetInstance = instance,
                      ValueToWrite = value,
                      MemberSelector = memberExpression
                });
	}
}
</pre>
<p>
It&#8217;s not so important to understand the full context of the code. The important part is in the body of the WriteTo() method. Do you see it? It constructs an instance and passes it into an internal dependency. The interesting question now is how to verify the indirect output passed to the dependeny in a spec&#8230;
</p>
<p><strong>Take 1: Overriding Equals and GetHashcode() in the indirect output class.</strong></p>
<p>
In case you correctly implemented both of these methods you could write a spec, that looks like somewhat like this.</p>
<p><pre class="brush: csharp">
    [Concern(typeof(ExpressionBasedWriter&lt;,&gt;))]
    public class When_something_is_about_to_be_written : InstanceContextSpecification&lt;IWriteStrategy&lt;TestDto1&gt;&gt;
    {
        private IExpressionHandler expressionHandler;
        private Expression&lt;Func&gt; targetExpression;
        private TestDto1 target;
        private string valueToWrite;

        protected override void EstablishContext()
        {
            targetExpression = x =&gt; x.StringProperty;
            expressionHandler = Dependency();
            target = new TestDto1();
            valueToWrite = &quot;uninteresting value&quot;;
        }

        protected override IWriteStrategy CreateSut()
        {
            return new ExpressionBasedWriter(targetExpression, expressionHandler);
        }

        protected override void Because()
        {
            Sut.WriteTo(target, valueToWrite);
        }

        [Observation]
        public void should_form_a_context_and_pass_it_to_the_actual_expression_handler()
        {
            expressionHandler.WasToldTo(x =&gt; x.Handle(new HandlerContext
            {
                MemberSelector = (MemberExpression)targetExpression.Body,
                TargetInstance = target,
                TargetInstanceType = target.GetType(),
                ValueToWrite = valueToWrite
            }));
        }
    }
</pre>
<p>
This works. Ok, but what I don&#8217;t like about this solution is that I expose the concrete HandlerContext class to the spec. Test isolation is broken here. Besides I have to be very carefully with my implementation of Equals in this case, although it might only be needed in the specification.
</p>
<p><strong>Take 2: Introduce a factory</strong></p>
<p>
You can prevent the direct exposure of the specification to the concrete HandlerContext by introducing a factory which abstacts the creation of the HandlerContext class away.
</p>
<pre class="brush: csharp">
	public class ExpressionBasedWriter&lt;Target,PropertyType&gt; : IWriteStrategy&lt;PropertyType&gt;
	{
		private readonly IExpressionHandler expressionHandler;
		private readonly IHandlerContextFactory handleContextFactory;
		private readonly MemberExpression memberExpression;

		public ExpressionBasedWriter(
			Expression&lt;Func&gt; memberSelector,
			IExpressionHandler expressionHandler,
			IHandlerContextFactory handleContextFactory)
		{
			this.memberExpression = (MemberExpression) memberSelector.Body;
			this.expressionHandler = expressionHandler;
			this.handleContextFactory = handleContextFactory;
		}

		public void WriteTo(Target instance, object value)
		{
			var context = handleContextFactory.CreateContext(memberExpression, instance, value);
			expressionHandler.Handle(context);
		}
	}

	[Concern(typeof (ExpressionBasedWriter&lt;,&gt;))]
	public class When_something_is_about_to_be_written :
		InstanceContextSpecification&lt;IWriteStrateg&lt;TestDto1&gt;&gt;
	{
		private IExpressionHandler expressionHandler;
		private IHandlerContext handlerContext;
		private IHandlerContextFactory handlerContextFactory;
		private TestDto1 target;
		private Expression&lt;Func&gt; targetExpression;
		private string valueToWrite;

		protected override void EstablishContext()
		{
			targetExpression =  x =&gt; x.StringProperty;
			expressionHandler = Dependency();
			handlerContextFactory = Dependency();
			handlerContext = Dependency();

			target = new TestDto1();
			valueToWrite = &quot;uninteresting value&quot;;

			handlerContextFactory.WhenToldTo(x =&gt; x.CreateContext((MemberExpression)targetExpression.Body, target, valueToWrite)).Return(handlerContext);
		}

		protected override IWriteStrategy CreateSut()
		{
			return new ExpressionBasedWriter(targetExpression, expressionHandler, handlerContextFactory);
		}

		protected override void Because()
		{
			Sut.WriteTo(target, valueToWrite);
		}

		[Observation]
		public void should_call_the_context_handler_factory_in_order_to_create_a_context()
		{
			handlerContextFactory.WasToldTo(x =&gt; x.CreateContext((MemberExpression)targetExpression.Body, target, valueToWrite));
		}

		[Observation]
		public void should_call_the_expression_handler_in_order_to_handle_the_created_context()
		{
			expressionHandler.WasToldTo(x =&gt; x.Handle(handlerContext));
		}
	}
</pre>
<p>
Again, this works too. But is that really a path one should go? Introducing an additional factory + interface everytime one encounters an indirect output? Besides that, did you notice how the specification kind of degraded? So much additional noise now in there. This one causes me actually more pain than Take 1, which takes me to &#8230;
</p>
<p><strong>Take 3: A neat Rhino.Mocks feature</strong></p>
<p>
Leave the code from Take 1 as it is. Here&#8217;s how you can write the specification, without exposing it to the concrete HandlerContext class and without causing to much noise in the specification itself.
</p>
<pre class="brush: csharp">
    [Concern(typeof(ExpressionBasedWriter&lt;,&gt;))]
    public class When_something_is_about_to_be_written : InstanceContextSpecification&lt;IWriteStrategy&lt;TestDto1&gt;&gt;
    {
        private IExpressionHandler expressionHandler;
        Expression&lt;Func&gt; targetExpression;
        private TestDto1 target;
        private string valueToWrite;

        protected override void EstablishContext()
        {
            targetExpression = x =&gt; x.StringProperty;
            expressionHandler = Dependency();
            target = new TestDto1();
            valueToWrite = &quot;uninteresting value&quot;;
        }

        protected override IWriteStrategy CreateSut()
        {
            return new ExpressionBasedWriter(targetExpression, expressionHandler);
        }

        protected override void Because()
        {
            Sut.WriteTo(target, valueToWrite);
        }

        [Observation]
        public void should_form_a_context_and_pass_it_to_the_actual_expression_handler()
        {
            	expressionHandler.WasToldTo(x =&gt; x.Handle(Arg&lt;IHandlerContext&gt;.Matches(matcher =&gt;
                       matcher.MemberSelector == targetExpression.Body &amp;&amp;
                       matcher.TargetInstance == target &amp;&amp;
                       matcher.TargetInstanceType == target.GetType() &amp;&amp;
                       matcher.ValueToWrite.Equals(valueToWrite))));
        }
    }
</pre>
<p>
The interesting stuff happens around the generic Arg class. You can use it to specify a callback with which the indirect output can be verified.
</p>
<p><strong>Conclusion</strong></p>
<p>
In the past I mostly did what I demonstrated with Take 1 when I encountered a situation where I needed to verify indirect outputs. Introducing a factory for this was never really an option for me. I don&#8217;t see a real benefit there. The generic argument matching capabilities of Rhino.Mocks really close a gap for me and they&#8217;re what I&#8217;m going to use for solving similar situations from now on. </p>
<p> I hope I&#8217;m not the only kid on the street who didn&#8217;t know that this feature exists . . . </p>
]]></content:encoded>
			<wfw:commentRss>http://www.bjoernrochel.de/2009/01/30/verifying-indirect-outputs-with-rhinomocks-in-xunitbddextensions/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>AutoMocking in xUnit.BDDExtensions</title>
		<link>http://www.bjoernrochel.de/2009/01/26/automocking-in-xunitbddextensions/</link>
		<comments>http://www.bjoernrochel.de/2009/01/26/automocking-in-xunitbddextensions/#comments</comments>
		<pubDate>Mon, 26 Jan 2009 14:33:59 +0000</pubDate>
		<dc:creator>BjRo</dc:creator>
				<category><![CDATA[BDD]]></category>
		<category><![CDATA[xUnit]]></category>
		<category><![CDATA[xUnit.BDDExtensions]]></category>

		<guid isPermaLink="false">http://www.bjoernrochel.de/?p=248</guid>
		<description><![CDATA[
	public class when_an_automatically_resolved_instance_with_a_single_dependency_is_used_in_a_fixture :
		InstanceContextSpecification&#60;ClassWithSingleDependency&#62;
	{
		private object actualResult;
		private IDependency dependency;
		private object expectedResult;

		protected override void EstablishContext()
		{
			expectedResult = new object();
			dependency = AutoDependency&#60;IDependency&#62;();
			dependency.WhenToldTo(x =&#62; x.Invoke()).Return(expectedResult);
		}

		protected override void Because()
		{
			actualResult = Sut.Invoke();
		}

		[Observation]
		public void should_be_able_to_verify_calls_made_to_the_dependency()
		{
			dependency.WasToldTo(x =&#62; x.Invoke());
		}

		[Observation]
		public void should_execute_the_configured_behavior_on_the_dependency()
		{
			actualResult.ShouldBeEqualTo(expectedResult);
		}
	}


This little feature was added to the trunk today. Yes, no CreateSut() call. You can omit it for most of the simple scenarios. You can [...]]]></description>
			<content:encoded><![CDATA[<pre class="brush: csharp">
	public class when_an_automatically_resolved_instance_with_a_single_dependency_is_used_in_a_fixture :
		InstanceContextSpecification&lt;ClassWithSingleDependency&gt;
	{
		private object actualResult;
		private IDependency dependency;
		private object expectedResult;

		protected override void EstablishContext()
		{
			expectedResult = new object();
			dependency = AutoDependency&lt;IDependency&gt;();
			dependency.WhenToldTo(x =&gt; x.Invoke()).Return(expectedResult);
		}

		protected override void Because()
		{
			actualResult = Sut.Invoke();
		}

		[Observation]
		public void should_be_able_to_verify_calls_made_to_the_dependency()
		{
			dependency.WasToldTo(x =&gt; x.Invoke());
		}

		[Observation]
		public void should_execute_the_configured_behavior_on_the_dependency()
		{
			actualResult.ShouldBeEqualTo(expectedResult);
		}
	}
</pre>
<p />
This little feature was added to the trunk today. Yes, no CreateSut() call. You can omit it for most of the simple scenarios. You can still override it, if you need/have to. It uses the AutoMocking capabilities of StructureMap internally. </p>
<p>I&#8217;m going to merge the different involved assemblies to a single assembly soon in order to make deployment a bit easier . . . </p>
]]></content:encoded>
			<wfw:commentRss>http://www.bjoernrochel.de/2009/01/26/automocking-in-xunitbddextensions/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Using Rake to automate .NET builds</title>
		<link>http://www.bjoernrochel.de/2009/01/19/using-rake-to-automate-net-builds/</link>
		<comments>http://www.bjoernrochel.de/2009/01/19/using-rake-to-automate-net-builds/#comments</comments>
		<pubDate>Mon, 19 Jan 2009 17:12:05 +0000</pubDate>
		<dc:creator>BjRo</dc:creator>
				<category><![CDATA[Rake]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[xUnit]]></category>

		<guid isPermaLink="false">http://www.bjoernrochel.de/?p=208</guid>
		<description><![CDATA[Today I started writing my first build scripts in Ruby for a .NET project using Rake. This is what I came up with.

require &#039;rake/clean&#039;

EXTERNALS_DIR = File.expand_path(&#039;../Externals&#039;)
BUILD_DIR = File.expand_path(&#039;../Bin&#039;)
SOURCE_DIR = File.expand_path(&#039;../Source&#039;)

CLEAN.include(FileList[File.join(BUILD_DIR, &#039;*&#039;)])

desc &#34;Compiles the gemini sources&#34;
task :build do
  gemini_solution =  File.join(SOURCE_DIR, &#039;Gemini.sln&#039;)
  sh &#34;msbuild /property:WarningLevel=4;OutDir=#{BUILD_DIR}/  #{gemini_solution}&#34;
end

desc &#34;Runs all the tests on the [...]]]></description>
			<content:encoded><![CDATA[<p>Today I started writing my first build scripts in Ruby for a .NET project using Rake. This is what I came up with.</p>
<pre class="brush: ruby">
require &#039;rake/clean&#039;

EXTERNALS_DIR = File.expand_path(&#039;../Externals&#039;)
BUILD_DIR = File.expand_path(&#039;../Bin&#039;)
SOURCE_DIR = File.expand_path(&#039;../Source&#039;)

CLEAN.include(FileList[File.join(BUILD_DIR, &#039;*&#039;)])

desc &quot;Compiles the gemini sources&quot;
task :build do
  gemini_solution =  File.join(SOURCE_DIR, &#039;Gemini.sln&#039;)
  sh &quot;msbuild /property:WarningLevel=4;OutDir=#{BUILD_DIR}/  #{gemini_solution}&quot;
end

desc &quot;Runs all the tests on the gemini code&quot;
task :test do
  assemblies = all_spec_assemblies()
  xunit_console = File.join(EXTERNALS_DIR, &quot;xUnit/xunit.console.exe&quot;)

  assemblies.each do |assembly|
    sh &quot;#{xunit_console} #{assembly} /html #{assembly +&#039;.UnitTests.html&#039;}&quot;
  end
end

task :default =&gt; [:clean, :build, :test]

def all_spec_assemblies()
  file_mask = File.join(BUILD_DIR, &#039;*Specs.dll&#039;)
  FileList[file_mask]
end
</pre>
<p>I think this code demonstrates the qualities of Ruby as a scripting language and Rake as a build tool really well. It&#8217;s very descriptive and even more important it doesn&#8217;t have all the xml-slash-what-the-hell-is-going-on-here-noise around it. I know it&#8217;s a very simple solution, but I consider it a good start. Let&#8217;s look a bit more detailed at the parts of the script.</p>
<p />
<pre class="brush: ruby">
EXTERNALS_DIR = File.expand_path(&#039;../Externals&#039;)
BUILD_DIR = File.expand_path(&#039;../Bin&#039;)
SOURCE_DIR = File.expand_path(&#039;../Source&#039;)
</pre>
<p>This part defines some directory constants that are used in the script. The rakefile is currently run from the directory &#8216;Build&#8217; which is on the same level as &#8216;Externals&#8217;, &#8216;Bin&#8217; and &#8216;Source&#8217;. Relative paths are expanded to absolute paths here.</p>
<pre class="brush: ruby">
CLEAN.include(FileList[File.join(BUILD_DIR, &#039;*&#039;)])
</pre>
<p>This tiny little code piece modifies the built-in :clean task and adds all files under the BUILD_DIR to it.<br />
Running &#8216;rake clean&#8217; on the console will now delete all files from our build directory.</p>
<pre class="brush: ruby">
desc &quot;Compiles the gemini sources&quot;
task :build do
  gemini_solution =  File.join(SOURCE_DIR, &#039;Gemini.sln&#039;)
  sh &quot;msbuild /property:WarningLevel=4;OutDir=#{BUILD_DIR}/  #{gemini_solution}&quot;
end
</pre>
<p>This is the first task I&#8217;ve actually written on my own. It&#8217;s only a very small wrapper around msbuild that builds the solution file. </p>
<pre class="brush: ruby">
desc &quot;Runs all the tests on the gemini code&quot;
task :test do
  assemblies = all_spec_assemblies()
  xunit_console = File.join(EXTERNALS_DIR, &quot;xUnit/xunit.console.exe&quot;)

  assemblies.each do |assembly|
    sh &quot;#{xunit_console} #{assembly} /html #{assembly +&#039;.UnitTests.html&#039;}&quot;
  end
end

def all_spec_assemblies()
  file_mask = File.join(BUILD_DIR, &#039;*Specs.dll&#039;)
  FileList[file_mask]
end
</pre>
<p>That little code is a small wrapper around xUnit.net which invokes the xunit.console.exe for each file<br />
it finds in the build directory that ends with &#8216;Spec.dll&#8217;. These are the assemblies which contain the BDD-style tests in our project. </p>
<pre class="brush: ruby">
task :default =&gt; [:clean, :build, :test]
</pre>
<p>This last piece defines the :default build task. That&#8217;s the task which is run when you don&#8217;t specify a task directly when running rake from console. This will run all tasks in the order specified from left to right.</p>
<p><b>Conclusion</b></p>
<p>The Rake build engine rocks !!! Its really simple and descriptive API is fun and Rake doesn&#8217;t create a lot of ceremony around build scripts (Only around 30 lines of code in my current script).  However, you should be aware of one thing: Coming from a language with a lot of IDE support (like C# in my case) to Ruby might not be as easy as it sounds. It took me quite a while to make the transition from Intellisense and Resharper to using IRB and reading RDoc in order to explore new APIs . . .  </p>
]]></content:encoded>
			<wfw:commentRss>http://www.bjoernrochel.de/2009/01/19/using-rake-to-automate-net-builds/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>A new syntax for xUnit.BDDExtensions ???</title>
		<link>http://www.bjoernrochel.de/2008/11/27/a-new-syntax-for-xunitbddextensions/</link>
		<comments>http://www.bjoernrochel.de/2008/11/27/a-new-syntax-for-xunitbddextensions/#comments</comments>
		<pubDate>Thu, 27 Nov 2008 13:21:51 +0000</pubDate>
		<dc:creator>BjRo</dc:creator>
				<category><![CDATA[BDD]]></category>
		<category><![CDATA[xUnit]]></category>
		<category><![CDATA[xUnit.BDDExtensions]]></category>

		<guid isPermaLink="false">http://www.bjoernrochel.de/2008/11/27/a-new-syntax-for-xunitbddextensions/</guid>
		<description><![CDATA[I&#8217;ve been doing BDD with the &#8220;context/specificationt&#8221;- style for about 4 months now.  Examples for this style are MSpec, NSpec or my little framework called xUnit.BDDExtensions.
What bothers me lately is that this style mixes context and behavior under test into one fixture class name, which can be extremely long because of that.  An [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been doing BDD with the &#8220;<a href="http://www.lostechies.com/blogs/colinjack/archive/2008/11/19/context-specification-available-frameworks-bdd.aspx" target="_blank">context/specification</a>t&#8221;- style for about 4 months now.  Examples for this style are <a href="http://codebetter.com/blogs/aaron.jensen/archive/2008/09/02/mspec-v0-2.aspx" target="_blank">MSpec</a>, <a href="http://nspec.tigris.org/" target="_blank">NSpec</a> or my little framework called <a href="http://code.google.com/p/xunitbddextensions/" target="_blank">xUnit.BDDExtensions</a>.</p>
<p>What bothers me lately is that this style mixes context and behavior under test into one fixture class name, which can be extremely long because of that.  An example to clarify what I mean:</p>
<pre class="brush: csharp"> public class When_adding_a_contact_to_a_user_with_no_existing_contacts { }
 </pre>
<p>&#8220;Adding a contact&#8221; is the observed behavior in the context of &#8220;no existing contacts&#8221;. I believe<br />
this should be more obvious, which made me thinking of how a syntax for this could look like.</p>
<p>Having said that, here is what I came up with. It&#8217;s heavily inspired by MSpec and <a href="http://dannorth.net/2007/06/introducing-rbehave" target="_blank">RBehave</a>.</p>
<pre class="brush: csharp">
[SpecificationFor(typeof(PatientService))]
public class A_patient_with_a_missing_first_name_is_not_allowed_to_be_persisted
{
      Given a_patient_with_a_missing_first_name = () =&gt;
      {
      };

      When trying_to_save_the_patient = () =&gt;
      {
      };

      It should_not_persist_the_supplied_patient = () =&gt;
      {
      };

      It should_return_a_report_indicating_that_the_patients_first_name_is_required = () =&gt;
      {
      };
}
</pre>
<p>A generated report for this code might look like this: </p>
<p><strong><span style="underline;">Specifications for &#8220;PatientService&#8221;</span></strong></p>
<ul>
<li><strong>A patient with a missing first name is not allowed to be persisted</strong>
<ul>
<li><strong>Given a patient transfer object with a missing first name</strong></li>
<li><strong>when trying to save the patient</strong>
<ul>
<li><strong>it should not persist the supplied patient</strong></li>
<li><strong>it should return a report indicating that the patients first name is required<br />
</strong></li>
</ul>
</li>
</ul>
</li>
</ul>
<p>I&#8217;m still not 100% happy with this, because there is some sort of duplication between the fixture name and the &#8220;givens&#8221; (at least in the shown example), but with this approach you</p>
<ol>
<li>are able to separate context and behavior in a clean way,</li>
<li>can describe the context very fine grained (by having multiple &#8220;givens&#8221;)</li>
<li>and besides that it looks cool <img src='http://www.bjoernrochel.de/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> </li>
</ol>
<p>I would like to hear opinions on that. Is this something worth implementing / adding to xUnit.BDDExtensions?<br />
Or am I off the track with this?</p>
]]></content:encoded>
			<wfw:commentRss>http://www.bjoernrochel.de/2008/11/27/a-new-syntax-for-xunitbddextensions/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
		<item>
		<title>Introducing xUnit.BDDExtensions</title>
		<link>http://www.bjoernrochel.de/2008/10/04/introducing-xunitbddextensions/</link>
		<comments>http://www.bjoernrochel.de/2008/10/04/introducing-xunitbddextensions/#comments</comments>
		<pubDate>Sat, 04 Oct 2008 11:28:31 +0000</pubDate>
		<dc:creator>BjRo</dc:creator>
				<category><![CDATA[BDD]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[xUnit]]></category>
		<category><![CDATA[xUnit.BDDExtensions]]></category>

		<guid isPermaLink="false">http://www.bjoernrochel.de/?p=143</guid>
		<description><![CDATA[
xUnit.BDDExtensions is a little framework build on top of xUnit which enables a BDD style of testing with xUnit.
Besides an emphasis on a &#8220;test case class per fixture&#8221; organization scheme for tests, AAA (Arrange, Act and Assert) style of writing tests and left to right assertions, this framework also provides Rhino.Mocks integration out of the [...]]]></description>
			<content:encoded><![CDATA[<div style="0pt 3em 1.2em 0pt;">
<p>xUnit.BDDExtensions is a little framework build on top of xUnit which enables a BDD style of testing with xUnit.</p>
<p>Besides an emphasis on a &#8220;test case class per fixture&#8221; organization scheme for tests, AAA (Arrange, Act and Assert) style of writing tests and left to right assertions, this framework also provides Rhino.Mocks integration out of the box. By hiding the mechanics of Rhino.Mocks (record and replay model, mocks vs. stubs)  behind the scenes, xUnit.BDDExtensions also helps on writing cleaner, easier to understand and less brittle tests</p>
<p>xUnit.BDDExtensions is based on JP Boodhoos BDD extensions for MBUnit used in his &#8220;Nothing but .NET&#8221; bootcamps.</p>
<p><b>Enough of the talking, let&#8217;s look at some code</b></p>
<p>This is actual code of the xUnit.BDDExtensions trunk. The <em>SpecificationTestCommand </em>class serves as a kind of adapter inside xUnit. It enables the test class to have methods that are run before and after the actual test method is executed.* </p>
<pre class="brush: csharp">
    public class SpecificationTestCommand : BeforeAfterCommand
    {
        public SpecificationTestCommand(
            ITestCommand innerCommand,
            MethodInfo testMethod)
            : base(innerCommand, testMethod)
        {
        }

        public override MethodResult Execute(object testClass)
        {
            var specification = testClass as ITestSpecification;

            try
            {

                if (specification == null)
                {
                    throw new InvalidOperationException(
                          &quot;Instance does not implement ITestSpecification&quot;);
                }

                specification.InitializeSpecification();
                return base.Execute(testClass);
            }
            finally
            {
                if (specification != null)
                {
                    specification.CleanupSpecification();
                }
            }
        }
    }
</pre>
<p>Notice several things: </p>
<ol>
<li>It expects the instance to implement <em>ITestSpecification</em>.</li>
<li>It calls the <em>InitializeSpecification()</em> method on it </li>
<li>Passes the execution to the inner command (in <em>base.Execute(obj)</em>) </li>
<li>and finally cleans up the specification by calling <em>CleanupSpecification() </em>on it.</li>
</ol>
<p>So how can a completely isolated happy path test for this look like?</p>
<pre class="brush: csharp">
 [Concern(typeof(SpecificationTestCommand))]
 public class when_a_specification_test_command_is_executed_on_a_ITestSpecification_implementer :
        concern_for_specification_test_command
    {
        private MethodResult expectedTestResult;
        private ITestCommand innerCommand;
        private MethodInfo methodInfo;
        private MethodResult testResult;
        private ITestSpecification testSpecification;

        protected override void EstablishContext()
        {
            innerCommand = Dependency();
            testSpecification = Dependency();
            methodInfo = GetTestMethodHandle();
            expectedTestResult = CreateMethodResult(methodInfo);

            innerCommand.WhenToldTo(x =&gt; x.Execute(testSpecification))
                     .Return(expectedTestResult);
        }

        protected override SpecificationTestCommand CreateSut()
        {
            return new SpecificationTestCommand(innerCommand, methodInfo);
        }

        protected override void Because()
        {
            testResult = Sut.Execute(testSpecification);
        }

        [Observation]
        public void should_ask_the_test_specification_to_initialize()
        {
            testSpecification.WasToldTo(x =&gt; x.InitializeSpecification());
        }

        [Observation]
        public void should_pass_the_test_specification_to_the_inner_test_command()
        {
            innerCommand.WasToldTo(x =&gt; x.Execute(testSpecification));
        }

        [Observation]
        public void should_return_the_test_result_from_the_inner_test_command()
        {
            testResult.ShouldBeEqualTo(expectedTestResult);
        }

        [Observation]
        public void should_ask_the_test_specification_to_cleanup()
        {
            testSpecification.WasToldTo(x =&gt; x.CleanupSpecification());
        }
    }
</pre>
<p>Notice several things:</p>
<ol>
<li>
       In the <em>EstablishContext()</em> method the whole context for the test is created.  This includes creating most of the dependencies with Rhino.Mocks through <em>Dependeny()</em> and the necessary configuration of their behavior. This is done in order to quickly get from an interaction based style of testing to a state based style of testing. In AAA terms this method implements the Arrange part.
   </li>
<li> The <em>CreateSut()</em> method is executed after <em>EstablishContext()</em> and creates the actual system under test.</li>
<li> The <em>Because()</em> method implements the actual behavior under test. In AAA terms this is the Act part. In the current example this meant executing the test command with an instance implementing the expected interface.</li>
<li> Each method marked with the <em>ObservationAttribute</em> contains a single observation which should be fulfilled when the test has been executed. In AAA terms every Observation is an Assert.</li>
</ol>
<p>That&#8217;s basically it. Pretty straight forward imho. If I managed to make you at least a bit curious about this style of testing, you can grab the source with any Subversion client from:</p>
<p><tt><strong><em>http</em></strong>://xunitbddextensions.googlecode.com/svn/trunk/<br />
</tt></div>
<p>Enjoy coding</p>
<p>*<br />
I know xUnit dropped this behavior in favor of the dispose pattern, but having explicit, non technically named methods for that still seems more natural in the context of BDD to me.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.bjoernrochel.de/2008/10/04/introducing-xunitbddextensions/feed/</wfw:commentRss>
		<slash:comments>10</slash:comments>
		</item>
		<item>
		<title>BDD and xUnit continued</title>
		<link>http://www.bjoernrochel.de/2008/09/16/bdd-and-xunit-continued/</link>
		<comments>http://www.bjoernrochel.de/2008/09/16/bdd-and-xunit-continued/#comments</comments>
		<pubDate>Tue, 16 Sep 2008 18:00:55 +0000</pubDate>
		<dc:creator>BjRo</dc:creator>
				<category><![CDATA[BDD]]></category>
		<category><![CDATA[xUnit]]></category>

		<guid isPermaLink="false">http://www.bjoernrochel.de/?p=123</guid>
		<description><![CDATA[Because of several requests I uploaded the little BDD extension I recently wrote for xunit.  It&#8217;s basically a port of the framework JP Boodhoos currently uses in his famous Nothing but .Net bootcamps (he&#8217;s using MbUnit).
So here it is. Any feedback is appreciated . . .
]]></description>
			<content:encoded><![CDATA[<p>Because of several requests I uploaded the little BDD extension I recently wrote for xunit.  It&#8217;s basically a port of the framework JP Boodhoos currently uses in his famous Nothing but .Net bootcamps (he&#8217;s using MbUnit).</p>
<p>So <a href="http://www.bjoernrochel.de/wp-content/uploads/2008/09/xunitbddextensions.zip">here</a> it is. Any feedback is appreciated . . .</p>
]]></content:encoded>
			<wfw:commentRss>http://www.bjoernrochel.de/2008/09/16/bdd-and-xunit-continued/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>BDD, xUnit and Resharper</title>
		<link>http://www.bjoernrochel.de/2008/09/02/bdd-xunit-and-resharper/</link>
		<comments>http://www.bjoernrochel.de/2008/09/02/bdd-xunit-and-resharper/#comments</comments>
		<pubDate>Tue, 02 Sep 2008 16:01:19 +0000</pubDate>
		<dc:creator>BjRo</dc:creator>
				<category><![CDATA[BDD]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[xUnit]]></category>
		<category><![CDATA[Resharper]]></category>

		<guid isPermaLink="false">http://www.bjoernrochel.de/?p=111</guid>
		<description><![CDATA[Yesterday was an interesting evening. I tried to pinpoint the problem between the little BDD framework I used and the Resharper addin for xUnit.
A short description of my problem
I&#8217;m using a test-case-class-per-fixture organization and the template method pattern for writing tests in the AAA scheme. Besides that I use a specialized FactAttribute in order to [...]]]></description>
			<content:encoded><![CDATA[<p>Yesterday was an interesting evening. I tried to pinpoint the problem between the little BDD framework I used and the Resharper addin for xUnit.</p>
<p><strong>A short description of my problem</strong></p>
<p>I&#8217;m using a test-case-class-per-fixture organization and the template method pattern for writing tests in the AAA scheme. Besides that I use a specialized <em>FactAttribute </em>in order to invoke my AAA &#8211; hook methods in the correct order. All of this is residing in a separate assembly.</p>
<p>When I use the build-in FactAttribute to mark my tests alll tests are discovered by the Resharper&#8217;s TestExplorer, but when I&#8217;m using my own marker attributes nothing is discovered.</p>
<p><strong>What seems to be the problem </strong></p>
<p>It took me some time to find out what was actually going on. I&#8217;ve never debugged a Resharper-Plugin before.  <a href="http://www.jetbrains.net/confluence/display/ReSharper/Building,+running+and+debugging+plugin" target="_blank">This</a> helped a lot. It was an interesting experience, though. Didn&#8217;t knew that there is so much going on behind the scenes. This is what I found out:</p>
<ul>
<li>The XUnitTestProvider class is responsible for discovering tests.</li>
<li> It skips all assemblies which don&#8217;t reference xunit directly.</li>
</ul>
<p>Hm, I had a reference to xunit in my test library project settings. However I was not referencing xUnit stuff from my code directly (Own FactAttribute and  xunitext35 extension methods for assertions). That&#8217;s when it hit me:</p>
<p>My problem was probably caused by a compiler optimization. It seems that all unused assembly references are removed when building the test assembly. A look into reflector supported my thesis. So my test assembly has no direct reference to the xunit.dll, only an indirect one through the BDD framework.</p>
<p><strong>Patching this is quite easy</strong></p>
<p>This is the original method:</p>
<pre class="brush: csharp">
static bool IsTestAssembly(IMetadataAssembly assembly)
{
        foreach (AssemblyReference reference in assembly.ReferencedAssembliesNames)
               if (reference.AssemblyName.Name.ToLowerInvariant() == &quot;xunit&quot;)
                     return true;

        return false;
}
</pre>
<p>When changing this a bit to this, everything runs as expected. </p>
<pre class="brush: csharp">
static bool IsTestAssembly(IMetadataAssembly assembly)
{
        foreach (AssemblyReference reference in assembly.ReferencedAssembliesNames)
        {
              string assemblyName = reference.AssemblyName.Name.ToLowerInvariant();

              if (assemblyName.StartsWith(&quot;xunit&quot;))
                   return true;
       }

       return false;
}
</pre>
<p>All tests are discovered and I&#8217;m quite happy that I can use BDD, XUnit and Resharper in combination <img src='http://www.bjoernrochel.de/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<p>One thing to be aware of: In order to get the tests not only discovered but also executed in Resharper you&#8217;ll have make sure that your test project and the Resharper addin are both using the same, exact version of xUnit. I stumbled over this after I recompiled and installed my patch on my machine. Resharper is not able to execute the tests in case of a version mismatch.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.bjoernrochel.de/2008/09/02/bdd-xunit-and-resharper/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>BDD with Xunit</title>
		<link>http://www.bjoernrochel.de/2008/08/28/bdd-with-xunit/</link>
		<comments>http://www.bjoernrochel.de/2008/08/28/bdd-with-xunit/#comments</comments>
		<pubDate>Thu, 28 Aug 2008 09:53:06 +0000</pubDate>
		<dc:creator>BjRo</dc:creator>
				<category><![CDATA[BDD]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[xUnit]]></category>

		<guid isPermaLink="false">http://www.bjoernrochel.de/?p=100</guid>
		<description><![CDATA[My current tool of interest is XUnit. For those of you who haven&#8217;t heard of it it&#8217;s a relatively new unit testing framework from Brad Wilson and the original author of NUnit 2.0, James Newkirk. You can find it here.
Some of the things I really like about it:

It has a set of .NET 3.0 Extension [...]]]></description>
			<content:encoded><![CDATA[<p>My current tool of interest is XUnit. For those of you who haven&#8217;t heard of it it&#8217;s a relatively new unit testing framework from Brad Wilson and the original author of NUnit 2.0, James Newkirk. You can find it <a href="http://www.codeplex.com/xunit" target="_blank">here</a>.</p>
<p>Some of the things I really like about it:</p>
<ul>
<li>It has a set of .NET 3.0 Extension methods, which can be used instead of classic assertions (f.e.: &#8220;Foo&#8221;.ShouldNotBeNull() )</li>
<li>It runs every every test on a separated instance.</li>
<li>It uses the constructor of the test class and the Dispose-pattern for fixture initialization and release of resources after a test.</li>
<li>It&#8217;s relatively easy to extend XUnit.</li>
</ul>
<p>Because of curiosity and my current affection with BDD I decided to port the BDDExtension stuff fromÂ  JP Boodhoo to XUnit. So here we go:</p>
<p><strong>Marking specifications with concerns<br />
</strong></p>
<p>All specifications for a particular type are marked with the <em>ConcernAttribute</em>.Â  This is only a marker attribute by which a tool like <em>bddunit </em>is able to correlate specifications and their related type.</p>
<pre class="brush: csharp">
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)]
public class ConcernAttribute : TraitAttribute
{
        private readonly Type _Type;

        public ConcernAttribute(Type type) : base(&quot;Concern&quot;, type.FullName)
        {
                _Type = type;
        }

        public Type Type
        {
                get { return _Type; }
        }
}
</pre>
<p>The <em>ConcernAttibute </em>extends the <em>TraitAttribute </em>which is described in the documentation as &#8220;an Attribute used to decorate a test method with arbitrary name/value pairs (&#8220;traits&#8221;).&#8221; I changed the <em>AttributeTarget </em>from method to class in order to suit my needs.</p>
<p><strong>Changing the way the test is executed</strong></p>
<p>JP&#8217;s original code relied on the SetUp and Teaddown handlers of NUnit / MBUnit which are execute before and after each test method in the same class. Since XUnit doesn&#8217;t have that feature any more we&#8217;ll have to extend it a bit.</p>
<p>The main extension point for how a test is executed is the <em>FactAttibute </em>used to mark a method as a test. You can extend it and return a different <em>ITestCommand </em>which is then used to execute the test.</p>
<pre class="brush: csharp">
public class ObservationAttribute : FactAttribute
{
        protected override IEnumerable EnumerateTestCommands(MethodInfo method)
        {
                var testCommand = base.EnumerateTestCommands(method).First();
                yield return new SpecificationTestCommand(testCommand, method);
        }
}
</pre>
<p>Do you wonder why the method returns an <em>IEnumerable&lt;ITestCommand&gt;</em>? This is done in order to support something like row tests in MBUnit. The XUnit framework basically enables you to run a test several times. For me this isn&#8217;t interesting so I just grabbed the first <em>ITestCommand </em>from it and wrapped it with my own implementation, which looks like this:</p>
<pre class="brush: csharp">
public class SpecificationTestCommand : BeforeAfterCommand
{
        public SpecificationTestCommand(
                ITestCommand innerCommand,
                MethodInfo testMethod)
                : base(innerCommand, testMethod)
        {
        }

        public override MethodResult Execute(object testClass)
        {
                var specification = testClass as IContextSpecification;

                if (specification == null)
                {
                       throw new InvalidOperationException(
                          &quot;Instance does not implement IContextSpecification&quot;);
                }

                try
                {
                        specification.EstablishContext();
                        specification.Because();
                        return base.Execute(testClass);
                }
                catch(AssertException)
                {
                        throw;
                }
                catch (Exception exception)
                {
                        ExceptionUtility.RethrowWithNoStackTraceLoss(exception.InnerException);
                }

                return null;
        }
}
</pre>
<p>The code requires the test class to implement the <em>IContextSpecification </em>interface in order to invoke the <em>EstablishContext()</em> and <em>Because()</em> methods for doing AAA based tests. (Do you miss AfterEachSpec? One moment please <img src='http://www.bjoernrochel.de/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> ) For every interface there is a base class which is in my case the <em>ContextSpecification</em> class.</p>
<pre class="brush: csharp">
public abstract class ContextSpecification : IContextSpecification, IDisposable
{
      protected abstract void Because();

      protected abstract void EstablishContext();

      protected virtual void AfterEachSpec()
      {
      }

      #region IContextSpecification Members

      void IContextSpecification.Because()
      {
            Because();
      }

      void IContextSpecification.EstablishContext()
      {
            EstablishContext();
      }

      #endregion

      #region IDisposable Members

      public void Dispose()
      {
            AfterEachSpec();
      }

      #endregion
}
</pre>
<p>Notice some things.<em> AfterEachSpec()</em> is called from <em>Dispose()</em>, That&#8217;s why I didn&#8217;t need to include it into the <em>IContextSpecification</em> interface. That interface is implemented explicitly in order to allow the hooks to have different modifiers (protected).</p>
<p><strong>A first test</strong></p>
<p>There&#8217;s always an interesting moment when you first run your little experiment. Here we go:</p>
<pre class="brush: csharp">
[Concern(typeof(Factory))]
public class When_creating_product_with_a_valid_name : ContextSpecification
{
      private Factory _Factory;
      private Product _CreatedProduct;

      protected override void EstablishContext()
      {
            _Factory = new Factory();
      }

      protected override void Because()
      {
            _CreatedProduct = _Factory.Create(&quot;Foo&quot;);
      }

      [Observation]
      public void The_product_should_contain_the_correct_name()
      {
            _CreatedProduct.Name.ShouldEqual(&quot;Foo&quot;);
      }

      [Observation]
      public void The_product_should_contain_the_correct_vendor_name()
      {
            _CreatedProduct.VendorName.ShouldEqual(&quot;FooVendor&quot;);
      }
}
</pre>
<p>And the result from TestDriven.NET is:</p>
<p>&#8212;&#8212; Test started: Assembly: Xunit.BddExtensions.Samples.dll &#8212;&#8212;<br />
2 passed, 0 failed, 0 skipped, took 0,92 seconds.</p>
<p><strong>Conclusions</strong></p>
<p>It&#8217;s in fact very easy to extend XUnit. I like the tool even more after doing this little research. The shown code runs smoothly with TestDriven.NET. However the Resharper &#8211; TestRunner seems to have problems with it (TestExplorer stays blank).</p>
<p>I&#8217;ll play with that approach in the next few weeks and will blog about my experience with both XUnit and BDD. So if you&#8217;re interested in more stay tuned . . .</p>
<p>P.s.: If you&#8217;re interested in the code, just drop me a line . . .</p>
]]></content:encoded>
			<wfw:commentRss>http://www.bjoernrochel.de/2008/08/28/bdd-with-xunit/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>
