Automated UI Testing Using WatiN | URDINESH

Software Programming, Tutorials, Interview Preparations,Stock Market,BSE/NSE, General informations

Sunday, April 27, 2014

Automated UI Testing Using WatiN

Automated UI Testing Using WatiN

About WatiN:

·         WatiN stands for Web Application Testing In .NET.
·         With WatiN you can open a browser (IE or FireFox) and open a specific website in it by code and interact will all the (html) elements on the page.
·         WatiN aims to bring you an easy way to automate your tests.


Steps to be followed:

1.      Download WatiN 2.1 from  any website 
2.      Extract the zip file.
3.      Create a new “test project”  and add a reference to the following dll file according to the DotNet framework versions you are using
a.      If you are using DotNet framework 4.0, then use the WatiN.core.dllunder bin\net40 folder.
b.      If you are using DotNet framework 3.5, then use the WatiN.core.dll under bin\net35 folder.
c.       If you are using DotNet framework 2.0, then use the WatiN.core.dll under bin\net20 folder.
4.      Ensure that you have included “using WatiN.Core;” namespaceinorder to proceed testing with WatiN.
5.      Delete the UnitTest1.cs file which will be available under the test project.
6.      Create a new class (Right click on the newly created test project and select Add->Class..) and mark the class as public.
7.      Add the [TestClass] attribute to the new class.
a.      Ensure that you have included  the following namespace
“usingMicrosoft.VisualStudio.TestTools.unitTesting;” inorder to use the attributes like TestClass, TestMethod, TestInitialize, TestCleanup, etc.
8.      Compile.
9.      Create a private field in the test class of type Browser, say objBrowser.
10.  Create a test initialization method give it the [TestInitialize] attribute. We will use this method to create a new instance of the IE class, passing in the required URL to it, and assign it to the browser instance, say objBrowser (refer step 9).
11.  Create a test cleanup method and give it the [TestCleanup] attribute. We will use this method to execute the Close() method on our browser instance(objBrowser) and assign the field to null to assist with object disposal.
12.  Finally, create a test method and give it the [TestMethod] attribute. We will use this method to use our own logic to validate the code.
13.  Call the event using the Click() method inside the test method.
a.      Use the static methods like IsTrue(), AreEqual(), etc of Assert class to verify the conditions in the unit tests.
b.      Use Find.ById() or Find.ByName() method on the browser instance, say objBrowser to find any control to validate.
c.       Use of lambda expression can also be done to find the controls in the browser to validate them.

A SAMPLE DEMO:

Below is a sample demo which validates the contents of the two text fields, say username and password whether they are equal or not on clicking the button called “Validate!”.  On clicking the validate button after the username and password fields are entered, the read only text field shows the status as “Success” if the above said criteria matches. Else it will show “Failure”. This is set at the Code behind file. The code is shown below.

<MyFirstPage.aspx.cs>

using System;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Web;
usingSystem.Web.UI;
usingSystem.Web.UI.WebControls;

namespaceMyTestWebApplication
{
publicpartialclassWebForm1 : System.Web.UI.Page
    {
protectedvoidPage_Load(object sender, EventArgs e)
        {

        }

protectedvoid btnValidate1_Click(object sender, EventArgs e)
        {
if (txtUserName.Text == txtPassword.Text)
                {
txtResult.Text = "Success";
                }
else
                {
txtResult.Text = "Failure";
                }

        }
    }
}


<TestUsingWatiNClass.cs>

TestingMyWebPage() method fills those two text fields, calls the event handler of button and writes all the username, password, and the status tried onto a file.

using System;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
usingWatiN.Core;
usingMicrosoft.VisualStudio.TestTools.UnitTesting;
using System.IO;

namespaceTestUsingWatiN
{
    [TestClass]
publicclassTestUsingWatiNClass
    {
BrowserobjBroswer;
privateFileStream fs1;
privateStreamWritersw;

        [TestInitialize]
publicvoidOpenMyBrowser()
        {
objBroswer = newIE("http://localhost:35261/MyFirstPage.aspx");
        }

        [TestCleanup]
publicvoidOnClose()
        {
objBroswer.Close();
objBroswer = null;
        }
        [TestMethod]
publicvoidTestingMyWebPage()
        {
List<string>listUsers = newList<string>() { "Cognizant", "Technology", "Solutions", "Chennai" };
List<string>listPass = newList<string>() { "Cognizant", "Chennai", "Solutions", "Hyderabad" };
try
            {
                fs1 = newFileStream(@"D:\SuccessFile.txt", FileMode.Create, FileAccess.Write, FileShare.None);
sw = newStreamWriter(fs1);


for (int i = 0; i <listUsers.Count; i++)
                {

try
                    {

objBroswer.TextField(Find.ByName("txtUserName")).TypeText(listUsers[i].ToString());
objBroswer.TextField(Find.ByName("txtPassword")).TypeText(listPass[i].ToString());

objBroswer.Button(Find.ByName("btnValidate1")).Click();

sw.WriteLine(listUsers[i].ToString() + "\t" + listPass[i].ToString() + "\t" + objBroswer.TextField(Find.ByName("txtResult")).Text);

Assert.AreEqual("Success", objBroswer.TextField(Find.ByName("txtResult")).Text);

                    }
catch (Exception e)
                    {
Console.WriteLine(e.ToString());
                    }
                }
            }
catch (Exception e)
            {
Console.WriteLine(e.ToString());
            }
finally
            {
sw.Close();
fs1.Close();
            }
        }

    }


}


Contents of SuccessFile.txt:

Company        Company        Success
Technology    Chennai          Failure
Solutions        Solutions        Success
Chennai          Hyderabad     Failure

Example test methods for reference:


 [TestMethod
publicvoid TestForLogo() 
  Image myLogo; 
myLogo = browserInstance.Image(img =>img.Id == “logo”);  //use of lambda expression to find the image whose image id is “logo”
Assert.IsTrue(myLogo.Exists); 
Assert.AreEqual("LogoDescription", myLogo.Alt); 

    [TestMethod
publicvoidTestPageContentAndBodyFont() 
  { 
Assert.IsTrue(browser.ContainsText("AnyText"));// Checks whether the page contains “AnyText”
Assert.AreEqual(“arial, sans-serif”, browserInstance.Body.Style.FontFamily);  //Checks whether the style of the body matches arial, sans-serif.
  } 



Advantages of WatiN:

1.      WatiN executes test a bit faster than Visual studio coded UI test
2.      Custom defined test cases.
3.      Ability to test even the events generated from button click, etc.
4.      Easy to maintain the code since reference is taken based on the ID’s.
5.      Find elements by multiple attributes
6.      Handles popup dialogs like alert, confirm, login etc.
7.      Can be used with any .Net Language
8.      Supports AJAX website testing and HTML Dialogs

Disadvantages of WatiN:
1.       Time constraint in creating the test cases.

2.       Test cases can be written easily only with help of IE (IE tool).

No comments:

Post a Comment

Thanks for your valuable comments

Followers