Brian Orrell's Blog
My Links
Blog Stats
  • Posts - 30
  • Stories - 0
  • Comments - 13
  • Trackbacks - 4
Archives
Post Categories
Image Galleries
Blogroll

Say you have a page like this:

<asp:TextBox ID="NameTextBox" runat="Server" /><asp:Button ID="SubmitButton" Text="Submit" runat="server" OnClick="SubmitButton_Click" />
<asp:Label ID="MessageLabel" runat="server" />

With the following code behind.

using System;

namespace AspUnitTest

{

    public partial class _Default : System.Web.UI.Page

    {

        protected void SubmitButton_Click(object sender, EventArgs e)

        {

            MessageLabel.Text = string.Format("Hello, {0}", NameTextBox.Text);

        }

    }

}

Create a unit test with the following code to test it.

using Microsoft.VisualStudio.TestTools.UnitTesting;

using Microsoft.VisualStudio.TestTools.UnitTesting.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System;

 

namespace AspUnitTest.Test

{

    ///

    /// Summary description for DefaultAspxTest

    ///

    [TestClass]

    public class DefaultAspxTest

    {

        private TestContext testContextInstance;

 

        public TestContext TestContext

        {

            get { return testContextInstance; }

            set { testContextInstance = value; }

        }

 

 

        [TestMethod()]

        [HostType("ASP.NET")]

        [UrlToTest("http://localhost:50551/default.aspx")]

        [AspNetDevelopmentServerHost("C:\\Users\\brian.orrell.PARIVEDA\\Documents\\Source\\Samples\\AspUnitTest\\AspUnitTest")]

        public void TestNameEntry()

        {

            Page page = testContextInstance.RequestedPage;          //1

 

            TextBox NameTextBox = (TextBox)page.FindControl("NameTextBox");

            Assert.IsNotNull(NameTextBox);

            Button SubmitButton = (Button)page.FindControl("SubmitButton");    //2

            Assert.IsNotNull(SubmitButton);

            Label MessageLabel = (Label)page.FindControl("MessageLabel");

            Assert.IsNotNull(MessageLabel);

 

            PrivateObject po = new PrivateObject(page);            //3

            string name = "Brian Orrell";

            NameTextBox.Text = name;

            po.Invoke("SubmitButton_Click", SubmitButton, EventArgs.Empty);

            Assert.AreEqual(string.Format("Hello, {0}", name), MessageLabel.Text);

 

        }

    }

}

Pretty easy.

posted on Sunday, May 20, 2007 8:38 PM
Brian Orrell