Thursday, November 10, 2011

Testing ASP.NET Webforms

ASP.NET web forms are challenging to test, because the code and UI logic are sprinkled together.

Nonetheless, if you are stuck with legacy code - what do you do?
Here are some of the options I was thinking of:

1) HttpSimulator allows you to simulate the HttpContext.

For example, to simulate a GET request for the web root of your application, you would write:

public void CanGetSetSession()
using (new HttpSimulator("/", @"c:\inetpub\").SimulateRequest())
HttpContext.Current.Session["Test"] = "Success";
Assert.AreEqual("Success", HttpContext.Current.Session["Test"]);

2) NunitAsp : a cool mock framework, but doesn't seem to be actively maintained.

Here is how you could imitate clicking on buttons in an ASP form.

public void TestExample()
// First, instantiate "Tester" objects:
LabelTester label = new LabelTester("textLabel");
LinkButtonTester link = new LinkButtonTester("linkButton");
// Second, visit the page being tested:
// Third, use tester objects to test the page:
Assert.AreEqual("Not clicked.", label.Text);
Assert.AreEqual("Clicked once.", label.Text);
Assert.AreEqual("Clicked twice.", label.Text);

3) Use Cassini DLL (built-in VS web server) in your code, and explicitly start its instance in your unit tests. Scott Hanselman describes how this could be done.


public void Setup()


//Extract the web.config and test cases (case sensitive!)




//NOTE: Cassini is going to load itself AGAIN into another AppDomain,

// and will be getting it's Assembliesfrom the BIN, including another copy of itself!

// Therefore we need to do this step FIRST because I've removed Cassini from the GAC

//Copy our assemblies down into the web server's BIN folder


foreach(string file in Directory.GetFiles(tempPath,"*.dll"))


string newFile = Path.Combine(tempBinPath,Path.GetFileName(file));

if (File.Exists(newFile)){File.Delete(newFile);}



//Start the internal Web Server

webServer = new Server(webServerPort,webServerVDir,tempPath);

webServerUrl = String.Format("http://localhost:{0}{1}",webServerPort,webServerVDir);


//Let everyone know

Debug.WriteLine(String.Format("Web Server started on port {0} with VDir {1} in physical directory {2}",webServerPort,webServerVDir,tempPath));


public void BasicSmokeTestOfWebServer()
string result = GetPage("test1.aspx");
Assert.IsTrue(result.IndexOf("Hello") != -1,"Basic smoke test of test1.aspx didn't find 'Hello' in response!");

And my choice is #2 or #3.



Itz Really a very useful blog post....thank you very much Admin...
I found a really nice post.

Aking Web Tech a leading IT company & Provides web services :- website Development in just 1,999 Rs/-, software development like {Billing software, School Management Software, Inventory Software, ERP, CRM}, Domain & Hosting , SEO
software companies in indore

Post a Comment