Saturday 28 July 2012

Wrapping Up the Find Element Method

For a quite some time,  I thought of writing about actual way of using automation tool api in the test code, so that it can become more readable, maintainable, easy to debug. I will be writing with tool in mind Selenium/WebDriver (mostly famous open source tool in recent times.)

So while designing a automation framework, we need to design in such a way that will minimize the change. Lets talk about Selenium/WebDriver find element. WebDriver has 2 methods to find element/s.
1)findElement
2)findElements

Ok, take closer look at findElment method, how it works? (Forgive me, i work only on Java bindings:))

WebElement myElem=driver.findElement(By.{manythings});

{manythings}=id,xpath,css,name,class,linktext

If you want to write a script to automate search in google page, then may be you need to use find element 2 times.
1)Open URL
2)find search text box
3)enter value to search field
4)find search button to click
5)Click on it.


For every find element, you want to implement the wait mechanism also. So if you keep on adding find element in your test code, it will be difficult for you to maintain it.


Now lets consider, Selenium guys think differently and then change the findElement() method name to findDOMElement(), Worst case:) they change the signature of the method also. What will you do? change in every place of your code, "IT WILL BE A NIGHTMARE" for you.


Lets see how we can handle this.
Create our own findElement method which takes parameter as, Parent Element, Locator Type, Locator value/expression.







Now in the above code, you can see another method PingDOMToFindElement is also called, which is wrapping the code to wait for some time for the element to appear in the DOM.


Lets see PingDOMToFindElement method also.




So here is method which actually does the work for you. This method implements web driver's explicit wait and have the web driver find element method. Locator type is type of locator you want to use like css, id, name or xpath. Locator value will be the  expression for the corresponding locator type. if you want to search element within a parent element or driver instance that will be decided by the first parameter, if it is null search within driver context else using the parent element specified.

So does it look cool now? easy to maintain? easy to debug? Do you think, we can make it much better? Please feel free to leave a suggestion/comment before leaving. 


Thanks!!

Related Posts

Related Posts...