Freekshow

June 26, 2008

Unit testing with Visual Studio 2008 – Part 2

Filed under: Microsoft,Unit Testing — Freek Leemhuis @ 3:03 pm
Tags:

This is the second part of a series of blogpost on unit testing. Find the first part here.

In the first part we’ve introduced the MS Test framework, and I realise now that I’ve left out a few bits and pieces, so first off let me try to make amends. 

Initialize and Cleanup

Many times when running a test you’ll want to set up some conditions under which the test will run. After completion you’ll want to clean up these artifacts. Similarly to NUnit, where you’ll find attributes as [Setup] and [TearDown], MS Test has some attributes you can use to accomplish this.

To set up state before every test method in a test class, you can decorate a method with the [TestInitialize] attribute. Similarly, to clean up you can use the [TestCleanup] attribute.

For example, suppose you are testing some xml parsing routines. If you are testing agains some sample xml fragment, and it’s the same fragment for all your test methods in a class, you can set the fragment using the [TestInitialize] attribute:

private MyDataContext db; 

[TestInitialize()]
private void TestInit()  
{
     db = new MyDataContext(
        ConfigurationManager.ConnectionStrings["TestDatabase"].ConnectionString);
     db.Connection.Open(); 
}

 
Similarly, you can use the [TestCleanup()] attribute to dispose of any state.

[TestCleanup()]
private void WrapUp()
{
       db.Dispose();
       db = null;
}

Note: you only use a db connection setup like this when testing data access routines. For any other routines you do not really want the tests to hit the database.

So that’s pretty convenient: you don’t have to add the initialization code in the methods themselves. However, the opening and closing of the database will occur as many times as there are test methods in your test class.

You can use the [ClassInitialize] and [ClassCleanup] attributes for state changes that will execute only once for all test methods within a test class. However, for methods to use these attributes they must be static, which means that you can not use it to set properties on the instance of the test class.

Testing for exceptions

A lot of times I’ve seen developers using a try/catch block to test for exceptions. Joel for example has posted this little code snippet:

[TestMethod]
public void TestZipCodeNotNumericThrowsArgumentException()
{
       TransactionRequestInfo req = new TransactionRequestInfo();
       string testValue = "034JB";
       try
       {
           req.Zip = testValue;
           Assert.Fail("Exception not thrown.");
       }
       catch (ArgumentException aex)
       {
           Assert.IsTrue(true, "Exception Thrown Properly");
       }
}

You can see what he’s trying to do, and I’ve seen many a test use this approach. There is a better way: let’s rewrite this using the appropriate ExpectedException attribute:

[TestMethod]
[ExpectedException(typeof(ArgumentException))]
public void TestZipCodeNotNumericThrowsArgumentException()
{
    TransactionRequestInfo req = new TransactionRequestInfo();
    string testValue = "034JB";
    req.Zip = testValue;
}

You can see it pays to investigate the full capabilities of the testing framework. Note that one would probably want to use a more specific exception than ArgumentException (InvalidZipcodeException?), but that’s for another post and another day.  

On cleanup and debugging

When dealing with databases, you might on occasion use a method with the TestInitialize attribute to verify preconditions in the database, and similar you have a cleanup routine to remove any artifacts. What happend to me on more than one occasion when starting with unit tests is that I would run tests under debugging, and when an expection occurred I would stop the debugging session. This however would prevent execution of any cleanup routine, and the state would not be properly reset before the following test run. Be sure to continue debugging to allow your cleanup code to execute!  

Keyboard Shortcuts

To wrap up the specifics of the MS Test frameworks, here’s a list of keyboard shortcuts to run your tests. The running of tests through the test windows is a bit cumbersome to navigate, so these keyboard combinations will come in handy:

CTRL + R, then press T
This runs the test(s) in the current scope. That is, it runs the current test method, all the tests in the current test class, or all the tests in the namespace, respectively.

CTRL + R, then press CTRL + T
This also runs the test(s) in the current scope, but under debugging.

CTRL + R, then press C
This runs all the tests in the current test class.

CTRL + R, then press A
This runs all the tests in the solution.

Resources

MSDN documentation on Unit Testing

Write Maintainable Unit Tests That Will Save You Time And Tears (MSDN article by Roy Osherove)

If you’re looking for a good book on unit testing, I can recommend Pragmatic Unit Testing in C# with NUnit , by Andrew Hunt and David Thomas. The authors use nUnit as the test framework, but the methods and practices apply regardless of what framework you use.

Roy Osherove shares his thoughts on unit testing and his upcoming book on The Art of Unit Testing/


Advertisements

June 2, 2008

DevDays 2008 impressions

Filed under: .Net,ADO.Net Data Services,Entity Framework,Events,Microsoft — Freek Leemhuis @ 1:31 pm

Keynote

The keynote this year was titled ‘Why Software Sucks’, by .Net professor David Platt. I’ve missed most of it while lining up to get tickets (thanks Mark ;-)) , but it was basically the same session that Platt has been delivering for a number of years now, most recently in TechEd Barcelona in 2007, and I was a bit surprised when I found out this talk was now promoted to keynote for the DevDays. Must have been a slow day at the office for original content or new announcements….
If you’ve not seen Platt’s talk before, it’s pretty entertaining. You can watch it (from a similar session) online here.

Silverlight 2.0

The session from Daniel Moth was about Silverlight 2.0. Where previous versions of Silverlight were all about media, video delivery etc, you could only program in javascript to make things happen. With version 2.0 you can finally write managed code to run in the browser. This, combined with the power of XAML makes for a very compelling platform to deliver RIA’s (most self-respecting conferences these days includes a RIA (Rich Internet Application) track). Silverlight 2 of course was announced during Mix, so if you want to check it out go watch the sessions on Silverlight on sessions.visitmix.com. They’ve recently redone the sessions so that the streaming includes the presenter as well as a separate stream to show the slides and demo’s.

The ADO.Net Entity Framework

The ADO.Net Entity Framework session from Mike Taulty was a good introduction into the subject. Mike pointed out a new website www.datadeveloper.net where you can find news, tutorials and other resources on new data technologies such as the Entity Framework and the ADO.Net Data Services. I was a bit puzzled when Mike spend considerable time of his session on how you can still use the old-fashioned ADO api (datareader, command) to program against the EF. I can think of only a small number of cases when you’d want to do that.
Check out this webcast for more details on the EF.

WCF on the Web

For me, the most interesting session of the day was delivered by Peter Himschoot, who showed what additional work has been done in WCF for the web in version 3.5. More specifically, WCF now supports JSON and REST. It’s interesting to see that a framework like WCF has been designed to a high enough level of abstraction that, while it was build when services were all very much soap-oriented, it has now been extended to include new concepts like JSON and REST.

ASP.Net MVC Framework

On the Friday, Alex Thissen kicked off with an introduction to the MVC framework. The MVC framework will be an alternative to the current asp.net webforms model. It allows the programmer to control the HTML markup, rather then having it generated by user controls. It does away with postback and viewstate, so you get a much cleaner model, that allows for better Separation of Concerns and better testability. As always, Alex is very thorough and I was impressed to see he managed to sprinke Unity and Moq in his demo without loosing the audience.

LINQ to SQL

Next up was Anko Duizer who discussed various options to include LINQ to SQL in your architecture. Do you regard LINQ to SQL as your data layer, or do you just use it as part of your datalayer? This was a good follow-up to Anko’s previous introductory sessions on LINQ to SQL, and it addressed some of the difficulties that you can run into when you need to figure out the best practices for leveraging LINQ and LINQ to SQL.

ADO.Net Data Services

Mike Taulty then had another session, this time on the ADO.Net Data Services (codename Astoria). Using this technologie you can take a data model like LINQ to SQL or an Entity Framework model, and make the classes available through REST-based services. The framework will be made available in service pack 1 for Visual Studio 2008, currently in beta.

Rosario

Marcel de Vries showed some of the new features of Rosario, the upcoming new version of Visual Studio and the .Net framework. His talk focused mostly on Team System. The primary goal of the new Rosario features is to bring together the three main stakeholders of a software project — business and IT governance, IT operations and development. Some of the new features include:

historical debugging: a new testrunner application allows a tester to record test runs, which can then be replayed on a programmer’s machine, thereby reproducing the bugs that the tester has stumbled upon, but also creating a debug session where there previously was none!
This should get rid of some ‘but it works on my machine’ discussions….

Functional testing– codename Camano- : a test manager for running functional tests. It provides test execution assistance, workflow, rich bug logging and reporting.

Marcel also showed some features of the Team Architect edition, that now includes… UML support! Ever wished you could generate a sequence diagram from existing code? I had noticed this through Clemen’s blog and I’m a bit puzzled to see Microsoft performing this U-turn, where they have previously stayed well away from anything related to UML. I’m intrigued enough to go and try this out to see how valuable the additions will be.

Dynamic languages and the DLR

Finally, I managed to catch Harry Pierson‘s session on dynamic languages and the Dynamic Language Runtime (DLR).  I have a fascination for the differences between different programming languages and paradigms, and the initiative from Microsoft to enable the use of existing dynamic languages on the .Net platform is a very interesting one.

The question many people who are using a statically typed language on the .Net platform will pose is: why would I want to (also) use a dynamic language. Harry really brought it home to me: with the DLR and the supported languages Microsoft aims for the developer that is currently using Python or Ruby, and get them on board by making it easy for them to switch to the Microsoft platform.

So, if you’re not currently using dynamic languages, should you care about this stuff? Well, if you are a believer in polyglot programming you should. This is the idea that within an application you would use multiple languages, and you select the language that is best fits the particular concern you’re trying to address. For example, in a Model-View-Controller application, you would write the view in HTML and javascript, the controller using a dynamic language like IronPython and the model in a statically typed language like C#. Read the chapter on polyglot programming in the recently released Thoughtworks Anthology for more information.

One interesting thing to note on the DLR is that the original plan for the DLR was to release it with four languages that were going to be supported: IronRuby, IronPython, JavaScript and VBX, where the last one was a new dynamic variant of Visual Basic. The last one has now apparently been dropped, and the DLR will be released initially with just the first three languages. It looks like Microsoft has not yet made its mind up considering the future of VB. 

When .Net first came out, the differences between the implementations of VB and C# were surprisingly few, and the choice of customers between these two would invariably hinge on the history and familiarity of their existing programmers base, rather then on the merits of the particular language.  With the recent additions in VB like xml literals, these languages seem to start to drift apart again, and I would very much like to see people preferring one over the other because they like the language features better, not just because it’s what they are used to.

So the question is, will Microsoft rediscover VB as a dynamic language? That’s why I was curious to see how the VBX implementation for the DLR was taking shape…. I spoke to Harry about this, and he was rather tight-lipped about it but hinted that we might get an announcement on these issues at the upcoming PDC.

And so..

All session on DevDays were recorded on video, so I’ll keep you posted when materials will be made available online. If you attended, let me know what you thought…

 

Create a free website or blog at WordPress.com.