<?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; Testing</title>
	<atom:link href="http://www.bjoernrochel.de/tag/testing/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>How to: Visual Studio test runner &amp; side by side test code</title>
		<link>http://www.bjoernrochel.de/2009/05/18/how-to-visual-studio-test-runner-side-by-side-test-code/</link>
		<comments>http://www.bjoernrochel.de/2009/05/18/how-to-visual-studio-test-runner-side-by-side-test-code/#comments</comments>
		<pubDate>Mon, 18 May 2009 20:34:49 +0000</pubDate>
		<dc:creator>BjRo</dc:creator>
				<category><![CDATA[MSTest]]></category>
		<category><![CDATA[Testing]]></category>

		<guid isPermaLink="false">http://www.bjoernrochel.de/?p=337</guid>
		<description><![CDATA[After spending a lot of time with xUnit.net I recently had to go back to MSTest for my testing again (because it&#8217;s the de facto standard at my current client which is not negotiable ;-().

Former colleagues of mine will probably laugh about this, because I&#8217;ve had a love-and-hate-relationship with MSTest and especially the VisualStudio runner [...]]]></description>
			<content:encoded><![CDATA[<p>After spending a lot of time with xUnit.net I recently had to go back to MSTest for my testing again (because it&#8217;s the de facto standard at my current client which is not negotiable ;-().
</p>
<p>Former colleagues of mine will probably laugh about this, because I&#8217;ve had a love-and-hate-relationship with MSTest and especially the VisualStudio runner in the past. I won&#8217;t go into details here, but you can read about it <a href="http://www.bjoernrochel.de/tag/mstest/">here</a>. However since I currently have no other option I use what is there. Better writing tests such an environment, than writing no test at all. At least if you ask me.</p>
<p />
This brings me back to the topic of the post. Some prerequisites: I like developing software in a TDD manner and am using Resharper with its &#8216;Generate&#8217; and &#8216;Move To&#8217; features a lot. I like the idea of having test-code side by side with the actual tested code. With this a lot of you&#8217;re daily TDD life becomes at least a bit easier and painless. I see at least two advantages in such an approach:</p>
<ol>
<li>You don&#8217;t have to copy generated classes from the test-assembly to the regular assembly.</li>
<li>You don&#8217;t have to maintain two different folder hierarchies (The one in the code-assembly and the one in the regular assembly) and therefore know exactly where to look for test-code.
</li>
</ol>
<p />
This is one of the things I learned from JP Boodhoo in his NBDN bootcamp,  credit for the general idea goes to him for this. So how can we achieve this in VisualStudio with MSTest? </p>
<p />
DISCLAIMER: The stuff I describe in the rest of the post has to do with modifying the .csproj &#8216;“ msbuild file of a project. If this is a &#8216;no go&#8217; for you, you can probably stop reading here <img src='http://www.bjoernrochel.de/wp-includes/images/smilies/icon_wink.gif' alt=';-)' class='wp-smiley' /> . For the rest here is the list of steps I took in order to make it work:</p>
<p>
<strong>Step 1: Add the ProjectType Guids to your project.</strong></p>
<p />
VisualStudio&#8217;s test explorer scans only projects which are of a certain project type (aka the test project) for tests. VS identifies such a project based on the value of a particular node in the .csproj file, the <em>ProjectTypeGuid</em> node. Simply copy this one from an actual test project to the .csproj of your regular assembly. Another option of course would be to start with a test project from scratch. </p>
<pre class="brush: xml">
&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;Project ToolsVersion=&quot;3.5&quot; DefaultTargets=&quot;Build&quot; xmlns=&quot;http://schemas.microsoft.com/developer/msbuild/2003&quot;&gt;
  &lt;PropertyGroup&gt;
    &lt;Configuration Condition=&quot; &#039;$(Configuration)&#039; == &#039;&#039; &quot;&gt;Debug&lt;/Configuration&gt;
    &lt;Platform Condition=&quot; &#039;$(Platform)&#039; == &#039;&#039; &quot;&gt;AnyCPU&lt;/Platform&gt;
    &lt;ProductVersion&gt;9.0.30729&lt;/ProductVersion&gt;
    &lt;SchemaVersion&gt;2.0&lt;/SchemaVersion&gt;
    &lt;!-- The line below has to be added to regular projects --&gt;
    &lt;ProjectTypeGuids&gt;{3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}&lt;/ProjectTypeGuids&gt;
    &lt;ProjectGuid&gt;{890DA3CA-999A-474E-BA87-05A834CAB7B8}&lt;/ProjectGuid&gt;
    &lt;OutputType&gt;Library&lt;/OutputType&gt;
    &lt;AppDesignerFolder&gt;Properties&lt;/AppDesignerFolder&gt;
    &lt;RootNamespace&gt;SpecReport&lt;/RootNamespace&gt;
    &lt;AssemblyName&gt;SpecReport&lt;/AssemblyName&gt;
    &lt;TargetFrameworkVersion&gt;v3.5&lt;/TargetFrameworkVersion&gt;
    &lt;FileAlignment&gt;512&lt;/FileAlignment&gt;
  &lt;/PropertyGroup&gt;
</pre>
<p><strong>Step 2: Apply conditional compilation for not including the test code when compiling in release mode</strong></p>
<p />
So, the tests sit right next to the tested code, right? We presumable don&#8217;t want our tests to be deployed to production. We can achieve this in MSBuild fairly easy with conditional compilation and wildcards. </p>
<pre class="brush: xml">
  &lt;ItemGroup&gt;
    &lt;!-- The line below skips all files ending with &#039;Spec.cs&#039; when compiling in a mode other than DEBUG --&gt;
    &lt;Compile Condition=&quot;&#039;$(Configuration)&#039; == &#039;Debug&#039;&quot; Include=&quot;**\*Specs.cs&quot; /&gt;
    &lt;Compile Include=&quot;IReportEngine.cs&quot; /&gt;
    &lt;Compile Include=&quot;IReportGenerator.cs&quot; /&gt;
    &lt;Compile Include=&quot;Notification.cs&quot; /&gt;
    &lt;Compile Include=&quot;NotificationCollection.cs&quot; /&gt;
    &lt;Compile Include=&quot;Properties\AssemblyInfo.cs&quot; /&gt;
    &lt;Compile Include=&quot;ReportEngine.cs&quot; /&gt;
    &lt;Compile Include=&quot;ReportEngineArgs.cs&quot; /&gt;
  &lt;/ItemGroup&gt;
</pre>
<p><strong>Step 3: Apply conditional compilation for not deploying the test-related assemblies when compiling in release mode<br />
</strong></p>
<p />
In order to get rid of the test-specific assemblies for production deployment you can also apply conditionals to the assembly references of a project.</p>
<pre class="brush: xml">
&lt;ItemGroup&gt;
&lt;Reference Condition=&quot;&#039;$(Configuration)&#039; == &#039;Debug&#039;&quot; Include=&quot;Microsoft.VisualStudio.QualityTools.UnitTestFramework, Version=9.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL&quot; /&gt;
    &lt;Reference Condition=&quot;&#039;$(Configuration)&#039; == &#039;Debug&#039;&quot; Include=&quot;Rhino.Mocks, Version=3.5.0.1337, Culture=neutral, PublicKeyToken=0b3305902db7183f, processorArchitecture=MSIL&quot;&gt;
      &lt;SpecificVersion&gt;False&lt;/SpecificVersion&gt;
      &lt;HintPath&gt;..\Externals\RhinoMocks35\Rhino.Mocks.dll&lt;/HintPath&gt;
    &lt;/Reference&gt;
    &lt;Reference Include=&quot;System&quot; /&gt;
    &lt;Reference Include=&quot;System.Core&quot;&gt;
      &lt;RequiredTargetFramework&gt;3.5&lt;/RequiredTargetFramework&gt;
    &lt;/Reference&gt;
    &lt;Reference Include=&quot;System.Xml.Linq&quot;&gt;
      &lt;RequiredTargetFramework&gt;3.5&lt;/RequiredTargetFramework&gt;
    &lt;/Reference&gt;
    &lt;Reference Include=&quot;System.Data.DataSetExtensions&quot;&gt;
      &lt;RequiredTargetFramework&gt;3.5&lt;/RequiredTargetFramework&gt;
    &lt;/Reference&gt;
    &lt;Reference Include=&quot;System.Data&quot; /&gt;
    &lt;Reference Include=&quot;System.Xml&quot; /&gt;
  &lt;/ItemGroup&gt;
</pre>
<p>
Et voila: The approach described in this post seams to work fine. At least I&#8217;m not experiencing side effects since I&#8217;ve configured it that way &#8230; </p>
]]></content:encoded>
			<wfw:commentRss>http://www.bjoernrochel.de/2009/05/18/how-to-visual-studio-test-runner-side-by-side-test-code/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Beat the It</title>
		<link>http://www.bjoernrochel.de/2009/02/09/beat-the-it/</link>
		<comments>http://www.bjoernrochel.de/2009/02/09/beat-the-it/#comments</comments>
		<pubDate>Mon, 09 Feb 2009 09:45:55 +0000</pubDate>
		<dc:creator>BjRo</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[C# 3.0]]></category>
		<category><![CDATA[Domain Specific Languages]]></category>
		<category><![CDATA[Testing]]></category>

		<guid isPermaLink="false">http://www.bjoernrochel.de/?p=279</guid>
		<description><![CDATA[. . . or how one could implement the It-Syntax introduced by MSpec. If you don&#8217;t know what the hell I&#8217;m talking about take a look at this code. (I don&#8217;t know if that&#8217;s the current MSpec syntax but I think you&#8217;ll get where I&#8217;d like to take you . . . )

[Description]
public class Transferring_between_from_account_and_to_account
{
 [...]]]></description>
			<content:encoded><![CDATA[<p>. . . or how one could implement the It-Syntax introduced by MSpec. If you don&#8217;t know what the hell I&#8217;m talking about take a look at this code. (I don&#8217;t know if that&#8217;s the current MSpec syntax but I think you&#8217;ll get where I&#8217;d like to take you . . . )</p>
<pre class="brush: csharp">
[Description]
public class Transferring_between_from_account_and_to_account
{
  static Account fromAccount;
  static Account toAccount;

  Context before_each =()=&gt;
  {
    fromAccount = new Account {Balance = 1m};
    toAccount = new Account {Balance = 1m};
  };

  When the_transfer_is_made =()=&gt;
  {
    fromAccount.Transfer(1m, toAccount);
  };

  It should_debit_the_from_account_by_the_amount_transferred =()=&gt;
  {
    fromAccount.Balance.ShouldEqual(0m);
  };

  It should_credit_the_to_account_by_the_amount_transferred =()=&gt;
  {
    toAccount.Balance.ShouldEqual(2m);
  };
}
</pre>
<p>What you&#8217;ll see in this post is part of a spike I did some month ago<a href="http://www.bjoernrochel.de/2008/11/27/a-new-syntax-for-xunitbddextensions/" target="_blank"> while I was considering</a> to move the xUnit.BDDExtensions syntax to something more GWT and MSpec like. I finally decided against that, partially because I realized that there is absolutely no need for a MSpec-Clone; partially because I&#8217;m still not so happy with the implications / side effects of the syntax (nearly everything in you spec needs to become static).</p>
<p>Anyway, <a href="http://blog.jpboodhoo.com/SlightAdditionToJpboodhoobdd.aspx" target="_blank">recently</a> JP Boodhoo introduced the same feature to his Jpboodhoo.bdd codebase. A lot of the comments requested a more detailed description of how he implemented that feature. While I can&#8217;t answer that question, I can talk about how I tackled that problem. So here we go!</p>
<p><strong>Some prerequisites first</strong></p>
<p>If you wonder how such a sweet syntax is possible in C#,  here are some clues: </p>
<ul>
<li>
It uses fields with ommited access modifiers (therefore private fields).
</li>
<li>
It, When, etc. are delegate types.
</li>
<li>
Field-initializers are used to specifiy the delegates inline. (and because Field-Initializers are run before the constructor you can only access static and no instance members here. Thats the sideeffect I mentioned earlier).
</li>
</ul>
<p><strong>A closer look at my spike</strong></p>
<p>The following class is the heart of the spike I implemented. It takes a blank object and uses reflection to build an ISpecHandler instance which is ultimately used to run the specification.</p>
<pre class="brush: csharp">
    public class SpecFactory : ISpecFactory
    {
    	public ISpecHandler CreateSpecFrom(object candidate)
        {
            var fields = candidate.AllFields();

            return fields.AllFixtureInitializers()
                .Then(fields.AllContextInitializers())
                .Then(fields.AllContextFinalizers())
                .Then(fields.BehaviorUnderTest())
                .Then(fields.AllObservations())
                .ThenFinally(fields.AllFixtureCleaners());
        }
    }
</pre>
<p>As you might guess a lot of extension methods are used in here, together with the composite pattern. Lets start be inspecting the AllFields() extension method.</p>
<pre class="brush: csharp">
        public static IEnumerable&lt;IFieldInfo&gt; AllFields(this object instance)
        {
            var mask = BindingFlags.Instance |
                       BindingFlags.Static |
                       BindingFlags.NonPublic |
                       BindingFlags.FlattenHierarchy;

            return instance
                .GetType()
                .GetFields(mask)
                .Select&lt;FieldInfo, IFieldInfo&gt;(x =&gt; new FieldInfoAdapter(x, instance));
        }
</pre>
<p>As its name implies this method reflects all the fields from the supplied object. It returns a collection of IFieldInfo objects. IFieldInfo? Yes I introduced a little adapter here, which helped me to introduce better test isolation in the spike code. </p>
<pre class="brush: csharp">
    public class FieldInfoAdapter : IFieldInfo
    {
        private readonly FieldInfo fieldInfo;
        private readonly object host;

        public FieldInfoAdapter(FieldInfo fieldInfo, object host)
        {
            this.fieldInfo = fieldInfo;
            this.host = host;
        }

        public object ReadValue()
        {
            return fieldInfo.GetValue(host);
        }

        public Type FieldType
        {
            get { return fieldInfo.FieldType; }
        }

        public string Name
        {
            get { return fieldInfo.Name; }
        }
    }
</pre>
<p>And here is how the code that finds all the It delegates was implemented.</p>
<pre class="brush: csharp">
public static ISpecHandler AllObservations(this IEnumerable&lt;IFieldInfo&gt; fields)
{
    return fields.AllHandlersOf().AsOne();
}

 private static IEnumerable AllHandlersOf&lt;HandlerType&gt;(this IEnumerable&lt;IFieldInfo&gt; fields)
 {
      return fields
           .Where(field =&gt; field.FieldType == typeof(HandlerType)  &amp;amp;amp;amp;&amp;amp;amp;amp; !field.Name.StartsWith(&quot;CS$&quot;))
           .Select&lt;IFieldInfo, ISpecHandler&gt;(field =&gt; new SpecHandler((Delegate)field.ReadValue()));
 }

  private static ISpecHandler AsOne(this IEnumerable&lt;ISpecHandler&gt; specHandler)
  {
        return new CompositeSpecHandler(specHandler);
  }
</pre>
<p>The basic stuff happens in the AllHandlersOf method which filters the supplied fields by the fieldtype and also removes all compiler generated fields (which start with &#8220;CS$&#8221; in their names). The content (aka the delegate) of each field that is left is read and wrapped in a SpecHandler instance. </p>
<pre class="brush: csharp">
    public class SpecHandler : ISpecHandler
    {
        private readonly Delegate handler;

        public SpecHandler(Delegate handler)
        {
            this.handler = handler;
        }

        public void Run()
        {
            try
            {
                handler.DynamicInvoke();
            }
            catch (TargetInvocationException e)
            {
                throw e.InnerException.PreserveStackTrace();
            }
        }
    }
</pre>
<p>Last but not least there is the Then extension method which uses the composite pattern to wrap all found spec handlers into a single instance.</p>
<pre class="brush: csharp">
 public static ISpecHandler Then(this ISpecHandler handler, ISpecHandler handlerToRunAfterwards)
        {
            return new CompositeSpecHandler(new[]
            {
                handler,
                handlerToRunAfterwards
            });
        }
</pre>
<p><strong>Conclusion</strong></p>
<p>It&#8217;s not as hard to implement such a syntax in C# as one might initially think. Although the code shown in this post is only spike code and not considered production ready, you can derive all what&#8217;s necessary to implement such a syntax. Fields, omitted access modifiers, Field-Initializers and Delegates are the basic parts together with some reflection logic to execute the code.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.bjoernrochel.de/2009/02/09/beat-the-it/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Poor mans dependency injection</title>
		<link>http://www.bjoernrochel.de/2008/08/29/poor-mans-dependency-injection/</link>
		<comments>http://www.bjoernrochel.de/2008/08/29/poor-mans-dependency-injection/#comments</comments>
		<pubDate>Fri, 29 Aug 2008 09:02:08 +0000</pubDate>
		<dc:creator>BjRo</dc:creator>
				<category><![CDATA[Testing]]></category>
		<category><![CDATA[Poor mans dependency Injection]]></category>

		<guid isPermaLink="false">http://www.bjoernrochel.de/?p=104</guid>
		<description><![CDATA[While watching the first of JP Boodhoos screencast series I discovered that a concept that I used in order to introduce testing to developers who work mostly in legacy code (I&#8217;m using Michael Feathers terminology here) is in fact a well known pattern.
Let me give you an example. You&#8217;ve got a class that you want [...]]]></description>
			<content:encoded><![CDATA[<p>While watching the first of JP Boodhoos screencast series I discovered that a concept that I used in order to introduce testing to developers who work mostly in legacy code (I&#8217;m using Michael Feathers terminology here) is in fact a well known pattern.</p>
<p>Let me give you an example. You&#8217;ve got a class that you want test, but this class somehow depends on an untestable resource like for instance a webservice. You don&#8217;t have some kind of dependency inversion to you&#8217;re hand and have to solve this problem on your own. A short example:</p>
<pre class="brush: csharp">
public class BillingService
{
      public BillingResult DoBilling(BillingData data)
      {
            Bill theBil = MakeBill(data);

            using(BillingClient wc = new BillingClient())
            {
                 wc.DoBilling(theBil);
            }
      }
}
</pre>
<p>What I mostly recommend in such a situation is</p>
<ol>
<li>Extract or isolate the ugly (Quote from Jeremy Miller) which is the webservice call here.</li>
<li>Introduce an interface that shields the class from the webservice call.</li>
<li>Make the whole class rely on the abstraction.</li>
<li>Use two constructors. I mostly reffered to them as the opened and the closed constructor.</li>
</ol>
<pre class="brush: csharp">
public class BillingService
{
      private IBillingSystem _BillingSystem;

      public BillingService(IBillingSystem billingSystem)
      {
             _BillingSystem = billingSystem;
      }

      public BillingSystem() : this(new BillingSystem())
      {
      }

      public BillingResult DoBilling(BillingData data)
      {
            Bill theBill = MakeBill(data);

            _BillingSystem.DoBilling();
      }
}

public interface IBillingSystem
{
      void DoBilling(Bill theBill);
}

public class BillingSystem : IBillingSystem
{
      public void DoBilling(Bill theBill)
      {
            using(BillingClient wc = new BillingClient())
            {
                 wc.DoBilling(theBill);
            }
      }
}
</pre>
<p>With that you can easily replace the untestable code with some kind of testdouble like a stub or a mock.</p>
<pre class="brush: csharp">
public class BillingServiceTest
{
     [Fact]
     public void DoBilling_ValidBill_BillIsCorrectlySendToBillingSystem()
     {
           BillingSystemStub billingSystem =  new BillingSystemStub();
           BillingService billingService = new BillingService(billingSystem);
           BillingData billingData = MakeValidBillingData();

           billingService.DoBilling(billingData);

           //Do some assertions
           Assert.NotNull(billingSystem.RecievedBill);
     }
}
</pre>
<p>Today I learned that this is also called POOR MANS DEPENDENCY INJECTION.</p>
<p>P.S.:<br />
Mabe the example is not the best one but I didn&#8217;t want to go into something like  Foo and Bar again. Besides that it&#8217;s only a simplified example. Consider that before throwing eggs and tomatos at me <img src='http://www.bjoernrochel.de/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> .</p>
<p>P.S.2:<br />
An alternative to this approach which doesn&#8217;t require a new interface is &#8220;Extract &amp; Override&#8221;.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.bjoernrochel.de/2008/08/29/poor-mans-dependency-injection/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>First steps with BDD</title>
		<link>http://www.bjoernrochel.de/2008/08/27/first-steps-with-bdd/</link>
		<comments>http://www.bjoernrochel.de/2008/08/27/first-steps-with-bdd/#comments</comments>
		<pubDate>Wed, 27 Aug 2008 11:35:06 +0000</pubDate>
		<dc:creator>BjRo</dc:creator>
				<category><![CDATA[BDD]]></category>
		<category><![CDATA[C# 3.0]]></category>
		<category><![CDATA[Domain Specific Languages]]></category>
		<category><![CDATA[MbUnit]]></category>
		<category><![CDATA[NUnit]]></category>
		<category><![CDATA[Testing]]></category>

		<guid isPermaLink="false">http://www.bjoernrochel.de/?p=79</guid>
		<description><![CDATA[One of the positive things of being ill and staying at home is having time to look into stuff I always wanted to look into but never actually had the time to. A good example for this is Behavior Driven Development or in short BDD.
BDD is described by its creator Dan North as an enhancement [...]]]></description>
			<content:encoded><![CDATA[<p>One of the positive things of being ill and staying at home is having time to look into stuff I always wanted to look into but never actually had the time to. A good example for this is Behavior Driven Development or in short BDD.</p>
<p>BDD is described by its creator Dan North as an enhancement to classic TDD with an emphasis on behavior specifications. It tries to provide business value by using classes and methods written as human readable sentences which can be reflected in order to generate a behavior specification document for the classes under test. The document can fulfill multiple purposes. It could be used as documentation for the tested system and even more important as an enabler for the ubiquitous language of the project (in terms of Evans DDD).</p>
<p>Before looking at something more concrete about BDD, first a brief history of my personal experience with testing throughout the last 3 years. I think this helps me to clarify, why I liked BDD from the moment I started reading about it.</p>
<p>My first unit tests looked very much like a lot of tests I&#8217;ve seen from a lot of people starting with unit tests since. (The examples are using the NUnit syntax but you can project this to any unit testing framework you want.)</p>
<p><strong>Every fresh start is hard.</strong></p>
<pre class="brush: csharp">
[TestFixture]
public class FactoryTest
{
    private Factory _Factory;

    [SetUp]
    public void SetUp()
    {
          _Factory = new Factory();
    }

    [Test]
    public void Test1()
    {
           SomeProduct product = _Factory.Create(&quot;FooProduct&quot;);

           Assert.IsNotNull(product);
           Assert.AreEqual(product.Name, &quot;FooProduct&quot;);
           Assert.AreEqual(product.Vendor, &quot;Foo&quot;);
    }

    [Test]
    [ExpectedException(typeof(ArgumentNullException))]
    public void Test2()
    {
           _Factory.Create(null);
    }
}
</pre>
<p>For every class I wanted to test I wrote a corresponding test class, which had the suffix &#8220;Test&#8221; and contained all tests for that class under test. I discovered later that this is a testing strategy known as TEST-CASE-CLASS-PER-CLASS while reading &#8220;XUnit Test Patterns&#8221; by Gerard Meszaros. At that time it felt pretty confident with what I did. I mean, I wrote tested code, which was to a particular degree bug free. Yeah right, but let&#8217;s have a look at the downside of what I was doing:</p>
<ul>
<li>When such a test failed I didn&#8217;t have a clue what the test was actually verifying. I had to debug the testcode.</li>
<li>When a test like &#8220;Test1&#8243; failed I didn&#8217;t know what assertion was broken. I had to debug the testcode. </li>
<li>It didn&#8217;t scale well. I became quite messy and unclear as the number of tests increased.</li>
<li>I always hat a hard time coming back to the test after having spend days in a different topic.</li>
</ul>
<p><strong>Incorporating a standard naming scheme for tests</strong></p>
<p>As one result of the observed problems I incorporated a standard naming scheme (inspired by a post of Roy Osherove) to my tests which followed the following scheme:</p>
<p>MethodName_Scenario_Behavior</p>
<p>Applied to the sample code it would look like this:</p>
<pre class="brush: csharp">
[TestFixture]
public class FactoryTest
{
    private Factory _Factory;

    [SetUp]
    public void SetUp()
    {
          _Factory = new Factory();
    }

    [Test]
    public void Create_ValidCreationData_CreatesAValidProduct()
    {
           SomeProduct product = _Factory.Create(&quot;FooProduct&quot;);

           Assert.IsNotNull(product);
           Assert.AreEqual(product.Name, &quot;FooProduct&quot;);
           Assert.AreEqual(product.Vendor, &quot;Foo&quot;);
    }

    [Test]
    [ExpectedException(typeof(ArgumentNullException))]
    public void Create_NullForArgument_ThrowsArgumentNullException()
    {
           _Factory.Create(null);
    }
}
</pre>
<p>The naming scheme helped me a lot for maintaining my tests. When a test failed I knew instantly a) which class was tested, b) what the test scenario was and c) what the expected behavior was, that was broken. However, the problem with the multiple assertions still existed. You can fix this issue by providing error messages with every assertion. I must admit that I never really liked that approach. I would rather go down the SINGLE-ASSERTION-PER-TEST-METHOD way. This way you have the behavior of the class under test completely discoverable by a unit test framework which is something I appreciate. (Maybe I&#8217;m alone with this. Several members of my team disagree with this.)</p>
<p><strong>Single Assertion per Test</strong></p>
<p>After refactoring the test it would look like this:</p>
<pre class="brush: csharp">
[TestFixture]
public class FactoryTest
{
    private Factory _Factory;

    [SetUp]
    public void SetUp()
    {
          _Factory = new Factory();
    }

    [Test]
    public void Create_ValidCreationData_CreatedProductHasName()
    {
           SomeProduct product = _Factory.Create(&quot;FooProduct&quot;);
           Assert.AreEqual(product.Name, &quot;FooProduct&quot;);
    }

    [Test]
    public void Create_ValidCreationData_CreatesProductHasNameOfVendor()
    {
           SomeProduct product = _Factory.Create(&quot;FooProduct&quot;);
           Assert.AreEqual(product.Vendor, &quot;Foo&quot;);
    }

    [Test]
    [ExpectedException(typeof(ArgumentNullException))]
    public void Create_NullForArgument_ThrowsArgumentNullException()
    {
           _Factory.Create(null);
    }
}
</pre>
<p>One downside of this approach is the sudden code duplication you now have in the code. It isn&#8217;t that big in the example but it can be in reality. You should treat test code as you&#8217;re treating production code. Don&#8217;t repeat yourself! I usually dealt with that situation by switching the test strategy.</p>
<p><strong>Switching to TEST-CLASS-PER-FIXTURE</strong></p>
<p>TEST-CLASS-PER-FIXTURE is again a test strategy described by Gerald Meszaros in this book &#8220;XUnit Test Patterns&#8221;. The basic idea is that you split your test classes into several test classes based on the common initialization / execution logic the methods share. Applied to the sample code this would result in this:</p>
<pre class="brush: csharp">
[TestFixture]
public class FactoryTest_ArgumentTests
{
    private Factory _Factory;

    [SetUp]
    public void SetUp()
    {
          _Factory = new Factory();
    }

    [Test]
    [ExpectedException(typeof(ArgumentNullException))]
    public void Create_NullForArgument_ThrowsArgumentNullException()
    {
           _Factory.Create(null);
    }
}

[TestFixture]
public class FactoryTest_CreatingAValidProduct
{
    private Factory _Factory;
    private SomeProduct _Product;

    [SetUp]
    public void SetUp()
    {
          _Factory = new Factory();
          _Product = _Factory.Create(&quot;FooProduct&quot;);
    }

    [Test]
    public void Create_ValidCreationData_CreatedProductHasName()
    {
           Assert.AreEqual(_Product.Name, &quot;FooProduct&quot;);
    }

    [Test]
    public void Create_ValidCreationData_CreatesProductHasNameOfVendor()
    {
           Assert.AreEqual(_Product.Vendor, &quot;Foo&quot;);
    }
}
</pre>
<p>I&#8217;ve worked with that approach for 2 years now. It suited my needs very well. However the tests are often not as expressive as I like them to be in terms of the naming. I&#8217;ll guess there&#8217;s a better naming scheme when using something like the TEST-CASE-CLASS-PER-FIXTURE testing strategy and that&#8217;s where the circle closes for me.</p>
<p><strong>Coming back to BDD</strong></p>
<p>While working through the preparation material for JP Boodhoos Nothing but .NET bootcamp I made first contact with his style of applying BDD. I must admit that I&#8217;m pretty amazed, because I&#8217;ve seen a lot of things of value for me. Sometimes sourcecode says more than a thousand words, so this is what the sample would look like if his BDD conventions have been applied to it:</p>
<pre class="brush: csharp">
[Concern(typeof (Factory))]
public class When_creating_a_valid_product : ContextSpecification
{
     private Factory _Factory;
     private Product _CreatedProduct;

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

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

     [Observation]
     public void the_product_should_contain_the_correct_product_name()
     {
          _CreatedProduct.Name.should_be_equal_to(&quot;FooProduct&quot;);
     }

     [Observation]
     public void the_product_should_contain_the_correct_vendor_name()
     {
          _CreatedProduct.Vendor.should_be_equal_to(&quot;Foo&quot;);
     }
}

[Concern(typeof (Factory))]
public class When_passing_null_for_product_name : ContextSpecification
{
     private Factory _Factory;
     private Action _Call;

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

     protected override void because()
     {
           _Call = The.Action(() =&gt; _Factory.Create(null))
     }

     [Observation]
     public void should_throw_an_ArgumentNullException()
     {
           _Call.should_throw_an&lt;ArgumentNullException&gt;();
     }
}
</pre>
<p>Here is the base class that provides the hooks for the unit test framework (in this case MbUnit).</p>
<pre class="brush: csharp">
using MbUnit.Framework;
using Context = MbUnit.Framework.TestFixtureAttribute;

namespace NothinButDotNetPrep.SpecHelpers
{
    [Context]
    public abstract class ContextSpecification
    {
        [SetUp]
        public void setup()
        {
            establish_context();
            because();
        }

        [TearDown]
        public void teardown()
        {
            after_each_specification();
        }

        protected abstract void because();
        protected abstract void establish_context();
        protected virtual void after_each_specification()
        {
        }
    }
}
</pre>
<p>I like his way to implement the AAA (arrange, act and assert) pattern with the template method pattern and C# 3.0 extension method for the actual assertions very much. It feels like a natural progression to what I&#8217;ve been doing previously with a lot better readability. Another interesting thing is that he uses a tool called <em>bddunit </em> to generate a behavior documentation from the tests. A generated documentation would look like this:</p>
<ul>
<p>    Behavior of Factory</p>
<ul>
<li>
          When creating a valid product</p>
<ul>
<li>the product should contain the correct vendor name.</li>
<li>the product should contain the correct product name.</li>
</ul>
</li>
<li>
          When passing null for product name</p>
<ul>
<li>should throw an ArgumentNullException</li>
</ul>
</li>
</ul>
</li>
</ul>
<p>I&#8217;ll definitely have to dig more into this. If you&#8217;re interested in learning more about BDD here are some links I&#8217;ve read this morning.</p>
<ul>
<li>Dan North: <a href="http://dannorth.net/introducing-bdd" target="_blank">Introducing BDD</a>.</li>
<li>AgileJoe: <a href="http://www.lostechies.com/blogs/joe_ocampo/archive/2007/08/07/attempting-to-demystify-behavior-driven-development.aspx" target="_blank">Attempting to demyistify BDD</a>.</li>
<li>JP: Bodhoo: <a href="http://codebetter.com/blogs/jean-paul_boodhoo/archive/2007/11/29/getting-started-with-bdd-style-context-specification-base-na.aspx" target="_blank">Getting started with BDD style Context / Specification base naming</a>.</li>
<li>Jimmy Bogard: <a href="http://grabbagoft.blogspot.com/2008/01/converting-tests-to-specs-is-bad-idea.html" target="_blank">Converting tests into specs is a bad idea</a>.</li>
<li>David Laribee: <a href="http://codebetter.com/blogs/david_laribee/archive/2007/12/17/approaching-bdd.aspx" target="_blank">Approaching BDD.</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.bjoernrochel.de/2008/08/27/first-steps-with-bdd/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Some words regarding MSTest</title>
		<link>http://www.bjoernrochel.de/2008/08/19/some-words-regarding-mstest/</link>
		<comments>http://www.bjoernrochel.de/2008/08/19/some-words-regarding-mstest/#comments</comments>
		<pubDate>Tue, 19 Aug 2008 19:41:50 +0000</pubDate>
		<dc:creator>BjRo</dc:creator>
				<category><![CDATA[MSTest]]></category>
		<category><![CDATA[Testing]]></category>

		<guid isPermaLink="false">http://bjro.de/2008/08/19/some-words-regarding-mstest/</guid>
		<description><![CDATA[Today I stumbled again about this and feel (once more) a bit frustrated about the current version of MSTest.
In theory Visual Studio VS2008 supports Test-Class-Inheritance. Once you actually start using it, you pretty fast encounter one big limitation:
The test base class must be in the same assembly as the derived test
Mh,Â  is that such an [...]]]></description>
			<content:encoded><![CDATA[<p>Today I stumbled again about this and feel (once more) a bit frustrated about the current version of <strong>MSTest</strong>.</p>
<p>In theory Visual Studio VS2008 supports Test-Class-Inheritance. Once you actually start using it, you pretty fast encounter one big limitation:</p>
<p><strong>The test base class must be in the same assembly as the derived test</strong></p>
<p>Mh,Â  is that such an uncommon scenario that it&#8217;s not supported? Personally I don&#8217;t think so. What about BDD extensions for MSTest? Do I need to have a Specification-base class in each test assembly? Oh, c&#8217;mon ?!</p>
<p>Just when you think it can&#8217;t get worse, you realize that</p>
<p><strong>Tests using Test-Class-Inheritance are NOT EXECUTED when running inside a VS TFS 2008 TeamBuild</strong></p>
<p>Awesome <img src='http://www.bjoernrochel.de/wp-includes/images/smilies/icon_sad.gif' alt=':-(' class='wp-smiley' /> </p>
<p>Besides that we also still have the *.vsmdi-hell (Replace * with the name your Solution and a number between 1 and 100 . . .), but that a different story.</p>
<p>If it was my personal decision I would ditch MSTest right away. It&#8217;ll be interesting to see whether I&#8217;m able to convince our development leads to go down that road . . .</p>
]]></content:encoded>
			<wfw:commentRss>http://www.bjoernrochel.de/2008/08/19/some-words-regarding-mstest/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
	</channel>
</rss>
