Equinox IT Blog

What’s new in unit testing with Visual Studio 2012

A few weeks ago I had the opportunity to embrace my geekiness and attend my very first IT conference. I attended a range of talks at TechEd 2012, my favourite being ‘What’s new in Unit Testing’ by Rob Maher. 

Microsoft have introduced a few new improvements for unit testing with Visual Studio 2012. The one that caught my attention the most is the introduction of Shims. The best way to explain it is with an example. If you had the following method…

public void Save(Client client)
{
    client.lastUpdated = DateTime.Now;
    repository.Save(client);
}

Since DateTime.Now will return a different value every time it is called, how would you go about testing whether the lastUpdated property is what we expect it to be?

With Shims it’s very easy. You can override the Now getter for DateTime using ShimDateTime.NowGet.

For example...

using (ShimsContext.Create())
{
    ShimDateTime.NowGet = () =>new DateTime(2012, 1, 1);
    //set up test data and call save method
    Assert.AreEqual(new DateTime(2012, 1, 1), testClient.lastUpdated);
}

Wrapping the ShimDateTime.NowGet call inside a using statement means that the DateTime override you specified will only be used within the using statements open and closed brackets. E.g. calling DateTime.Now within the using statement will return the 1st January 2012, however using it outside of the using statement will return the current date and time.

In order to get started with Shims you need to add a fakes assembly. Select the reference to the assembly you want to fake. E.g. for our DateTime example above we would select the System.dll reference in Solution Explorer. Then choose ‘Add Fakes Assembly’.

One thing I should mention, Shims are only available in Visual Studio 2012 Ultimate.

Microsoft have also introduced the keywords ‘async’ and ‘await’. These two keywords make it a lot easier to code asynchronous methods. The good news is that you can also use these keywords in your unit tests to test asynchronous code.

Free recorded webinar: Testing is key to your agile software development success

Subscribe by email