ASP .NET Unit Testing


ASP.NET developers have long searched for an easy, effective tool for unit testing their code. Typemock Isolator has come to the rescue by making it easy to test ASP.NET or ASP.NET MVC code without changing it.

The problem with unit testing ASP.NET
ASP.NET and ASP.NET MVC are the ways to write website code on Windows. The problem is that both rely on having a web server in place which makes testing a real challenge. The web server objects are hard to simulate because of their static nature, and so most automated testing is relegated to browser automation. Needless to say, these tests are slow, and cannot give the immediate feedback that unit tests provide. So how can we resolve these issues and unit test our ASP.NET web code effectively and easily? 

Typemock Isolator’s solution
Unit testing ASP.NET and ASP.NET MVC code require isolation from the web server. With Typemock Isolator you can write unit tests for your server components, without opening a browser. Isolator helps simulate the HttpContextSession and other objects so your tests run quickly, isolated from the web server and the client code, to give you the confidence that your code is working correctly…even before it loads into the browser!

If this is still not sufficient and you’d like to test code-behind of ASP.NET pages, you can also use Ivonna, the web add-on to Isolator. With Ivonna, you‘ll get even easier APIs to simulate everything you need to test code-behind pages, like event handlers or the Page object.

Isolator’s ASP.NET unit test in action
Let’s look at an example. We have a class that takes inputs and composes tags for them to send to the client. Let’s examine the WriteBoldNameToBrowser method:


public class ResponseWriter

How can we test that the method works correctly? There are two problems with testing it:

  1. We need a web server that can return a valid HttpContext to run it.
  2. Without a browser, we can’t really know if that correct tag was sent to the client.

Let’s now see how we can test it with Isolator:

Note that we use Isolator for two purposes. The first is to fake HttpContext and any of its called variables. Using a Recursive Fake every object, starting from the HttpContext root is faked by default – no need to build a tree of fake objects. That means no NullReferenceException from the Response property or its Write method. The second is that, instead of analyzing HTML code, we can simply make sure that the Write call was made with the correct arguments, using Isolate.Verify APIs. We now have an easy, quick and readable ASP.NET unit test!

Download a free trial of Typemock’s ASP.NET Unit Testing tool to start writing your own ASP.NET tests or click through our resources below for all the information and support you need to effectively unit test in ASP.NET.

ASP.NET Unit Testing Resources: