Unit Testing Validations Controls on ASP.NET Page Using WatiN

I have been playing around with WatiN and quite frankly I think it is an awesome product. Today, I need to test if the validation controls are working properly or not so I used WatiN to write simple unit tests.

The thing about validation controls is that they are displayed with the page with everything intact but are not visible. Here is the RequiredFieldValidation control HTML.

<span id="rfvName" style="color:Red;visibility:hidden;">Name is required</span>

The interesting thing is visibility:hidden attribute/value. So, now whenever the user makes a mistake in not filling up the fields then the visibility attribute will be changed to "visible". With that in mind let's see our unit test.

[Test]       
        public void TestAgreementNotAcceptedUntilCheckBoxIsChecked()
        {
            _ie = new IE("http://localhost:1950/Default.aspx");
           
            // I am not writing anything in the textbox
            //_ie.TextField("txtName").TypeText("Mohammad Azam");
           
            _ie.CheckBox("chkAgree").Click();
           
            _ie.Button("Btn_Agree").Click();

            Assert.Contains(_ie.Span("rfvName").Style.CssText,"hidden");  
           
            Assert.AreEqual("Valid", _ie.Span("lblMessage").Text);

            base.Dispose();
        }

I am not writing anything in the textbox and letting the validation control kick in. When you run the test the test will fail since, I did not typed anything in the textbox and I am assuming that the user will supply the name. To pass this test simply un-comment the following line.

//_ie.TextField("txtName").TypeText("Mohammad Azam");

Now, the test will pass.

Print | posted @ Thursday, January 03, 2008 9:53 AM

Twitter