<?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/tag/xunit/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>Testing F# code with xUnit.net (on .NET 4.0)</title>
		<link>http://www.bjoernrochel.de/2010/04/19/testing-f-code-with-xunit-net-on-net-4-0/</link>
		<comments>http://www.bjoernrochel.de/2010/04/19/testing-f-code-with-xunit-net-on-net-4-0/#comments</comments>
		<pubDate>Mon, 19 Apr 2010 07:48:46 +0000</pubDate>
		<dc:creator>BjRo</dc:creator>
				<category><![CDATA[Testing]]></category>
		<category><![CDATA[F#]]></category>
		<category><![CDATA[xUnit]]></category>

		<guid isPermaLink="false">http://www.bjoernrochel.de/?p=784</guid>
		<description><![CDATA[A lot of my free time currently goes into learning F#. While I had a great time playing around with the F# REPL FSI, I came to the conclusion that using FSI is not my preferred way of a) learning the F# language and b) to develop code. Writing unit tests simply for the purpose [...]]]></description>
			<content:encoded><![CDATA[<p>A lot of my free time currently goes into learning F#. While I had a great time playing around with the F# REPL FSI, I came to the conclusion that using FSI is not my preferred way of a) learning the F# language and b) to develop code. Writing unit tests simply for the purpose of learning and understanding of a language/component/system (aka &quot;Learning tests&quot;) seems to be a better fit, at least for me. So, I sat down in order to see how I can use my beloved xUnit.net for this. As it turns out it&#8217;s not that difficult, but it&#8217;s got some hurdles. </p>
<p><strong>Possible runtime differences</strong> </p>
<p>xUnit.net 1.5 is compiled against the .Net Framework 3.5. If you&#8217;re using F# in combination with the VS2010 RC or RTM (like I do) you&#8217;ve got at least to options to make them work together. </p>
<ol>
<li>Use multi-targeting&#160; and configure the F# projects to compile for the .NET 3.5 runtime (Properties/Application/Target Framework). </li>
<li>Update the app.config files of xunit.console.exe and xunit.gui.exe with a startup section and specify the .NET framework 4.0 version as supported.
<pre class="brush: xml">

     &lt;startup&gt;
    	&lt;supportedRuntime version=&quot;v4.0.30128&quot; safemode=&quot;true&quot;/&gt; &lt;!-- VS2010 RC --&gt;
    	&lt;supportedRuntime version=&quot;v4.0.30319&quot; safemode=&quot;true&quot;/&gt; &lt;!-- VS2010 RTM --&gt;
     &lt;/startup&gt;
</pre>
</li>
</ol>
<p><strong>Pay attention to your parentheses</strong> </p>
<p>My choice was to update the xUnit.net configurations. After the update of the configuration files my assembly was loaded, however the test runner failed to detect my unit tests. As it turns out the open parentheses after a test function play an important role.</p>
<p><pre class="brush: csharp">
     [&lt;Fact&gt;]
     let After_converting_a_valid_data_row_the_title_should_have_been_extracted = //This compiles, but the test doesn&#039;t show up in the test runner.
        let row = convertDataRow &quot;Test, 1234&quot;
        Assert.Equal(fst(row), &quot;Test&quot;)

     [&lt;Fact&gt;]
     let After_converting_a_valid_data_row_the_title_should_have_been_extracted() = //This will work fine
        let row = convertDataRow &quot;Test, 1234&quot;
        Assert.Equal(fst(row), &quot;Test&quot;)
  </pre>
</p>
<p>My first reaction was: WTF? But after reading some more chapters of &quot;Real world functional programming&quot; and a discussion at our local F# book club the behavior makes sense to me. My current understanding is that omitting the parentheses results in a different method signature. You can easily spot this in FSI. The first one is <em>val After_converting_a_valid_data_row_the_title_should_have_been_extracted : unit</em> while the second one results in a <em>val After_converting_a_valid_data_row_the_title_should_have_been_extracted : unit -&gt; unit</em>. What you can see here is that the first function signature doesn&#8217;t have a parameter while the second has a parameter of the type unit. One interesting difference between F# and C# is that the F# equivalent to C#&#8217;s void is an actual type called unit. The fun part is that () is it&#8217;s only value. Parentheses play a completely different role here <img src='http://www.bjoernrochel.de/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' />  The xUnit test runner looks for methods with one unit parameter and a return type of unit. That&#8217;s why you need the parentheses. </p>
<p><strong>Testing exceptions with xUnit.Net</strong> </p>
<p>One little subtlety I came across when testing exceptions is that you have to explicitly &quot;ignore&quot; the return value when you&#8217;re using Assert.Throws and pass in a method which doesn&#8217;t return unit. Feels a bit strange at first, but explainable. Again a signature mismatch. Assert.Throws expects a method with a unit -&gt; unit signature. You have to do this in order to please the compiler. (If there&#8217;s a better way for this, please let me know) </p>
<p><pre class="brush: csharp">
    [&lt;Fact&gt;]
    let Trying_to_convert_an_invalid_format_throws() =
        Assert.Throws(fun () -&gt; convertDataRow &quot;FuBar&quot; |&gt; ignore)
  </pre>
</p>
<p>The ignore function simply throws away any value it receives, returns a unit and makes the F# compiler happy.</p>
<p><strong>Conclusion</strong> </p>
<p>I hope you saw in this post that testing F# with xUnit.net is actually pretty easy. It&#8217;s also a wonderful case for language interop on top of the CLR. Go see it for yourself <img src='http://www.bjoernrochel.de/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.bjoernrochel.de/2010/04/19/testing-f-code-with-xunit-net-on-net-4-0/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>ILMerge and Rake go xunit.BDDExtensions</title>
		<link>http://www.bjoernrochel.de/2009/01/27/ilmerge-and-rake-go-xunitbddextensions/</link>
		<comments>http://www.bjoernrochel.de/2009/01/27/ilmerge-and-rake-go-xunitbddextensions/#comments</comments>
		<pubDate>Tue, 27 Jan 2009 12:48:54 +0000</pubDate>
		<dc:creator>BjRo</dc:creator>
				<category><![CDATA[Rake]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[xUnit]]></category>
		<category><![CDATA[xUnit.BDDExtensions]]></category>

		<guid isPermaLink="false">http://www.bjoernrochel.de/?p=253</guid>
		<description><![CDATA[Today I added this little piece of code to the trunk of xUnit.BDDExtensions. It&#8217;s a rake task for merging assemblies via the ILMerge tool.


desc &#34;Merges the assemblies&#34;
task :merge do
  mkdir DEPLOY_DIR unless File.exists?(DEPLOY_DIR)
  cp &#34;xunit.dll&#34;.expand_to(:build_dir), &#34;xunit.dll&#34;.expand_to(:deploy_dir)
  cp &#34;Rhino.Mocks.dll&#34;.expand_to(:build_dir), &#34;Rhino.Mocks.dll&#34;.expand_to(:deploy_dir)
  assemblies_to_merge = [&#34;xUnit.BDDExtensions.dll&#34;, &#34;StructureMap.dll&#34;, &#34;StructureMap.AutoMocking.dll&#34;]
  ilmerge &#34;xunit.bddextensions.dll&#34;, assemblies_to_merge
end


Ruby is a fantastic [...]]]></description>
			<content:encoded><![CDATA[<p>Today I added this little piece of code to the trunk of xUnit.BDDExtensions. It&#8217;s a rake task for merging assemblies via the ILMerge tool.
<p />
<pre class="brush: ruby">
desc &quot;Merges the assemblies&quot;
task :merge do
  mkdir DEPLOY_DIR unless File.exists?(DEPLOY_DIR)
  cp &quot;xunit.dll&quot;.expand_to(:build_dir), &quot;xunit.dll&quot;.expand_to(:deploy_dir)
  cp &quot;Rhino.Mocks.dll&quot;.expand_to(:build_dir), &quot;Rhino.Mocks.dll&quot;.expand_to(:deploy_dir)
  assemblies_to_merge = [&quot;xUnit.BDDExtensions.dll&quot;, &quot;StructureMap.dll&quot;, &quot;StructureMap.AutoMocking.dll&quot;]
  ilmerge &quot;xunit.bddextensions.dll&quot;, assemblies_to_merge
end
</pre>
<p>
Ruby is a fantastic language. The more I learn about it the more I actually like it. Let&#8217;s have a look at how this task is implemented. First of all I opened up Ruby&#8217;s string class and added new methods to it (this is called MonkeyPatching, and worth a blog post on its own <img src='http://www.bjoernrochel.de/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> )
</p>
<pre class="brush: ruby">
class String
  def escape
    &quot;\&quot;#{self.to_s}\&quot;&quot;
  end

  def expand_to dir_symbol
    case dir_symbol
      when :build_dir
        path = BUILD_DIR
      when :source_dir
        path = SOURCE_DIR
      when :externals_dir
        path = EXTERNALS_DIR
      when :deploy_dir
        path = DEPLOY_DIR
    end    

    File.join(path, self.to_s)
  end
end
</pre>
<p>
And here is the actual <i>ilmerge</i> &#8211; method. It simply gets the complete path to the ILMerge.exe (not shown here), expands the name to all assemblies that have to be merged and escapes them, before the actual call to ILMerge is issued over the console &#8230;</p>
<p />
<pre class="brush: ruby">
def ilmerge(output_name, assemblies)
  ilmerge = get_tool :ILMerge
  expanded_assemblies = assemblies.map do |x|
    x.expand_to(:build_dir).escape
  end

  sh &quot;#{ilmerge.escape} /out:#{output_name.expand_to(:deploy_dir).escape} #{expanded_assemblies.join(&quot; &quot;)}&quot;
end
</pre>
<p>
Currently 3 assemblies pop out of the Rake build. These are xunit.dll, xunit.bddextensions.dll and Rhino.Mocks.dll. While it&#8217;s technically no problem to merge them into a single assembly (and of course I would love to have it that way) there are two problems currently not solved. The R# runner dynamically loads the xunit.dll to run the tests and StructureMap.AutoMocking.dll dynamically loads Rhino.Mocks.dll. That&#8217;s the reason why I&#8217;m currently not able to merge it.
</p>
<p>Any suggestions how to solve that?</p>
]]></content:encoded>
			<wfw:commentRss>http://www.bjoernrochel.de/2009/01/27/ilmerge-and-rake-go-xunitbddextensions/feed/</wfw:commentRss>
		<slash:comments>1</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>
		<item>
		<title>Ambient transactions and NHibernate</title>
		<link>http://www.bjoernrochel.de/2008/08/22/ambient-transactions-and-nhibernate/</link>
		<comments>http://www.bjoernrochel.de/2008/08/22/ambient-transactions-and-nhibernate/#comments</comments>
		<pubDate>Fri, 22 Aug 2008 15:29:30 +0000</pubDate>
		<dc:creator>BjRo</dc:creator>
				<category><![CDATA[NHibernate]]></category>
		<category><![CDATA[xUnit]]></category>
		<category><![CDATA[Ambient transactions]]></category>

		<guid isPermaLink="false">http://bjro.de/2008/08/22/ambient-transactions-and-nhibernate/</guid>
		<description><![CDATA[About two weeks ago we had some discussions in the german Alt.NET mailing list whether ambient transactions can be used in combination with NHibernate, especially regarding performance implications of such an approach.
Background of that discussion was that my colleague Sergey and I wanted to implement the repository pattern based on Linq 2 NHibernate in a [...]]]></description>
			<content:encoded><![CDATA[<p>About two weeks ago we had some discussions in the german Alt.NET mailing list whether ambient transactions can be used in combination with NHibernate, especially regarding performance implications of such an approach.</p>
<p>Background of that discussion was that my colleague <a href="http://shishkin.org" target="_new">Sergey</a> and I wanted to implement the repository pattern based on Linq 2 NHibernate in a way that exposes NO NHibernate dependency to a surrounding layer. Besides that we didn&#8217;t want to dublicate the UnitOfWork pattern that NHibernate implements internally. Because of that we decided to try out ambient transactions (System.Transactions) as our UnitOfWork.</p>
<p>Sergey has already posted about the design we&#8217;re currently investigating, so I won&#8217;t go into detail about that here. You can read more here:</p>
<ul>
<li><a href="http://sergeyshishkin.spaces.live.com/blog/cns!9F19E53BA9C1D63F!263.entry" target="_new">RepositoryPatter revised</a></li>
<li><a href="http://sergeyshishkin.spaces.live.com/blog/cns!9F19E53BA9C1D63F!265.entry" target="_new">UnitOfWork Pattern revised</a></li>
<li><a href="http://sergeyshishkin.spaces.live.com/blog/cns!9F19E53BA9C1D63F!264.entry" target="_new">Specification Pattern revised</a></li>
</ul>
<p>We started with a simple test comparison between the behavior of NHibernates native ITransactions and an NHibernate using TransactionScope for transactions.Â  What we noticed :</p>
<p><strong>FlushMode.Commit doesn&#8217;t work when using ambient Transactions</strong></p>
<p>The following (xUnit) test fails:</p>
<pre class="brush: csharp">
[Fact]
public void Session_should_be_clean_after_commited_transaction()
{
    using (var tx = new TransactionScope())
    {
          SaveTwoPatients();
          tx.Complete();
    }

        Session.IsDirty().ShouldBeFalse();
}
</pre>
<p>But this can be easily fixed like this:</p>
<pre class="brush: csharp">
[Fact]
public void Session_should_be_clean_after_commited_transaction_Fixed()
{
    using (var tx = new TransactionScope())
    {
        Transaction.Current.TransactionCompleted += (s, e) =&gt;
        {
            if (e.Transaction.TransactionInformation.Status == TransactionStatus.Committed)
            {
                Session.Flush();
                Session.Clear();
            }
        };

        SaveTwoPatients();
        tx.Complete();
    }

    Session.IsDirty().ShouldBeFalse();
}
</pre>
<p><strong>For some reason ambient Transaction are FASTER than NHibernates native counter parts</strong></p>
<p>We have also some testsÂ  that perform a transactional insert a 1000 times. The duration of those tests are quite surprising. Have a look:</p>
<p><a title="NHibernateTransactions" href="http://www.bjoernrochel.de/wp-content/uploads/2008/08/nhibernatetransactions.png"><img src="http://www.bjoernrochel.de/wp-content/uploads/2008/08/nhibernatetransactions.png" alt="NHibernateTransactions" width="80%" height="80%" /></a></p>
<p>This has nothing to do with jitting in the CLR or the order how test are executed. I double checked the durations and ran each test on his own.Â  I didn&#8217;t expect that gap, but I&#8217;m also not a NHibernate pro. Any thoughts?</p>
<p>I&#8217;ll write more about our experiences with that approach soon. Our concept looks good on paper and our first impressions are not disproving either, so stay tuned . . .</p>
]]></content:encoded>
			<wfw:commentRss>http://www.bjoernrochel.de/2008/08/22/ambient-transactions-and-nhibernate/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>
