<?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>www.fooberry.com &#187; Unit Testing</title>
	<atom:link href="http://fooberry.com/category/unit-testing/feed/" rel="self" type="application/rss+xml" />
	<link>http://fooberry.com</link>
	<description>Sweetness Without Context</description>
	<lastBuildDate>Fri, 30 Jul 2010 14:17:02 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>How does BDD style specs test a single class?</title>
		<link>http://fooberry.com/2010/03/16/how-does-bdd-style-specs-test-a-single-class/</link>
		<comments>http://fooberry.com/2010/03/16/how-does-bdd-style-specs-test-a-single-class/#comments</comments>
		<pubDate>Tue, 16 Mar 2010 15:56:34 +0000</pubDate>
		<dc:creator>mark</dc:creator>
				<category><![CDATA[Unit Testing]]></category>
		<category><![CDATA[BDD]]></category>
		<category><![CDATA[SRP]]></category>

		<guid isPermaLink="false">http://fooberry.com/2010/03/16/how-does-bdd-style-specs-test-a-single-class/</guid>
		<description><![CDATA[<br/>I really like how BDD specs read, especially in the test result window. We don’t use anything like MSpec yet. I’m still trying to get testing to gain momentum and making them look as far from regular code as MSpec does makes it that much more difficult. We do have a pattern we follow: public [...]]]></description>
			<content:encoded><![CDATA[<br/><p>I really like how BDD specs read, especially in the test result window. We don’t use anything like <a href="http://github.com/machine/machine">MSpec</a> yet. I’m still trying to get testing to gain momentum and making them look as far from regular code as MSpec does makes it that much more difficult. </p>
<p>We do have a pattern we follow:</p>
<pre class="c#" name="code">public class When_something_happens : Specification{

  Foo somethingUnderTest;
  Bar result;

  override public void Given(){
    somethingUnderTest = new Foo(...);
  }

  override public void When(){
    result = somethingUnderTest.doesSomething();
  }

  [Then] public void the_result_should_not_be_null(){
     result.ShouldNotBeNull();
  }

}</pre>
<p>&#160;</p>
<p>We just created a base Specification, renamed the xUnit FactAttribute to ThenAttribute (probably unnecessary) and then created a load of extensions of object for the ShouldBeWhatevers. There is more noise than there would be with MSpec, but that&#8217;s the tradeoff for looking like code.</p>
<p>I’m pretty happy with all this and it works pretty well, but what I’m finding is that the BDD specs I write before I write a class often don’t test what the class does in the end, after that work has been off loaded to a dependency. Take for example the following simple spec. (bits have been left out for simplicity…know it won’t compile)</p>
<pre class="c#" name="code">public class When_creating_an_order_invoice_view_model_from_an_order : Specification {

  override public void Given(){
    factory = new OrderInvoiceViewDataFactory();
    order = new Order{ FirstName = &quot;Homer&quot;,
                       LastName  = &quot;Simpson&quot;,
                       Items     = new []{
                                     new LineItem{ Product =&quot;Duff 6 pack&quot;,
                                                            Price = 4.99m, }
                                     new LineItem{ Product =&quot;Duff can koozie&quot;,
                                                            Price = 0.99m, }
                                   }
  }

  override public void When(){
    invoice = factory.BuildFrom(order);
  }

  [Then] public void the_total_should_be_the_sum_of_the_items(){
    invoice.Total.ShouldBe(4.99m + 0.99m);
  }

}</pre>
<p>&#160;</p>
<p>Overlooking the simplicity of the spec, it seems reasonable right?</p>
<p>Here’s my problem. I build my factory to calculate the total, but as soon as I do I realize that totaling the order in the factory that builds the view data violates <a href="http://en.wikipedia.org/wiki/Single_responsibility_principle">SRP</a>.</p>
<p>That’s easy enough to fix. I just end up with a factory that looks like this:</p>
<pre class="c#" name="code">public class OrderInvoiceViewDataFactory{
  public OrderInvoiceViewDataFactory(IOrderTotalCalculator calculator){
    //...
  }
}</pre>
<p>&#160;</p>
<p>Now I mock that out in my spec:</p>
<pre class="c#" name="code">public class When_creating_an_order_invoice_view_model_from_an_order : Specification {
  override public void Given(){
    // ..

    mockCalculator = new Mock&lt;(IOrderTotalCalculator&gt;();
    mockCalculator
      .Setup(x=&gt;x.CalculateTotal(order))
      .Returns(3.14m);
    factory = new OrderInvoiceViewDataFactory(mockCalculator.Object);

  }

  [Then] public void the_total_should_be_the_sum_of_the_items(){
    // we only need to test what out mock returns
    invoice.Total.ShouldBe(3.14m);
  }

}</pre>
<p>&#160;</p>
<p><strong>…and abracadabra…my spec tests nothing.</strong></p>
<p>From a spec perspective it’s valid, but from a test perspective, all it tests is that my mocking framework works and I’m making that call to it like I expect.</p>
<p>So what do you do? All the test around the calculations move to another file and the spec&#160; gets simplified to just test the interaction with the dependencies?</p>
<pre class="c#" name="code">[Then] public void the_calculator_was_called_to_calculate_the_total(){
   mockCalculator.Verify(x=&gt;x.CalculateTotal(order),Times.Once);
}</pre>
<p>&#160;</p>
<p>What I loose here is my nice test result that anyone can look at an understand. All my non-techy folks need to look at several different places to see if that order invoice is be calculated correctly.</p>
<p>You could make this an integration test and test the calculator as well, but I don’t like that idea either.</p>
<p>This is probably a sign that I’m not writing my specs correctly or I should identify this is going to be factored out sooner. This hasn’t been the case so far. Especially when we are translating something from a graph of objects to a flat representation&#160; for a model in our MVC app, a lot of the work ends up being factored out or pushed into <a href="http://www.codeplex.com/AutoMapper">AutoMapper</a> where we need to write a different tests for it. </p>
<p>When we are done with the refactoring, the original spec for the class is very skinny, which is good, but as I said, seeing the results of how the story is progressing is more difficult. Maybe that is where my focus needs to be. How do you tie the specs to a specific story and see the results in an aggregated manner?</p>
]]></content:encoded>
			<wfw:commentRss>http://fooberry.com/2010/03/16/how-does-bdd-style-specs-test-a-single-class/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Are extensive extension method an anti-pattern</title>
		<link>http://fooberry.com/2009/11/30/are-extensive-extension-method-an-anti-pattern/</link>
		<comments>http://fooberry.com/2009/11/30/are-extensive-extension-method-an-anti-pattern/#comments</comments>
		<pubDate>Mon, 30 Nov 2009 15:55:09 +0000</pubDate>
		<dc:creator>mark</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Unit Testing]]></category>
		<category><![CDATA[anti-pattern]]></category>
		<category><![CDATA[design]]></category>
		<category><![CDATA[patterns]]></category>

		<guid isPermaLink="false">http://fooberry.com/2009/11/30/are-extensive-extension-method-an-anti-pattern/</guid>
		<description><![CDATA[<br/>I was explaining my dilemma to a Java friend and the e-mail ended up being fairly interesting, so I thought I would share it. I&#8217;m sure Java has extension methods, but I&#8217;ll give it a once over just in case.&#160; You can extend existing classes without sub-classing by extension methods. public static IEnumerable&#60;SelectListItem&#62; AsSelectListItems( this [...]]]></description>
			<content:encoded><![CDATA[<br/><p>I was explaining my dilemma to a Java friend and the e-mail ended up being fairly interesting, so I thought I would share it. </p>
<blockquote><p>I&#8217;m sure Java has extension methods, but I&#8217;ll give it a once over just in case.&#160; You can extend existing classes without sub-classing by extension methods.</p>
<pre>public static IEnumerable&lt;SelectListItem&gt;
                            AsSelectListItems( this IEnumerable&lt;Person&gt; listOfPeople){
   IList&lt;SelectListItem&gt; selectListItems = new List
<selectlistitems>();
   foreach(var person in listOfPeople){
      selecListItems.Add(new SelectListItem(person.ID,
					    string.Format(&quot;{0} {1} {2}&quot;,
                                                          person.First,
                                                          person.Middle,
                                                          person.Last));
   }
   return selectListItems;
}</pre>
<p>Right. So the <code>this</code> operator tells the compiler to basically create this function:</p>
<pre>public static IEnumerable&lt;SelectListItem&gt;
                           AsSelectListItems(IEnumerable&lt;Person&gt; listOfPeople);</pre>
<p>And invoke it every time you see this:</p>
<pre>IEnunerable&lt;Person&gt; p = myService.GetAllPeople();
IEnumerable&lt;SelectListItem&gt; s = p.AsSelectListItems();</pre>
<p>You probably knew all this, but it explains how we are using them. We end up calling a lot of extension methods off other extension methods. </p>
<pre>myViewData.PersonSelectListItems = myService.GetAllPeople()
                                                   .AsSelectListItems()
                                                   .OrderedByText()
                                                   .StartingWithAnEmptyItem();</pre>
<p>In this example we have three extension method calls and I think it really makes the code much more readable, but it makes testing this code a little more difficult. Obviously, the myService is a mocked dependency which will return a fake list of people, but the other extension method calls cannot be mocked, and the scope of the test bleeds a bit. </p>
<p>I like the syntax it gives, but now I&#8217;m going to test potentially four classes when I should be testing only one. </p>
</blockquote>
<p>This gets pretty pandemic in our code. Especially trying to make Selenium’s API and the assertion API of Nunit and xUnit more fluent.</p>
]]></content:encoded>
			<wfw:commentRss>http://fooberry.com/2009/11/30/are-extensive-extension-method-an-anti-pattern/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Type Safe Unit Testing of Data Annotations Validations</title>
		<link>http://fooberry.com/2009/11/13/type-safe-unit-testing-of-data-annotations-validations/</link>
		<comments>http://fooberry.com/2009/11/13/type-safe-unit-testing-of-data-annotations-validations/#comments</comments>
		<pubDate>Fri, 13 Nov 2009 19:52:59 +0000</pubDate>
		<dc:creator>mark</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://fooberry.com/2009/11/13/type-safe-unit-testing-of-data-annotations-validations/</guid>
		<description><![CDATA[<br/>We’re using the Data Annotations Validators in ASP.Net MVC 2.0, but there wasn’t a really great way to unit test them. I’ve read Brad Wilson’s blog post about how to set them up and unit test them, but I didn’t like how you relied on the name of the property as a string. // Arrange [...]]]></description>
			<content:encoded><![CDATA[<br/><p>We’re using the Data Annotations Validators in ASP.Net MVC 2.0, but there wasn’t a really great way to unit test them. I’ve read <a href="http://bradwilson.typepad.com/blog/2009/04/dataannotations-and-aspnet-mvc.html">Brad Wilson’s blog post</a> about how to set them up and unit test them, but I didn’t like how you relied on the name of the property as a string.</p>
<pre class="c#" name="code">// Arrange
var propertyInfo = typeof(Contact).GetProperty(&quot;FirstName&quot;);</pre>
<p>It would be nicer if that used lambda expressions to get the name of the property, so I set out to do just that. Before we begin, I need to remind you, as always, <strong>I don’t know what I’m doing</strong>. This is my first tiny venture into expression trees so it is possible isn’t the best way to do things, but so far, it’s working for me.</p>
<p>I created a base Specification to wrap up a lot of the messy bits of getting property names by lambdas. I took a look at <a href="http://aspnet.codeplex.com/sourcecontrol/changeset/view/23011?projectName=aspnet#266392">how the ASP.Net MVC helpers did it</a> and roughly followed their pattern.</p>
<pre class="c#" name="code">public class DataAnnotationSpecification&lt;T&gt; : Specification
{

    public PropertyInfo Property(Expression&lt;Func&lt;T,object&gt;&gt; op)
    {
        return Property(GetInputName(op));
    }

    public PropertyInfo Property(string propertyName)
    {
        return typeof (T).GetProperty(propertyName);
    }

    public static string GetInputName&lt;TProperty&gt;(Expression&lt;Func&lt;T, TProperty&gt;&gt; expression)
    {
        // not sure I totally understand this
        if (expression.Body.NodeType == ExpressionType.Convert)
        {
            var ue = (UnaryExpression)expression.Body;
            return GetInputName((MemberExpression) ue.Operand );
        }

        if (expression.Body.NodeType == ExpressionType.MemberAccess)
        {
            return GetInputName((MemberExpression)expression.Body);
        }
        throw new NotImplementedException();
    }

    private static string GetInputName(MemberExpression memberExpression)
    {
        return memberExpression.Member.Name;
    }

}</pre>
<p>I know this probably doesn’t cover an exhaustive list of expressions, but we’re only talking about Property access tests here so we’re probably in the clear.</p>
<p>To make things a bit nicer, I also created some extensions off PropertyInfo to help setup their assertions.</p>
<pre class="c#" name="code">public static class AttributeAssertions
{

    public static void ShouldNotBeRequired(this PropertyInfo @this)
    {
        @this.ShouldNotHaveAttribute&lt;RequiredAttribute&gt;();
    }

    public static void ShouldBeRequired(this PropertyInfo @this)
    {
        @this.ShouldHaveAttribute&lt;RequiredAttribute&gt;();
    }

    private static T PropertyAttributeOn&lt;T&gt;(ICustomAttributeProvider propertyInfo)
    {
        return propertyInfo.GetCustomAttributes(typeof (T), false)
            .Cast&lt;T&gt;()
            .FirstOrDefault();
    }

    public static void ShouldHaveAttribute&lt;T&gt;(this PropertyInfo @this)
    {
        PropertyAttributeOn&lt;T&gt;(@this).ShouldNotBeNull();
    }
    public static void ShouldNotHaveAttribute&lt;T&gt;(this PropertyInfo @this)
    {
        PropertyAttributeOn&lt;T&gt;(@this).ShouldBeNull();
    }
}</pre>
<p>We only have the <code>ShouldBeRequired</code> and <code>ShouldNotBeRequired</code> right now, but you could see it will be easy to extend upon them.&#160; The finished spec looks something like this.</p>
<pre class="c#" name="code">public class When_testing_the_state_of_the_CustomerViewData
    : DataAnnotationSpecification&lt;CustomerViewData&gt;
{
    [Then] public void the_customer_first_name_is_required()
    {
        Property(x =&gt; x.CustomerFirstName).ShouldBeRequired();
    }

    [Then] public void the_customer_middle_name_is_not_required()
    {
        Property(x =&gt; x.CustomerMiddleName).ShouldNotBeRequired();
    }

    [Then] public void the_customer_last_name_is_required()
    {
        Property(x=&gt;x.CustomerLastName).ShouldBeRequired();
    }

    [Then] public void the_email_address_is_required()
    {
        Property(x=&gt;x.CustomerEmailAddress).ShouldBeRequired();
    }

}</pre>
<p>That’s not so bad, and it stands up to any refactoring we might do.</p>
]]></content:encoded>
			<wfw:commentRss>http://fooberry.com/2009/11/13/type-safe-unit-testing-of-data-annotations-validations/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Replacing Rhino with Moq</title>
		<link>http://fooberry.com/2009/11/10/replacing-rhino-with-moq/</link>
		<comments>http://fooberry.com/2009/11/10/replacing-rhino-with-moq/#comments</comments>
		<pubDate>Tue, 10 Nov 2009 16:05:41 +0000</pubDate>
		<dc:creator>mark</dc:creator>
				<category><![CDATA[Unit Testing]]></category>
		<category><![CDATA[Moq]]></category>
		<category><![CDATA[Rhino]]></category>

		<guid isPermaLink="false">http://fooberry.com/2009/11/10/replacing-rhino-with-moq/</guid>
		<description><![CDATA[<br/>We’re just starting down the path of serious and extensive testing with mocks and fakes. Our initial tests were all done using Rhino Mocks, mostly because it had a well established reputation and we had no reason not to give it a try. The syntax is beautiful and did everything we needed, until we tried [...]]]></description>
			<content:encoded><![CDATA[<br/><p>We’re just starting down the path of serious and extensive testing with mocks and fakes. Our initial tests were all done using Rhino Mocks, mostly because it had a well established reputation and we had no reason not to give it a try. The syntax is beautiful and did everything we needed, until we tried to make a test similar to this one pass successfully. </p>
<pre class="c#" name="code">public interface IFoo
{
    string Bar();
}

[Fact] public void TestWithRhino()
{
    var mock = MockRepository.GenerateStub&lt;IFoo&gt;();
    mock.Stub(x =&gt; x.Bar()).Return(&quot;bar&quot;);
    mock.Stub(x =&gt; x.Bar()).Return(&quot;baz&quot;);
    Assert.Equal(&quot;baz&quot;,mock.Bar());
}</pre>
<p>We couldn’t, at least we couldn’t using strictly stubs. From what I could gather, we could if we used a more complicated for of mocking besides stubs. We only need stubs, or fakes, because we don’t need to test all the interaction, just the ending state. </p>
<p>Since we don’t have any serious stock in using Rhino, as an alternative I decided to take a look at using Moq. The syntax for Moq is not as nice. It is more wordy, but I do like how it doesn’t rely on extensions methods for everything. But what about the sample test?</p>
<pre class="c#" name="code">[Fact] public void TestWithMoq()
{
    var mock = new Mock&lt;IFoo&gt;();
    mock.Setup(x =&gt; x.Bar()).Returns(&quot;bar&quot;);
    mock.Setup(x =&gt; x.Bar()).Returns(&quot;baz&quot;);
    Assert.Equal(&quot;baz&quot;, mock.Object.Bar());
}</pre>
<p>It passes! Switching wasn’t that difficult, but where is the ugly syntax I‘ve run into so far? Well this in Rhino:</p>
<pre class="c#" name="code">MockOrdersRepository.AssertWasNotCalled(x=&gt;x.StartOrder(null,null,null,null));</pre>
<p>&#8230;becomes this in Moq:</p>
<pre class="c#" name="code">MockOrdersRepository   .Verify(x=&gt;x.StartOrder( It.IsAny&lt;string&gt;(),                            It.IsAny&lt;string&gt;(),                            It.IsAny&lt;string&gt;(),                            It.IsAny&lt;string&gt;()),              Times.Never());</pre>
<p>It might be I am not familiar enough with either to say that is the equivalent assertion of both, but it is working for us. I am probably missing something that is causing Moq to look more verbose.</p>
]]></content:encoded>
			<wfw:commentRss>http://fooberry.com/2009/11/10/replacing-rhino-with-moq/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Two bugs for the price of none</title>
		<link>http://fooberry.com/2009/02/18/two-bugs-for-the-price-of-none/</link>
		<comments>http://fooberry.com/2009/02/18/two-bugs-for-the-price-of-none/#comments</comments>
		<pubDate>Wed, 18 Feb 2009 13:57:59 +0000</pubDate>
		<dc:creator>mark</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[Nonsensical Rant]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://fooberry.com/?p=674</guid>
		<description><![CDATA[<br/>We recently pushed a feature into production that had a pretty serious flaw. If gone unfound it could have caused headaches with billing the wrong customer the wrong amount and all kinds of other potentially damning effects. Luckily for us, we also had a second bug. The feature that was to send the notification e-mail [...]]]></description>
			<content:encoded><![CDATA[<br/><p>We recently pushed a feature into production that had a pretty serious flaw. If gone unfound it could have caused headaches with billing the wrong customer the wrong amount and all kinds of other potentially damning effects.  Luckily for us, we also had a second bug. The feature that was to send the notification e-mail that data was ready to be corrupted by our bug was misconfigured when it moved to the production environment. Lucky for us, no one was being told they should go execute our buggy code, so no one did and we found it, fixed it and all those actions items that queued up ran through without a hitch.</p>
<p>Now lucky for us or not, we did fail to find two serious bugs. It highlights the need for thorough acceptance testing. <em>Thorough</em> being the key word there.</p>
<p>The first bug existed if action items queued up and were acted upon in a certain order. Testing was done in this area, but the items never fell in the order where we found the bug. Would acceptance tests go so far to say:</p>
<ul>
<li>Act on the first item in the list and verify the actions were taken correctly.</li>
<li>Act on the second item in the list&#8230;</li>
<li>Act on a list with a single item&#8230;</li>
<li>Act on a list with two items&#8230;</li>
<li>Act on a list with <em>n</em> items&#8230;</li>
</ul>
<p>How detailed do you get? </p>
<p>The first bug was a pretty lame mistake, although I feel SQL should have been alerted when we attempted to do an udate  a single from a statement that returned multiples. I don&#8217;t know how it makes sense to choose the first row and go about your business. </p>
<p>As for the second, testing the production configuration is hard. We do have some junk data laying around in the production DB that we can manipulate, and probably should have to verify the e-mails were sending. Config changes between the two are difficult to manage. Keeping the e-mail address, servers, roles, etc in sync to the correct environment is made simpler by branches, but verification isn&#8217;t.</p>
]]></content:encoded>
			<wfw:commentRss>http://fooberry.com/2009/02/18/two-bugs-for-the-price-of-none/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Getting Started with Selenium</title>
		<link>http://fooberry.com/2009/01/23/getting-started-with-selenium/</link>
		<comments>http://fooberry.com/2009/01/23/getting-started-with-selenium/#comments</comments>
		<pubDate>Fri, 23 Jan 2009 14:27:13 +0000</pubDate>
		<dc:creator>mark</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[TFS]]></category>
		<category><![CDATA[Unit Testing]]></category>
		<category><![CDATA[Web Development]]></category>
		<category><![CDATA[NUnit]]></category>
		<category><![CDATA[Selenium]]></category>
		<category><![CDATA[Team Build]]></category>

		<guid isPermaLink="false">http://fooberry.com/2009/01/23/getting-started-with-selenium/</guid>
		<description><![CDATA[<br/>The past few days have been spent getting Selenium setup and running as part of our CI builds. We only have a few proof-of-concept tests right now, but the power and potential is apparent. We have no automated unit testing right now and very little code in our code behinds so functional testing is as good [...]]]></description>
			<content:encoded><![CDATA[<br/><p>The past few days have been spent getting <a id="j.c:" title="Selenium" href="http://seleniumhq.org/">Selenium</a> setup and running as part of our CI builds. We only have a few proof-of-concept tests right now, but the power and potential is apparent. We have no automated unit testing right now and very little code in our code behinds so functional testing is as good as we&#8217;re going to get. Also, with the amount of AJAX that is currently in our pages, and the additional amount we see in them in the near future, Selenium&#8217;s method of control the browser helps us make sure our pages do and continue to behave like we expect.</p>
<p>Getting setup with Selenium was incredibly simple. The Selenium IDE Firefox plugin makes creating your first Selenium test a snap. Download it and install it and you&#8217;re off. I&#8217;m not going to walk you through creating the tests, because the Selenium web site has a pretty decent <a id="em17" title="movie" href="http://seleniumhq.org/movies/intro.mov">movie</a> that&#8217;ll take care of you.</p>
<p>The output of the test recorder are HTML files that contain the instructions, aka &#8220;Selenese&#8221;, to re-execute the tests through both the IDE and Selenium core. Selenese is very simple <a id="fuos" title="by design" href="http://darkforge.blogspot.com/2006/12/why-is-html-selenese-so-simplistic.html">by design</a>. While we could run the Selenese tests through the core in our Continuous Integration server, I&#8217;ve decided to use the IDE to export the C# source for the tests I create. This allows my to put the Selenium test into an NUnit test harness, refactor some of the common setup and config, and also run the tests via <a id="d7yk" title="Selenium Remote Control" href="http://seleniumhq.org/projects/remote-control/">Selenium Remote Control</a>(RC). I know the refactoring goes against the Selenese simplicity, but I want to run my tests locally and with different credentials without changing every test. Also, running in RC lets me run the tests without having to watch the pages in the browser fly by and, someone day, concurrently run all the browsers I care about.</p>
<p>Here&#8217;s an example of what one of those tests might look like </p>
<pre language="c#" name="code">
using System;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using NUnit.Framework;
using Selenium;

namespace SeleniumTests{

   [TestFixture] public class NewTest {
	private ISelenium selenium;
	private StringBuilder verificationErrors;

	[SetUp] public void SetupTest() {
		selenium = new DefaultSelenium("localhost", 4444, "*chrome", "http://www.google.com/");
		selenium.Start();
		verificationErrors = new StringBuilder();
	}

	[TearDown] public void TeardownTest() {
		try {
			selenium.Stop();
		} catch (Exception) {
			// Ignore errors if unable to close the browser
		}
		Assert.AreEqual("", verificationErrors.ToString());
	}

	[Test] public void TheNewTest() {
		selenium.Open("/");
		selenium.Type("q", "fooberry");
		selenium.Click("btnG");
		selenium.WaitForPageToLoad("30000");
	      Assert.IsTrue(selenium.IsElementPresent("css=a[href=\"http://www.fooberry.com/\"]"));
	}
   }
}
</pre>
<p>Getting this to run in the Team Build is as easy as <a id="dglw" title="getting the regular NUnit tests running" href="http://fooberry.com/2008/09/05/automating-the-build-step-1/">getting the regular NUnit tests running</a>. First we would want to parameterize those tests a bit so we can pass different hosts, ports and credentials (if present). That&#8217;s not too hard and should be obvious.</p>
<p>We&#8217;re trying multiple CI builds. One build just compiles and runs the unit test code, which is currently this single test&#8230;.baby steps.</p>
<pre language="c#" name="code">
[TestFixture] public class TheMostAwesomestUnitTestInTheWorld {
    [Test] public void ValidateOurCoreBeliefs() {
        Assert.That(true, Is.True);
    }
}</pre>
<p>The other build compiles and runs both the unit tests and integration tests. We suspect this build will take a while and the sooner we could get feedback about the quality of the build, the better. We could push this build to a separate build agent too, but for right now they are all just backing up in the same queue.</p>
<p>The only missing piece of the puzzle so far is the Remote Control Server. The RC Server is a Java application that has to run on a machine with access to which ever browser you plan to test. Starting the server is simple enough. Just make sure Firefox.exe is in the path. If you forget, you&#8217;ll get a nice warning about it.</p>
<pre name="code">java -jar selenium-server.jar</pre>
<p>It&#8217;s up an running and when you run the above unit test, you see the browser window fly by and the server log all the actions it&#8217;s performing on the browser. </p>
<p>Great! &#8230;if you want to stay logged into your server with the console open, but I didn&#8217;t. Luckily, creating a Windows service is pretty easy. There is a great tutorial out there that walks you through <a href="http://fitnesse.org/InstallingFitNesseAsaService">how to setup a similar Java application as a service</a>. Just substitute the Selenium RC Server for the FitNesse server. Note that when I tried to install the Windows Server 2003 Resource Kit, on both Vista and Windows Server 2008, I got a compatibility warning. I ignored the warning since I was only using the two files and it worked great.</p>
<p>Now you can start and stop the Selenium RC Server via a Windows service, keep it running when you log out and start automatically when the server starts up. </p>
<p>Have fun.</p>
]]></content:encoded>
			<wfw:commentRss>http://fooberry.com/2009/01/23/getting-started-with-selenium/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
<enclosure url="http://seleniumhq.org/movies/intro.mov" length="9052981" type="video/quicktime" />
		</item>
		<item>
		<title>Automating the Build (Step 1 cont&#8217;d)</title>
		<link>http://fooberry.com/2008/09/09/automating-the-build-step-1-contd/</link>
		<comments>http://fooberry.com/2008/09/09/automating-the-build-step-1-contd/#comments</comments>
		<pubDate>Wed, 10 Sep 2008 01:16:58 +0000</pubDate>
		<dc:creator>mark</dc:creator>
				<category><![CDATA[TFS]]></category>
		<category><![CDATA[Unit Testing]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<category><![CDATA[build automation]]></category>
		<category><![CDATA[MSB]]></category>
		<category><![CDATA[MSBuild]]></category>
		<category><![CDATA[NUnit]]></category>
		<category><![CDATA[Team Build]]></category>
		<category><![CDATA[Visual Studio 2008]]></category>

		<guid isPermaLink="false">http://fooberry.com/?p=332</guid>
		<description><![CDATA[<br/>After the disappointing ending to my previous post, I now have much success to report. Once we had the correct path to the MSTest.exe on the build server, I was able to publish the results of my NUnit tests. There are a few things to note. You still need MSTest.exe on the build server. I [...]]]></description>
			<content:encoded><![CDATA[<br/><p>After the disappointing ending to <a href="http://fooberry.com/2008/09/05/automating-the-build-step-1/">my previous post</a>, I now have much success to report. Once we had the correct path to the MSTest.exe on the build server, I was able to publish the results of my NUnit tests. There are a few things to note.</p>
<ol>
<li>You still need MSTest.exe on the build server. I guess that is OK since we, at our organization, want to allow for the ability to run MSTests as well. I&#8217;m not 100% sure that happens on the build server or the TFS server.</li>
<li>As of now, if the NUnit tests fail, it will not run the MSTest. This is because we are executing the NUnit tests in the AfterCompile target as suggested in the<a href="http://www.codeplex.com/nunit4teambuild"> NUnit for Team Build</a> example. I&#8217;m not really sure why you would do both in the same solution, but if you do, you won&#8217;t see failures from both. Only one at a time. I&#8217;m looking into getting both to run, but that isn&#8217;t going to be much of a priority since we won&#8217;t need to run both in the same solution.</li>
</ol>
<p>I am really excited that we have this running with such little effort. Thanks has to go to the NUnit for Team Build guys.</p>
<p>One to step two when time allows.</p>
]]></content:encoded>
			<wfw:commentRss>http://fooberry.com/2008/09/09/automating-the-build-step-1-contd/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>What Am I Testing</title>
		<link>http://fooberry.com/2008/07/04/what-am-i-testing/</link>
		<comments>http://fooberry.com/2008/07/04/what-am-i-testing/#comments</comments>
		<pubDate>Sat, 05 Jul 2008 04:05:09 +0000</pubDate>
		<dc:creator>Mark</dc:creator>
				<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://fooberry.com/?p=38</guid>
		<description><![CDATA[<br/>I’ve been spending the better part of two days doing this same process over and over. It doesn’t feel like I’m testing anything of value. I am not doing it in the C# 3.0ish way, but it is better to explain it that way. I have a class and a façade (MyFacade) that I want to [...]]]></description>
			<content:encoded><![CDATA[<br/><p>I’ve been spending the better part of two days doing this same process over and over. It doesn’t feel like I’m testing anything of value.</p>
<p>I am not doing it in the C# 3.0ish way, but it is better to explain it that way. I have a class and a façade (MyFacade) that I want to extend and test.</p>
<pre name="code" language="csharp">
class Foo {
     public string Name { get; set; }
}

class MyFacade {
     public IMyDependency Depend { get; set; }
}

interface IMyDependency {
     IList&lt;Foo&gt; GetAllFoos();
}</pre>
<p>So I write my test first like a good boy person should. I know my façade should give me back a list of the Name properties from the Foo objects it knows about.</p>
<pre name="code" language="csharp">
[TestFixture]
public class MyFacadeTests {
    [Test]
    public void GetFooNames_ReturnsOnlyName() {
        FakeDependancy fake = new FakeDependency();
        MyFacade m = new MyFacade() { Depend = fake };
        Assert.That(m.GetFooNames(), Is.EquivalentTo(fake.FakeFoos.Select(x =&gt; x.Name)));
    }
}</pre>
<p>I need that FakeDependency, so I go ahead and create that. This would be a like my repository that will allow me to initialize the fake data.<br />
class FakeDependency : IMyDependency {</p>
<pre name="code" language="csharp">    // My local fake repository
    public IList&lt;Foo&gt; FakeFoos = new List&lt;Foo&gt;{
                new Foo{ Name="A"},
                new Foo{ Name="B"},
                new Foo{ Name="B"}};

    public IList&lt;Foo&gt; GetAllFoos() {
        return FakeFoos;
    }
}</pre>
<p>OK. So now that I have that, I add my GetFooNames stub to MyFacade.</p>
<pre name="code" language="csharp">class MyFacade {
    public IMyDependency Depend { get; set; }

    public IList&lt;string&gt; GetFooNames()
    {
        return null;
    }
}</pre>
<p>Run my test. It fails. Good. Now to implement that method….uhh I just copy my assert statement:</p>
<pre name="code" language="csharp">fake.FakeFoos.Select(x =&gt; x.Name)</pre>
<p>…replace “fake.FakeFoos” with “Depend.GetAllFoos()” and I get:</p>
<pre name="code" language="csharp">class MyFacade {
    public IMyDependency Depend { get; set; }

    public IEnumerable&lt;string&gt; GetFooNames() {
        return Depend.GetAllFoos().Select(x =&gt; x.Name);
    }
}</pre>
<p>Build it. Run it. It passes. What did I really test since I just copied the assert statement into the implementation body and changed the source? Did I test anything? That my copy code does the same thing in two places? Am I wasting time?<br />
I rolled it around with a friend and decided to take out the select in the assert statement and replace it with a declarative list so it would look like this:</p>
<pre name="code" language="csharp">Assert.That(m.GetFooNames(), Is.EquivalentTo(new[]{"A","B","C"}));</pre>
<p>That make me feel a little less &#8220;copy and pastey&#8221;, but now I have to know my fake is setup to give me three letters for the names. Let’s add a little bit to the fake to make it easier to configure. I am hesitant to do this since I don’t want to add code to my test classes, but I think in the end it is more readable than a more raw configuration.<br />
So I added this to my test class:</p>
<pre name="code" language="csharp">public FakeDependency With(int i)
{
    FakeFoos.Clear();
    for (int j = 0; j &lt; i; j++)
    {
        FakeFoos.Add(new Foo());
    }
    return this;
}

public FakeDependency Named(string name)
{
    for (int i = 0; i &lt; FakeFoos.Count; i++)
    {
        // We want them to be 1 based and not zero based
        FakeFoos[i].Name = string.Format("{0} {1}", name, i + 1);
    }
    return this;
}</pre>
<p>And use it in my test like this:</p>
<pre name="code" language="csharp">[Test]
public void GetFooNames_ReturnsOnlyName() {
    FakeDependency fake = new FakeDependency().With(3).Named("Fake");
    MyFacade m = new MyFacade() { Depend = fake };
    Assert.That(m.GetFooNames(), Is.EquivalentTo(new[]{"Fake 1","Fake 2","Fake 3"}));
}</pre>
<p>I’m a lot happier with that than copying the same code from the test to the implementation classes.</p>
]]></content:encoded>
			<wfw:commentRss>http://fooberry.com/2008/07/04/what-am-i-testing/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Unit Tests Everywhere</title>
		<link>http://fooberry.com/2008/06/30/unit-tests-everywhere/</link>
		<comments>http://fooberry.com/2008/06/30/unit-tests-everywhere/#comments</comments>
		<pubDate>Mon, 30 Jun 2008 14:19:58 +0000</pubDate>
		<dc:creator>Mark</dc:creator>
				<category><![CDATA[Unit Testing]]></category>
		<category><![CDATA[ReSharper]]></category>

		<guid isPermaLink="false">http://fooberry.com/?p=25</guid>
		<description><![CDATA[<br/>  Recently I’ve been able to extend my unit test code coverage as I’ve been introducing more features into our code base. I know this is something that should always be done, but for whatever reason, that’s not the case. What I’ve come to notice is our current method of organizing our unit test makes adding new [...]]]></description>
			<content:encoded><![CDATA[<br/><p> </p>
<p>Recently I’ve been able to extend my unit test code coverage as I’ve been introducing more features into our code base. I know this is something that should <em>always </em>be done, but for whatever reason, that’s not the case. What I’ve come to notice is our current method of organizing our unit test makes adding new features and test for new features awkward.</p>
<p>Currently our unit tests align perfectly with the class they test. So for example, if we have a class:</p>
<pre name="code" language="csharp">namespace MyCompany.Domain{
     public class Foo{}
}</pre>
<p><span class="code">We have, or should have, a test fixture in a separate assembly that looks like this:</span></p>
<pre name="code" language="csharp">
using MyCompany.Domain;
using NUnit.Framework;
namespace MyCompany.Domain.Tests{
    [TestFixture]
    public class FooTests{}
}
</pre>
<p><span class="code">This is probably a pretty typical strategy for organization. It is intuitive where to find tests for a type. Were I’m loosing my taste for this method is as the solution grows to several assemblies or layers, adding new unit tests for a specific feature becomes a scattered mess of changes. If I need to add a new field, I add new tests in the <span style="font-family: con;">UI.Tests</span>, the <span style="font-family: con;">Domain.Tests, Repository.Tests, Core.Tests</span>, etc.  Makes sense though right? You have to pass that new field through all the layers. I’m ok with the number of tests I need to write, but I don’t like having to go to eight different places to run them when I want to test my feature. It would be nice to align them them to the feature, or tag them in such a way I could find them easily. It <strong>could be that we are over layered and that is the real problem</strong>. We could be an <a href="http://www.imdb.com/title/tt0126029/">onion</a>.</span></p>
<blockquote><p>Shrek: Example? Okay, er&#8230; ogres&#8230; are&#8230; like onions. <br />
Donkey: [sniffs onion] They stink? <br />
Shrek: Yes&#8230;NO! <br />
Donkey: Or they make you cry. <br />
Shrek: No! <br />
Donkey: Oh, you leave them out in the sun and they turn brown and start sproutin&#8217; little white hairs.</p></blockquote>
<p>We are definitely an onion….or an ogre, but that’s a whole different analogy.</p>
<p>There is a nice <a href="http://www.code-magazine.com/Article.aspx?quickid=0805061">article in CoDe Magazine by Scott Bellware</a> that talks about BDD. Most of it I didn’t see as valuable to my every day activities until he started talking about <a href="http://code.google.com/p/specunit-net/">SpecUnit .Net</a>. It was, in theory, what I’ve been looking for. Align my tests with my features/defects/requirements / whatever. SpecUnit .Net does some nice human readable report generation that I don’t need, but why would I need a new tool when I could just categorize my tests in folders that line up with my real world problems.</p>
<p>That gets me close, but there is no way to run the entire category without using the command line. Still doable, but not as nice as ReSharper’s unit test runner. It would be nice to get a <em>Run all tests in this category</em> from the context menu, but I’m not sure if that would be easy to do across the different frameworks. Again it would be nice to save my unit test session so I don’t loose it every time I close the IDE.</p>
<p>While we’re dreaming, Maybe we could invert the relationship and make the class under test and attribute and the tests themselves could align directly with the requirements. Something like this for example:</p>
<pre language="csharp" name="code">
[Test][TypeUnderTest(typeof(Foo))] public void Correctly_Calculates_Bar(){
    //...
}</pre>
<p> </p>
<p>Or we could even get fancy with generics:</p>
<pre name="code" language="csharp">[Test&lt;Foo&gt;]
public void Correctly_Calculates_Bar(){
    //...
}</pre>
<p>The IDE, ReSharper or someone could let me run all the tests for Foo if I wanted. </p>
<p>After Josh’s comments I thought I would add a couple screen shots of using the Category attribute to group the tests as needed. You can apply the Category attribute to the method or to the TestFixture.</p>
<pre name="code" language="csharp">
    [TestFixture]
    public class MyClassTests {

        [Category("Add the ability to do work")]
        [Test] public void DoWork_WithNoArgs_DoesWork(){  }

        [Category("Add the ability to do additional work ")]
        [Category("Add the ability to do work")]
        [Test]
        public void DoWork_WithAllArgs_DoesWork() {   }
    }</pre>
<p> </p>
<p>You can select Categories from the unit test runner’s <em>Group by:</em> combo box.</p>
<p><a href="http://geekswithblogs.net/images/geekswithblogs_net/OntologicalReciprocity/WindowsLiveWriter/UnitTestClutter_B289/image_2.png"><img title="image" src="http://geekswithblogs.net/images/geekswithblogs_net/OntologicalReciprocity/WindowsLiveWriter/UnitTestClutter_B289/image_thumb.png" border="0" alt="image" width="381" height="193" /></a></p>
<p>It then will group your tests by their category. I did find the UI a bit buggy. At first it wasn’t applying the grouping, but after a couple attempts they started to show up.</p>
<p><a href="http://geekswithblogs.net/images/geekswithblogs_net/OntologicalReciprocity/WindowsLiveWriter/UnitTestClutter_B289/image_4.png"><img title="image" src="http://geekswithblogs.net/images/geekswithblogs_net/OntologicalReciprocity/WindowsLiveWriter/UnitTestClutter_B289/image_thumb_1.png" border="0" alt="image" width="404" height="190" /></a></p>
<p>Thanks again Josh. That will keep me content for the time being. Now if I could only inspect the entire solution for tests in the category I would <em>really</em> happy.</p>
]]></content:encoded>
			<wfw:commentRss>http://fooberry.com/2008/06/30/unit-tests-everywhere/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
