Wednesday, February 18, 2009

MSTest XSLT

I am sure someone out there may find this useful. Its an XSLT to transform the TRX file that is output by the MSTest runner. Its a slightly better visual depiction than my MSBuild output of thousands of lines of courier new text...

This is very much "It works on my computer", I am running VS 2008 Team edition (?). Let me know if this works for you.

<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                xmlns:vs="http://microsoft.com/schemas/VisualStudio/TeamTest/2006">
  <xsl:template match="/">
    <html>
      <body style="font-family:Verdana; font-size:10pt">
        <h1>Test Results Summary</h1>
        <table style="font-family:Verdana; font-size:10pt">
          <tr>
            <td>
              <b>Run Date/Time</b>
            </td>
            <td>
              <xsl:value-of select="//vs:Times/@creation"/>
            </td>
          </tr>
          <tr>
            <td>
              <b>Results </b>
            </td>
            <td>
              <xsl:value-of select="//vs:Deployment/@runDeploymentRoot"/>
            </td>
          </tr>
        </table>
        <a href="coverage.htm">Coverage Summary</a>
        <xsl:call-template name="summary" />
        <xsl:call-template name="details" />
      </body>
    </html>
  </xsl:template>
  <xsl:template name="summary">
    <h3>Test Summary</h3>
    <table style="width:640;border:1px solid black;font-family:Verdana; font-size:10pt">
      <tr>
        <td style="font-weight:bold">Total</td>
        <td style="font-weight:bold">Failed</td>
        <td style="font-weight:bold">Passed</td>
      </tr>
      <tr>
        <td >
          <xsl:value-of select="//vs:ResultSummary/vs:Counters/@total"/>
        </td>
        <td style="background-color:pink;">
          <xsl:value-of select="//vs:ResultSummary/vs:Counters/@failed"/>
        </td>
        <td style="background-color:lightgreen;">
          <xsl:value-of select="//vs:ResultSummary/vs:Counters/@passed"/>
        </td>
      </tr>
    </table>
  </xsl:template>
  <xsl:template name="details">
    <h3>Unit Test Results</h3>
<table style="width:640;border:1px solid black;font-family:Verdana; font-size:10pt;">
      <tr>
        <td style="font-weight:bold">Test Name</td>
        <td style="font-weight:bold">Result</td>
      </tr>
      <xsl:for-each select="//vs:Results/vs:UnitTestResult">
        <tr>
          <xsl:attribute name="style">
            <xsl:choose>
              <xsl:when test="@outcome = 'Failed'">background-color:pink;</xsl:when>
<xsl:when test="@outcome = 'Passed'">background-color:lightgreen;</xsl:when>
              <xsl:otherwise>background-color:yellow;</xsl:otherwise>
            </xsl:choose>
          </xsl:attribute>
          <td>
            <xsl:value-of select="@testName"/>
          </td>
          <td>
            <xsl:choose>
              <xsl:when test="@outcome = 'Failed'">FAILED</xsl:when>
              <xsl:when test="@outcome = 'Passed'">Passed</xsl:when>
              <xsl:otherwise>Inconclusive</xsl:otherwise>
            </xsl:choose>
          </td>
        </tr>
      </xsl:for-each>
    </table>
  </xsl:template>
</xsl:stylesheet>

Tuesday, February 17, 2009

Rhino Mocks: AAA vs Record- Playback

Rhino Mocks is one of my favourite pieces of open source software. It has, more than any other piece of code, changed the way I code, for the better, I hope.
Many moons ago I first played with it and like the fact it was strongly typed, NMock2 was the mock framework I was using at the time and it is string based, which can lead to havoc when refactoring.
Back in those days RhinoMocks was only Record-Playback and to be honest it never felt natural to me. Due to popular demand the framework was extended to allow for either the record play back or IMO the more natural AAA syntax

Arrange - Act - Assert

Arrange, Act, Assert to me help break up the way I write my test to make it very clear what I am trying to achieve. I even have code snippets that auto populate my test. I type "mstest" and i get

[TestMethod]
public void Can()
{
//Arrange
//Act
//Assert
Assert.Inconclusive("Test not completed");
}

I also feel this allows newcomer to see what is going on more clearly and also helps them write test first.
How?
Well, in my mind the hardest thing to do when starting TDD is knowing what to write! If you have the code stub with comments as above, it gives you a visual guide to nudge you into progress.


I also find it helps if n00bs actually write the ACT part first, not the ARRANGE. Typically this involves writing 2 lines of code



  • create the object and

  • call the method you want to test


eg:

[TestMethod]
public void CanValidateCustomerFromCustomerAddPresenter()
{
//Arrange
//Act
var presenter = new CustomerPresenter(view,service);
presenter.Validate(customer);
//Assert
Assert.Inconclusive("Test not completed");
}

The fact the above code wont even compile is irrelevant. It shows intent. Now the developer writing the test has a clear direction of what they need to do. Often this way of TDD fleshes out new tests. To me this (incomplete and fictitious) test straight away is crying out for complimentary tests: eg CanNotValidateCustomerFromCustomerAddPresenterWithNullCustomer etc etc
The fact that I have not even defined what a customer is, means my mind is still open to possibilities.
On top of the benefits of writing the ACT first, I think AAA syntax makes the test more readable in terms of maintaining code bases, as it has the top down procedural look that coders are used to (even OO has top down).


