Sunday, December 11, 2011

Procedural vs Object Oriented Script Writing


It's been my experience that a lot of testers that take the automation route don't have a lot of programming experience. I think this is because the natural progression of a QA Engineer would be to one day become a developer. Those of us that have decided to dedicate our careers to automated QA are pretty rare, possessing skill-sets of both QA analyst and developer (in my case, a very bad developer :)) Having a novice set of programming skills, I've noticed that any time I approach a new project my scripts tend to take a procedural path. That is to say, my scripts take a linear path, and are extremely limited as far as code and object re-use goes. It's a particularly challenging task for someone with little programming background to imagine how an automated test script could be created in an object-oriented way. Below is an example of how I turned my procedural script into an object-oriented one: 

Here's a simple login script. Notice in the procedural script example, I'm constantly passing arguments into a method in a HelperMethod class, this class is simply filled with static methods that are executing tasks.

PROCEDURAL SCRIPT EXAMPLE

    [TestFixture]
    public class LoginTests
    {
        [Test]
        public void Login_Test()
        {

                HelperMethods.OpenPage("http://fakeloginpage.com");
                HelperMethods.InputLoginInfo("FakeID", "FakePW");
                HelperMethods.ClickLoginButton();
        }
    }


Here is the code re-written in an Object-Oriented way. Notice that the static methods are gone, and everything is occurring with an object. The immediate benefit of this is that the properties of the object are RE-USABLE later on!!!! Say, for example, if after login the login name was supposed to appear in the upper right hand corner of the next page. You could easily verify it by referencing a property of the object, instead of having to hard-code the login everywhere.

OBJECT ORIENTED EXAMPLE

        public class Login
        {
            public string url = "http://fakeloginpage.com";
            public string id = "FakeID";
            public string password = "FakePW";
            public void Go()
            {
                driver.Navigate().GoToUrl(url);
                driver.FindElement(By.Id("login_id").SendKeys(id);
                driver.FindElement(By.Id("login_pw").SendKeys(password);
                driver.FindElement(By.Id("login_button").Click();
            }
         }

Here is how this would be used in a test script:


    [TestFixture]
    public class MyTests
    {
        [Test]
        public void LoginTest()
        {   
             Login login = new Login();
             //note that your url/id/pw variables are public, so you can easily modify them here
             //it would look like this:
             //login.url = "http://newfakeurl.com";
             login.Go();
        }
     }