Friday, March 7, 2008

ASP.Net Unit Testing in VS.Net 2005

Let us focus on test Presenter in MVP, including Code-Behind and explicitly declared Presenter class..


Presneter Code:


public interface IGMWBView
{
void UpdateGMWBFields();
}
public class GMWBPresenter
{
private bool _ShowNextStepUpDate;
public bool ShowNextStepUpDate
{
get { return _ShowNextStepUpDate;}
set { _ShowNextStepUpDate = value;}
}
public void UpdateGMWBView(IGMWBView view)
{
BindToDomainModel();
view.UpdateGMWBFields();
}
public void BindToDomainModel()
{
ShowNextStepUpDate = true;
}
}

Code-behind:


public partial class _Default : System.Web.UI.Page, IGMWBView
{
protected void Page_Load(object sender, EventArgs e)
{
_Presenter = new GMWBPresenter();
}
protected void Button1_Click(object sender, EventArgs e)
{
this.lbNextStepUpDate.Text = "Changed";
_Presenter.UpdateGMWBView(this);
}
public GMWBPresenter _Presenter ;
#region IGMWBView Members
public void UpdateGMWBFields()
{
}
#endregion


Unit Test Code:


[TestMethod]
[HostType("ASP.NET")]
[UrlToTest("http://localhost/TDDASPNet1.Web/Default.aspx")]
public void CSRCanSeeNextStepUpDate()
{
Page p = ctx.RequestedPage;
Label lb = (Label) p.FindControl("lbNextStepUpDate");
Assert.IsTrue(lb.Visible, "Lable hidden for CSR");
PrivateObject pObj= new PrivateObject(p);
pObj.Invoke("Page_Load", null, EventArgs.Empty);
pObj.Invoke("Button1_Click",null,EventArgs.Empty);
Button btn = (Button)p.FindControl("Button1");
Assert.IsTrue((lb.Text == "Changed"), "Button click failed " + lb.Text);
GMWBPresenter gmwb= (GMWBPresenter) pObj.GetFieldOrProperty("_Presenter");
Assert.IsTrue( gmwb.ShowNextStepUpDate ,"OOps");
}
General Pattern:

/// (1) Set Url
/// (2) Get the page Object
/// (3) using PrivateObject to Invoke: Page_Load, Click
/// this should call Presenter entry pointer.
/// (4) Get Presenter as property and test its properties.

This will allows us to do Unit Tests by calling server code