[TestMethod]
public void CanValidateCustomerFromCustomerAddPresenter()
{
//Arrange - Set up mocks (put in your TestInitialize)
var view = MockRepository.GenerateMock<IView>();
var service = MockRepository.GenerateMock<IService>();
//Arrange - Set up your parameters & return objects
var customer = TestFactory.CreateVaildCustomer();
//Arrange - Set up your expectations on your mocks
view.Expect(v=>v.ShowValidation(customer));
service.Expect(s=>s.Validate(customer)).Return(ValidationFactory.Success);
//Act
var presenter = new CustomerPresenter(view,service);
presenter.Validate(customer);
//Assert
view.VerifyAllExpectations();
service.VerifyAllExpectations();
}


Now I have not run this thru a compiler I just threw this down, but to me this is pretty readable. I used Record-playback only for a few months and found it a little confusing, perhaps my pitiful little brain was maxing out on simple syntax, but hey.
If you are not using AAA try it out, it works great with the C# lambda expressions too (as above) which, to me, means you have incredibly readable tests.



*please ignore the fact the test is odd.. I am trying to show readability as opposed to how to write a crap object ;)
**is it incredibly obvious that i am writing MVP triplets ? ;)

Monday, February 16, 2009

Technical Debt

Having first heard the term from a former colleague that summed up the project we were one very well, this video by Ward Cunningham struck a chord with me.

Tuesday, February 10, 2009

Perth Alt.net: Tonight!

Just a remnder that we are meeting at 43below on Barrack Street in the city at 5:30 thonight (11th feb 09).
Be there or... well, or dont be there.

Stuff to play with

More stuff i am looking at:

  • Android dev... very exciting i will finally be able to do some real world dev in my osx environment
  • I will be starting to use GIT* due to android dev with my java mates... should be interesting. * this bring me up to using 4 different SCMs at the moment... bloody hell.
  • Automocking from the Jimmy Bogard. This looks to be a great help in the mismatch between dto and domain object. Used with the NH fluent interface for mapping life could be significantly easier :)


Some links:
Fellow OzAlt.netter post on GIT : http://www.paulbatum.com/2009/02/im-starting-to-git-it.html

Monday, February 9, 2009

Real World Test Driven Development: Unit Testing Enterprise Solutions

Join us at the Perth .NET Community of Practice, Thursday March 5th to hear Rhys Campbell present on the essentials of TDD and how encourages good software design as opposed to just having tests. Rhys will cover the differences between unit, acceptance and integration tests, why conventional unit test examples often do not work in the real world, what to test and what to mock, automating your tests, coding examples of how to use Mocks, Stubs, Fakes, Dummies and Spies... what are they and how do they help me.

TOPIC: Real World TDD with Rhys Campbell
DATE: Thursday, March 5th, 5:30pm
VENUE: Excom, Ground Floor, 23 Barrack Street, Perth
COST: Free. All welcome

Rhys Campbell is a software developer currently contracting in Perth, WA. He recently returned from London, where he has been active in the .NET community, attending and speaking at the 2008 Seattle and London Alt.NET Open Spaces. Rhys is interested in design, architecture, patterns and bringing best practices from other communities to .NET. Rhys is a director of ArtemisWest.

There will be door prizes of a ReSharper license (courtesy of JetBrains) and T-Shirts (courtesy of Redgate).

http://perthdotnet.org/blogs/events/archive/2009/02/08/real-world-test-driven-development-unit-testing-enterprise-solutions.aspx

Sunday, February 8, 2009

Singleton Pattern

I am not a fan of the singleton pattern. This may come as a surprise to some, as the very first thing that people may see when using my code is the wrapper I have for my IOC container acts as a singleton.

So why do I, along with many others, not like the singleton? Because it is usually used incorrectly and hard to test.

The first time I had seen massive singleton abuse was when I had to go on a consulting gig to help "finish" a project, i.e. the final sprint prior to go live. The whole data access layer was made up of a mess of singletons. There was no need for it, none for the objects had state let alone required to hold state in a single instance but they would not let us, the hired consultants, refactor it out. Bizarre*. Since then I have seen a singleton butcher-job at just about every contract I have had. it seems to be the first pattern people use and the first to be abused.

So when do i use a singleton? Well when an object that should only have one instance. The notion of singleton implies there is only one logical possible instance of that type that can be in creation at a time. I think this is the fundamental problem I regularly see. Most times I see the use of a singleton this is just not the case.

To highlight this even more, often the object itself does not even have state. If the type has no possible (instance) state, then there is surely no need for singular state! This is the time where the object is just a static class. In the same way it is ok to use singletons, it is ok to use static classes, just make sure it is the right circumstances for your choice.

One annoyance is when singletons are used so they can be "thread safe" and then the construction of the object is not thread safe. please investigate how to do this if this is actually a concern. Even better use an IoC container! By using an IoC the object becomes easily testable and you infrastructure concerns are hidden from the consumer. To me, this is a good thing. :)

*That project is still going, still not live and apparently still has singletons used inappropriately in the data access layer. Oh well.