Sunday, November 28, 2010

Unit Testing an ASP.NET Website

If you are accustomed to building ASP.NET Web Applications using TDD, you might find yourself perplexed when you sit down to work on a client’s ASP.NET Website project and try to run your first test.

In my case I hit the key command I have mapped to ReSharper’s test runner expecting to promptly see a window showing me a nice red test. After watching an icon spin for a minute I did what every awesome developer does, I blamed Studio, killed devenv.exe and tried it all over again. Same results.

It finally occurred to me that issue was that an ASP.NET Website has no DLL output for NUnit to load and run against. Whatever is a TDD fanatic to do without testing first? After typical developer style complaints about “having to work under these conditions,” I hacked together a page where I could give it a list of types representing each test fixture classes and have it render an HTML page somewhat representing the output I have come to expect from the GUI test runner.

Now I could simply navigate to http://localhost:1234/Website/UnitTests.aspx and run my tests. I recently reworked it to dynamically load the test fixtures from the assembly and thought I would post a sample solution.

Remember not to deploy the NUnit Framework DLL or the App_Code/UnitTests directory to your production site.

I have uploaded the source to my GitHub repository.

Working with JSON Values that are C# Reserve Words.

While playing around with GitHub’s API for Gists, I discovered I couldn’t simply deserialize into an object because the API used the C# reserve word “public” as a property name. Luckily, the DataMember attribute has a “Name” property that allows to you explicitly map a JSON property to your object’s property of a different name:

   1:  namespace MyGistClient
   2:  {
   3:      [DataContract]
   4:      public class GistsResult
   5:      {
   6:          ...
   7:   
   8:          [DataMember(Name = "public")]
   9:          public bool IsPublic { get; set; }
  10:   
  11:          ...
  12:      }
  13:  }

While C# will let me make a property named “Public”, I decided to use “IsPublic” instead so I don’t have any issues if my object gets consumed by another .NET language that isn’t case sensitive.

Follow me on App.net