Pages

Wednesday, 12 June 2013

Java testing with Selenium and dynamic ids in html

One of the cool aspects of Selenium, is that not only can you record yourself using a site, you can actually run this as a junit test.
Firstly, I'll install Selenium in Firefox (as this is the official version) and record a quick test.  It's important to note that Selenium will give you a number of different ways to remember which html tag you invoked.  For instance, it can just invoke a specific id on a page.
However, when using a portal system like say JSF under Liferay, the id values are generated on the fly, so you'd record one test, then never be able to run it successfully again.
One really nice feature of Selenium is you can invoke a HTML xpath so in the Liferay example, your code would still find the tag it needed to click.  Lets say I record myself logging into the page below...


Now because this page is generated with liferay, I can see the input text id for the form is...
As JSF under Liferay will create a new id quite regularly for this textbox (each time the server is restarted I believe, although it may be even more frequent), this means we can't just get the id and hook into that, as the tests will only ever run once. 



























What we can do however is hook into liferay by using the html tag directly as this won't be different each time Liferay loads the JSF.  I noticed I had to use this same technique for every page in Liferay as the id for nearly all the html rendered through JSF had a different id each time the page was accessed.


We can then export this to a junit class from the file menu File | Export Test Case As... | Java / JUnit 4 / Web Driver which would give us the following class to run and test.

No comments:

Post a Comment