Friday, June 20, 2008

UnitTesting an ASP.NET Web Application Project

Having a solution named 'UnitTestingASPNETwebApp'
, with an ASP.NET Web Application Project named 'MyWebApplication'
and a Test Project with name 'MyWebApplication.UnitTests'
, U can test the 'Page_Load' method of a webform 'Default.aspx'
using 1 of following testmethods


[TestMethod()]
[HostType("ASP.NET")]
[AspNetDevelopmentServerHost("UnitTestingASPNETwebApp\\MyWebApplication", "/")]
[UrlToTest("http://localhost:3798/Default.aspx")]
[DeploymentItem("MyWebApplication.dll")]
public void Page_Load__OnChangeTitle_Succeed()
{
_Default_Accessor target = new _Default_Accessor();
target.Page_Load(null, EventArgs.Empty);
Page p1 = target.Target as Page;
Assert.AreEqual(p1.Title, "My Home Page");
}


[TestMethod()]
[HostType("ASP.NET")]
[AspNetDevelopmentServerHost("UnitTestingASPNETwebApp\\MyWebApplication", "/")]
[UrlToTest("http://localhost:3798/Default.aspx")]
[DeploymentItem("MyWebApplication.dll")]
public void Page_Load__OnChangeTitle2_Succeed()
{
Page p2 = this.TestContext.RequestedPage;
PrivateObject po = new PrivateObject(p2);
po.Invoke("Page_Load", p2, EventArgs.Empty);
Assert.AreEqual(this.TestContext.RequestedPage.Title
   , "My Home Page"
   );
}



Default.aspx's codebehind class '_Default' looks like

public partial class _Default : Page
{
protected void Page_Load(Object sender, EventArgs e)
{
this.Title = "My Home Page";
}
}

No comments: