<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>QA Automation</title>
	<atom:link href="http://www.qaautomation.net/?feed=rss2" rel="self" type="application/rss+xml" />
	<link>http://www.qaautomation.net</link>
	<description>Improving software quality with automation.</description>
	<lastBuildDate>Fri, 07 Dec 2012 23:30:41 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.5.1</generator>
		<item>
		<title>Using Sauce app to do cross browser and OS testing</title>
		<link>http://www.qaautomation.net/?p=632</link>
		<comments>http://www.qaautomation.net/?p=632#comments</comments>
		<pubDate>Fri, 07 Dec 2012 22:44:59 +0000</pubDate>
		<dc:creator>Rahul Poonekar</dc:creator>
				<category><![CDATA[What's new]]></category>

		<guid isPermaLink="false">http://www.qaautomation.net/?p=632</guid>
		<description><![CDATA[SauceLabs has recently released a new app for Macs that can be used for cross browser/Os testing as well as mobile device testing using a simulator.]]></description>
				<content:encoded><![CDATA[<p>SauceLabs has recently released a new <a title="Sauce for Mac" href="https://saucelabs.com/mac">app that works on Macs</a> that can be used for cross browser/Os testing as well as mobile device testing using a simulator.</p>
<p>You can download this for free from the App store. Once you install it, you can either use your saucelabs account or try it for free with a few limitations. Currently they support various versions of Internet Explorer, Firefox, Chrome and Opera on Windows, Linux and OSX. They also have options for OSX/iPhone Simulator testing.</p>
<p>The way it works is that once you choose a url to navigate to and the OS/Browser combination, sauce creates a new vm on demand within seconds. On the vm you have access to the browser and the desktop. In the browser you have full keyboard and mouse control so you can perform all actions that are needed to simulate end user testing. Even with the limited access to the desktop, you can do things like change the resolution of the screen.</p>
<h2>Video</h2>
<p>Before describing it further you might want see it in action:</p>
<p><iframe width="500" height="281" src="http://www.youtube.com/embed/FKO-d_Qk3FU?feature=oembed" frameborder="0" allowfullscreen></iframe></p>
<h2>Free Version limitations</h2>
<p>If you are starting with the free version, there are a few limitations that you will encounter. Some of them are</p>
<ul>
<li>Access to 15 of the 95 currently supported os/browser combinations</li>
<li>Session time is limited to 10 mins and after that there is a period of time when you cannot create another vm. You can always find workarounds but I wont get into that.</li>
<li>You can have only one active session at a time.</li>
</ul>
<p>As demonstrated in the video, you can create screenshots as well. At the moment though, I was unable to access them later though. I got an error page at saucelabs website instead.</p>
<h2>Internal Testing</h2>
<p>One question that you might be wondering at this point is how would you be able to achieve internal testing with this tool. For that, first you would have to register with saucelabs and then use something called Sauce Connect to connect to your internal web apps securely.</p>
<p>Hope you find this useful.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.qaautomation.net/?feed=rss2&#038;p=632</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Tweeting test automation and quality assurance news @QAAutomationNet</title>
		<link>http://www.qaautomation.net/?p=595</link>
		<comments>http://www.qaautomation.net/?p=595#comments</comments>
		<pubDate>Wed, 21 Mar 2012 04:53:40 +0000</pubDate>
		<dc:creator>Rahul Poonekar</dc:creator>
				<category><![CDATA[What's new]]></category>

		<guid isPermaLink="false">http://www.qaautomation.net/?p=595</guid>
		<description><![CDATA[I have recently started tweeting @QAAutomationNet to share the latest news and discussions related to test automation and Quality Assurance.]]></description>
				<content:encoded><![CDATA[<p>I have recently started tweeting and you can follow me @QAAutomationNet. I hoping we can share the latest news, discussions and conferences related to test automation and Quality Assurance.</p>
<blockquote class="twitter-tweet tw-align-center"><p>My attempt to share &#8220;what&#8217;s new&#8221; in the world of test automation and QA.</p>
<p>&mdash; Rahul Poonekar (@QAAutomationNet) <a href="https://twitter.com/QAAutomationNet/status/175683751781736449" data-datetime="2012-03-02T20:47:25+00:00">March 2, 2012</a></p></blockquote>
<p><script src="//platform.twitter.com/widgets.js" charset="utf-8"></script></p>
]]></content:encoded>
			<wfw:commentRss>http://www.qaautomation.net/?feed=rss2&#038;p=595</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Waiting after web page interactions</title>
		<link>http://www.qaautomation.net/?p=490</link>
		<comments>http://www.qaautomation.net/?p=490#comments</comments>
		<pubDate>Fri, 16 Mar 2012 20:46:40 +0000</pubDate>
		<dc:creator>Rahul Poonekar</dc:creator>
				<category><![CDATA[Selenium]]></category>

		<guid isPermaLink="false">http://www.qaautomation.net/?p=490</guid>
		<description><![CDATA[Having the correct wait logic in your tests goes a long way in making your tests robust and fast. This post describes the common wait mechanisms in WebDriver.]]></description>
				<content:encoded><![CDATA[<p>If you want to build a successful testautomation solution all you really need is make it reliable and make it fast. The single most important factor that affects both of these goals in web automation is how you wait after each page interaction. Whether you click or hover over a web element, execute a javascript function, or simulate a key press, it can cause either a page transition or an ajax operation. You would need to wait for this to complete before you can perform the next operation. If you wait too long, it makes the test execution slower than it needs to be. If you don&#8217;t wait or wait too little, it manifests as either consistent or intermittent failures.</p>
<h2>Wait for page transitions</h2>
<p>If you have worked with Selenium 1, you would expect to find a <code>waitForPageToLoad</code> equivalent in WebDriver. You wont find one. WebDriver does a pretty good job waiting for a page transition. In situations that I have run into redirects, WebDriver waited for the page that we were redirected to to load as well. This was something I had to specially handle with Selenium 1.</p>
<p>When we talk about a &#8220;page load&#8221; we aren&#8217;t talking about Ajax loading though. There can be elements on the page that gets loaded using AJAX <strong>after</strong> the browser is in a &#8220;ready state&#8221;. If your next interaction with the page required these elements to be present, you would need to handle it with a wait for a condition.</p>
<p>By the way, if you find that the page transition wait&#8217;s do not work reliably for you, please share the case by adding a comment below. It is worth noting that WebDriver documentation does say:</p>
<p><em>&#8220;Dependent on several factors, including the OS/Browser combination, WebDriver may or may not wait for the page to load. In some circumstances, WebDriver may return control before the page has finished, or even started, loading. To ensure robustness, you need to wait for the element(s) to exist in the page using Explicit and Implicit Waits.&#8221;</em></p>
<p>Again, I didn&#8217;t run into the situation where WebDriver didn&#8217;t detect the page transition correctly yet.</p>
<p>A simple test that demonstrates this is:</p>
<pre class="brush: java; highlight: [5,8]; title: ; notranslate">
@Test
public void simpleTest() {
    WebDriver driver = new FirefoxDriver();
    driver.get(&quot;http://referencewebapp.qaautomation.net/&quot;);
    driver.findElement(By.linkText(&quot;Register&quot;)).click();

    // Check for body header on new page.&lt;br /&gt;
    WebElement bodyHeader = driver.findElement(By.id(&quot;body_header&quot;));
    assertEquals(&quot;Page body header match failed&quot;, &quot;Register&quot;, bodyHeader.getText());
    driver.close();
}
</pre>
<p>Here you can see I didn&#8217;t have to specify a wait between lines 5 and 8.</p>
<p>Now what if we want to specify how much the max wait time for a page transition should be? To do this in WebDriver you will have to add the following line:</p>
<pre class="brush: java; gutter: false; title: ; notranslate">
    driver.manage().timeouts().pageLoadTimeout(90, TimeUnit.SECONDS);
</pre>
<p>We will look into what <code>driver.manage().timeouts()</code> returns a little later, but the key thing to note here is that there is a mechanism to specify the page load timeout. You could set this anywhere you want but I would imagine for most scenarios you may want to specify this right after initializing the driver.</p>
<h1>Wait for a condition</h1>
<p>When we have asynchronous processing either on the web page or even in a different system, before you can do your validation or next browser interaction you will need to wait. If you don&#8217;t wait for these process(es) to complete, you will see unreliable results.</p>
<p>Let us see an example of such an error. Let us write a test that navigates to <a title="Progress bar reference app" href="http://referencewebapp.qaautomation.net/progressbar.php" target="_blank">http://referencewebapp.qaautomation.net/progressbar.php</a> and validates the progress text of &quot;Process completed!&quot;.</p>
<p><img class="size-full wp-image-556" title="Process 4 complete" src="http://www.qaautomation.net/wp-content/uploads/2012/03/process4complete.png" alt="Process 4 complete" style="padding: 10px"/></p>
<pre class="brush: java; title: ; notranslate">
@Before
public void initialize() {
    WebDriver driver = new FirefoxDriver();
    driver.get(&quot;http://referencewebapp.qaautomation.net/progressbar.php&quot;);
}

@Test
public void getProcessTextWithoutWaiting() {
    WebElement progressBar4CommentElement = driver.findElement(By.id(&quot;pb4_comment&quot;));
    assertNotNull(&quot;Could not find progress bar 4&quot;, progressBar4CommentElement);
    assertEquals(&quot;Insufficient progress (&quot; + driver.findElement(By.id(&quot;pb4_pbText&quot;)).getText() + &quot;)&quot;,
            &quot;Process completed!&quot;, progressBar4CommentElement.getText());
}
</pre>
<p>You will notice that we don&#8217;t get the expected text of &#8220;Process completed!&#8221; after the page is loaded. Instead, you will see failures with varying progress bar values. On my machine I see:</p>
<pre class="brush: plain; gutter: false; title: ; notranslate">
org.junit.ComparisonFailure: Process running (5/100) 
Expected : Process completed!
Actual   : Process running...
</pre>
<p>If you look at the DOM of this page, you will notice that there is an element with <code>id=pb4_status</code> that appears after the progress bar is completely loaded. If you were just to add</p>
<pre class="brush: java; gutter: false; title: ; notranslate">
driver.findElement(By.id(&quot;pb4_status&quot;));
</pre>
<p>in the above test, it would fail with an exception</p>
<pre class="brush: plain; gutter: false; title: ; notranslate">
org.openqa.selenium.NoSuchElementException: Unable to locate element: {&quot;method&quot;:&quot;id&quot;,&quot;selector&quot;:&quot;pb4_status&quot;}
</pre>
<p>So, in this case, the validation of the process completion message can be fixed if we wait for this progress status element. Broadly you have two choices on how you can implement this <em>wait for condition</em>. Let us look at them:</p>
<h2>Implicit Waits</h2>
<p>WebDriver has the ability to poll the DOM for element(s). Use of this capability of WebDriver, as opposed to building your own logic to wait for the element(s), is called an Implicit Wait.</p>
<p>The way you add this implicit wait is by instantiating an implementation of the <code>WebDriver.Timeouts</code> interface. This implementation allows you to specify how long web driver should keep looking (poll) for an element whenever you use try retrieving an element using <code>findElement</code> or <code>findElements</code> method in the page before failing. The way you would set this implict wait is by calling the <code>implicitlyWait</code> method.</p>
<p>So using this let us create a new test:</p>
<pre class="brush: java; highlight: [3,7]; title: ; notranslate">
@Test
public void implicitWaitForProcessStatus() {
    driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
    WebElement progressBar4CommentElement = driver.findElement(By.id(&quot;pb4_comment&quot;));
    assertNotNull(&quot;Could not find progress bar 4&quot;, progressBar4CommentElement);

    driver.findElement(By.id(&quot;pb4_status&quot;));
    assertEquals(progressBar4CommentElement.getText(),
            &quot;Process completed!&quot;, progressBar4CommentElement.getText());
}
</pre>
<p>You will now notice that your test passes! By adding the implicit wait in line 3, WebDriver now does not throw an exception on line 7 and instead polls for the <code>pb4_status</code> element on the page. So once the element exists only then it goes to the next statement where the assertion passes. The maximum time WebDriver polls for this element is 10 seconds, which is specified in the <code>implicitWait</code> call in line 3.</p>
<p>You can always remove this implict wait by resetting the timeout to zero:</p>
<pre class="brush: java; gutter: false; title: ; notranslate">
driver.manage().timeouts().implicitlyWait(0, TimeUnit.SECONDS);
</pre>
<h2>Explicit Waits</h2>
<p>When you build your own logic on how to wait for conditions and you call it between browser interactions, it is called an explicit wait. In this case, since it is your logic, you can build it to do more than just look for an element or elements that match a single criteria. For example you could cater to</p>
<ul>
<li>wait for multiple elements on a page that need a different way to look up i.e. different locators</li>
<li>wait for other types of events on the page, like new dialogs (alerts, confirmation), browser windows etc</li>
<li>wait for an external system to complete processing etc</li>
</ul>
<p>This can be done in different ways. Let us look at some options:</p>
<h3>Fixed delays</h3>
<p>The most common problem that I have seen in tests is when they  have a fixed amount of wait time. An example of how it could be implemented in java is <code>Thread.sleep(milliseconds)</code>. If you compare this with waiting for a specific condition, like appearance or disappearance of an element on the page, it is obvious that there could be a lot of wasted time because of all these delays in your tests. I have dedicated a special section at the end of this post with my thoughts on how bad this practice is and why people end up doing this anyways. But for now let&#8217;s just move on to options that you would actually want to consider.</p>
<h3>Explicit wait using WebDriver</h3>
<p>Within the WebDriver API you will find <code>WebDriverWait</code>. There are several very good code designs in WebDriver. <code>WebDriverWait</code> is another example. If you understand how it works, you can appreciate how much flexibility it can provide. Let us see an example of how you can use it.</p>
<pre class="brush: java; highlight: [6,9,11]; title: ; notranslate">
@Test
public void explicitWaitUsingWebDriver() {
    WebElement progressBar4CommentElement = driver.findElement(By.id(&quot;pb4_comment&quot;));
    assertNotNull(&quot;Could not find progress bar 4&quot;, progressBar4CommentElement);

    Wait&lt;WebDriver&gt; wait = new WebDriverWait(driver, 10);
    // Wait for search to complete
    wait.until(new ExpectedCondition&lt;Boolean&gt;() {
        public Boolean apply(WebDriver webDriver) {
            System.out.println(&quot;Searching...&quot;);
            return webDriver.findElement(By.id(&quot;pb4_status&quot;)) != null;
        }
    });

    assertEquals(progressBar4CommentElement.getText(),
            &quot;Process completed!&quot;, progressBar4CommentElement.getText());
}
</pre>
<p>Here we have used <code>WebDriverWait</code> to wait until an <code>ExpectedCondition</code> implementation we created as an anonymous class passes. In this implementation, on line 10, we added our condition &#8211; which is to wait for the <code>pb4_status</code> element.</p>
<p>Another class that WebDriver comes with is <code>ExpectedConditions</code> (note the s at the end of the class name). Using this class you can avoid writing your own implementation of <code>ExpectedCondition</code> (no s at the end of this class name). Using the method <code>presenceOfElementLocated</code> of this class the above test would look like this:</p>
<pre class="brush: java; highlight: [9]; title: ; notranslate">
@Test
public void explicitWaitUsingExpectedConditions() {
    driver.get(REFERENCE_APP_URL + &quot;progressbar.php&quot;);
    WebElement progressBar4CommentElement = driver.findElement(By.id(&quot;pb4_comment&quot;));
    assertNotNull(&quot;Could not find progress bar 4&quot;, progressBar4CommentElement);

    Wait&lt;WebDriver&gt; wait = new WebDriverWait(driver, 10);
    // Wait for search to complete
    wait.until(ExpectedConditions.presenceOfElementLocated(By.id(&quot;pb4_status&quot;)));

    assertEquals(progressBar4CommentElement.getText(),
            &quot;Process completed!&quot;, progressBar4CommentElement.getText());
}
</pre>
<p>I could write an entire post on how to use the WebDriverWait and what type of conditions we could specify. If this is something that interests you, let me know by adding a comment at the bottom of this post. If I see a lot of interest, I will add it soon.</p>
<p>Let us look at one other option &#8230;</p>
<h3>Build your wait logic not using WebDriver</h3>
<p>There may be some situations when you can&#8217;t or don&#8217;t want to use use WebDriver API. Some such situations are:</p>
<p>Since Selenium 1 didn&#8217;t provide a good way to wait for complex conditions, you might have created your own polling logic &#8230; I certainly did. If you think that would still do what you need and you don&#8217;t want to take on the risk to porting it to WebDriver&#8217;s implementation, you could.</p>
<p>Let us say you want to poll on external systems to complete some asynchronous processing, you may or may not be able to use <code>WebDriverWait</code> (or its parent <code>FluentWait</code>).</p>
<p><code>FluentWait</code> is not thread safe. If you need something thread safe, you will have to build it yourself.</p>
<h1>Some challenges with Waits</h1>
<p>I have witnessed multiple times test frameworks being scrapped because they were slow and/ or unreliable. The biggest factor &#8230; improper wait logic implementations. The list of mistakes framework developers make with waits is pretty long, but here are some of the most common reasons and ways to fix it:</p>
<ul>
<li>Most of the times framework developers are volunteering their time to work on this project or they are under a lot of time pressure and take shortcuts. Several people think adding fixed waits requires a lot lesser work than building a wait for a condition logic. Hopefully with this post you can see it doesn&#8217;t have to be much work for majority of the cases. There are several ways to work in such high pressure environments including learning how to build incrementally. The trick here is to never loose focus on speed and reliability of what you build even if what you build might be fewer in capabilities at the beginning.</li>
<li>There are several conditions you need to wait for which causes some complications in building wait logic &#8230; for instance there could be multiple widgets on a page. Couple of the most simplest solutions people should consider are</li>
<ul>
<li>you don&#8217;t have to wait for all the dynamic elements on the page but only the one that you need to interact with</li>
<li>you don&#8217;t have to only wait for an element to appear, you could also wait for an element to disappear. A simple example is the hourglass or spinners that ajax widgets usually have when they are loading. You could just wait for all spinners to stop being visible on the page.</li>
</ul>
<li>It could be that the functionality needs to be wrapped in a more domain specific api/ reusable function and you want to hide the details of what to wait for from the users and it is different for each situation. In some cases waiting for spinners idea mentioned above could solve the problem. The other option is to ask the UI developers to add some hint on the page &#8211; for instance a <code>loadcomplete</code> javascript variable on the page which turns to &#8220;true&#8221; after the dynamic element is loaded.</li>
</ul>
<p>This topic is pretty vast so if you think there are some key aspects that this post should cover, please send me your feedback below and I will try to incorporate them.</p>
<ol id="pagenavigation">
<li class="back">« Back : <a title="Interacting with html page elements using WebDriver" href="http://www.qaautomation.net/?p=443">Interacting with page elements</a></li>
<li class="next">Window, frames and Popup dialog handling : Next »</li>
</ol>
]]></content:encoded>
			<wfw:commentRss>http://www.qaautomation.net/?feed=rss2&#038;p=490</wfw:commentRss>
		<slash:comments>21</slash:comments>
		</item>
		<item>
		<title>Common Assertions using WebDriver</title>
		<link>http://www.qaautomation.net/?p=498</link>
		<comments>http://www.qaautomation.net/?p=498#comments</comments>
		<pubDate>Thu, 22 Sep 2011 22:35:36 +0000</pubDate>
		<dc:creator>Rahul Poonekar</dc:creator>
				<category><![CDATA[Selenium]]></category>

		<guid isPermaLink="false">http://www.qaautomation.net/?p=498</guid>
		<description><![CDATA[The common validations described here are against page title, does text exist, does element exist and values returned by javascript calls.]]></description>
				<content:encoded><![CDATA[<p>In the previous sections of this <a title="THE Selenium 2 User Guide" href="http://www.qaautomation.net/?p=365">User Guide</a>, we saw how to <a title="Getting started with Selenium 2 and WebDriver" href="http://www.qaautomation.net/?p=373">instantiate a new browser session</a> using the WebDriver API and how to <a title="Locating page elements using WebDriver" href="http://www.qaautomation.net/?p=388">locate page elements</a>.</p>
<p>The next action you will most likely want to perform are adding validation points, or assertions, in your test automation solution. The common types of validations are:</p>
<ul>
<li>Is the page title as expected</li>
<li>Validations against an element on the page</li>
<li>Does text exist on the page</li>
<li>Does a javascript call return an expected value</li>
</ul>
<p>Let us look at how to achieve each of these using the WebDriver API.</p>
<h2>Page Title</h2>
<p>You can get the current page title simply by calling <code>getTitle()</code> on the WebDriver instance. Here is how a simple test would look like:</p>
<pre class="brush: java; highlight: [4]; title: ; notranslate">
@Test
public void pageTitle() {
    driver.get(&quot;http://referencewebapp.qaautomation.net/&quot;);
    String pageTitle = driver.getTitle();
    assertEquals(&quot;Current page title&quot;, &quot;Reference Web App - QA Automation&quot;, pageTitle);
}
</pre>
<h2>Validations against an element</h2>
<h3>Text within an element</h3>
<p>There are two approaches you can use for validating text within an element. The first approach is find the element using one of the locator strategies and then call <code>getText()</code> on the element object returned.</p>
<pre class="brush: java; title: ; notranslate">
driver.get(&quot;http://referencewebapp.qaautomation.net/&quot;);
WebElement header = driver.findElement(By.id(&quot;header&quot;));
assertEquals(&quot;Header text&quot;, &quot;Reference Web App&quot;, header.getText());
</pre>
<p>The second approach is to search for an element using the text in the locator and check if it is not null.</p>
<pre class="brush: java; title: ; notranslate">
driver.get(&quot;http://referencewebapp.qaautomation.net/&quot;);
WebElement header = driver.findElement(
        By.xpath(&quot;//div[@id=\&quot;header\&quot; and normalize-space(.)=\&quot;Reference Web App\&quot;]&quot;));
assertNotNull(&quot;Header text&quot;, header);
</pre>
<p>In this example I used <code>xpath</code> but you could use other locators like <code>linkText</code> or <code>partialLinkText</code>.</p>
<h3>Attributes of the element</h3>
<p>This is similar to validating text in the element. You would find the element on the page and then use <code>getAttribute</code></p>
<pre class="brush: java; title: ; notranslate">
driver.get(&quot;http://referencewebapp.qaautomation.net/&quot;);
WebElement submit = driver.findElement(By.name(&quot;submit&quot;));
assertEquals(&quot;Submit button value&quot;, &quot;Login&quot;, submit.getAttribute(&quot;value&quot;));
</pre>
<h2>Does text exist in the entire page</h2>
<p>For those who start with Selenium 2, or who have used Selenium 1.x, you would expect to easily find a <code>doesTextExist</code> method. It will come as a bit of a shock that there isn&#8217;t something as obvious in the API.</p>
<p>One option to get the text representation of the entire page is getting the text of the <code>body</code> element using something like</p>
<pre class="brush: java; gutter: false; title: ; notranslate">
driver.findElement(By.tagName(&quot;body&quot;)).getText()
</pre>
<p>Unfortunately, getting text using this mechanism is <b>extremely</b> slow for large pages. The second option is to get the html content using <code>driver.getPageSource()</code> and then pass it to a html parser. One such a parser is <a href="http://jsoup.org/" title="Jsoup Html Parser home page">JSoup</a>.</p>
<ul>
<li>easy to use,</li>
<li>is better performant for this sort of thing, and</li>
<li>the output text is cleaner and easier do validations against</li>
</ul>
<p>. Here is how you would use it:</p>
<pre class="brush: java; title: ; notranslate">
    public String getPageContent() {
        Document doc = Jsoup.parse(driver.getPageSource());
        return doc.text();
    }
</pre>
<p>Just to compare the two approaches, getting document text in msn.com took over 5 secs using first approach and less than a second for the second.</p>
<p>Ofcourse for this code to work, you will have to download the jsoup library and put it in your classpath. Also if you are not developing in java you will have to find a different parser because jsoup is a java library that hasn&#8217;t been ported to other languages.</p>
<h2>Validating Javascript return values</h2>
<p>There are various reasons why you might want to directly call a javascript method or get the value of a javascript variable on the page. You can do this using only those WebDriver instances that implement the <code>JavascriptExecutor</code> interface. The <code>JavascriptExecutor</code> interface has a <code>executeScript</code> method that you would pass your javascript call. If you expect a return value, your javascript snippet must have a <code>return</code>.</p>
<p>Let&#8217;s look at an example:</p>
<pre class="brush: java; title: ; notranslate">
driver.get(REFERENCE_APP_URL + &quot;jsmethods.php&quot;);
String returnValue = (String) ((JavascriptExecutor) driver).executeScript(&quot;return getString();&quot;);
assertEquals(&quot;JS method with string return type&quot;, &quot;foo&quot;, returnValue);
</pre>
<p>The return type for <code>executeScript</code> method is Object. That is because this script would return an object of different types based on what is returned. The various types of objects returned are Sting, Integer, Boolean, etc. It also can return a WebElement as we saw in the <a title="Locating page elements using WebDriver" href="http://www.qaautomation.net/?p=388">Locating page elements using WebDriver</a> under DOM locator.</p>
<p>Besides these types of validations, there are certainly others you can have, like if a new window was opened, an alert dialog popped up, a cookie was set etc. We will cover those in later sections of the <a href="http://www.qaautomation.net/?p=365" title="THE Selenium 2 User Guide">Selenium 2 User Guide</a>.</p>
<ol id="pagenavigation">
<li class="back">« Back : <a title="Locating page elements using WebDriver" href="http://www.qaautomation.net/?p=388">Locating page elements using WebDriver</a></li>
<li class="next"><a title="Interacting with html page elements using WebDriver" href="http://www.qaautomation.net/?p=443">Interacting with page elements</a> : Next »</li>
</ol>
]]></content:encoded>
			<wfw:commentRss>http://www.qaautomation.net/?feed=rss2&#038;p=498</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Interacting with html page elements using WebDriver</title>
		<link>http://www.qaautomation.net/?p=443</link>
		<comments>http://www.qaautomation.net/?p=443#comments</comments>
		<pubDate>Mon, 19 Sep 2011 06:30:06 +0000</pubDate>
		<dc:creator>Rahul Poonekar</dc:creator>
				<category><![CDATA[Selenium]]></category>

		<guid isPermaLink="false">http://www.qaautomation.net/?p=443</guid>
		<description><![CDATA[Here we see how to make keyboard and mouse calls. Some examples show how to set form fields, click and drag and drop page elements.]]></description>
				<content:encoded><![CDATA[<p>In the previous section we looked at different strategies to <a title="Locating page elements using WebDriver" href="http://www.qaautomation.net/?p=388">locate page elements</a> using the WebDriver API. When you locate the element using the WebDriver API, you get the handle to the element as an object of the <code>WebElement</code> interface.</p>
<p>Once we get a handle to the element, we can perform</p>
<ul>
<li>Keyboard actions like type, multi select etc and</li>
<li>Mouse actions like clicking, dragging-dropping, left click etc</li>
</ul>
<div>Using these we can click links, set fields, move elements on the page, simulate key presses (for instance on websites that support keyboard shortcuts), right click elements and almost anything else that end users would manually do on interact with the web page.</div>
<p>Here are some of the common actions your framework/ tests would have to perform.</p>
<h2>Clicking Elements</h2>
<p>The <code>WebElement</code> interface has a <code>click()</code> method. So if you would want to click an element, you would have to use <code>findElement</code> or <code>findElements</code> to find the element and call the <code>click()</code> method.</p>
<p>Let us look at this example:</p>
<pre class="brush: java; highlight: [3,4]; title: ; notranslate">
driver.get(&quot;http://referencewebapp.qaautomation.net/&quot;);

WebElement registerLink = driver.findElement(By.linkText(&quot;Register&quot;));
registerLink.click();
</pre>
<p>Here in line 3 we got the handle to the anchor page element by looking it up using the link text. On the <code>WebElement</code> object we then called <code>click()</code> which allows us to navigate to the Registeration page. You will notice that in this case selenium handled waiting for the page transition. This is different from Selenium 1&#8242;s API where you had to explicitly call <code>waitForPageToLoad</code>.</p>
<p>As per Selenium 2&#8242;s documentation, there are cases when the click method would not wait for the page transition. Also, if there are a lot of asynchronous calls on the new page, most of WebDriver click implementation doesn&#8217;t wait for them to complete. It would be upto you to manage the appropriate waiting logic. This is covered in more details in the next section.</p>
<h2>Setting form fields</h2>
<div>The different keyboard actions are:</div>
<h3>Enter text in input fields</h3>
<div>End users of the web application under test would type text in input fields like text fields, password fields, text area, file input field etc. To simulate the same actions, you would use the <code>sendKeys</code> method on the <code>WebElement</code>. The <code>sendKeys</code> method takes the characters you would want to enter in the field. For example:</div>
<pre class="brush: java; highlight: [2]; title: ; notranslate">
WebElement usernameField = driver.findElement(By.id(&quot;username&quot;));
usernameField.sendKeys(&quot;rpoonekar&quot;);
</pre>
<h3>Selecting value in a Drop-down/ select fields</h3>
<p>Drop-down fields use the same method to set values in them. The main difference is that in the <code>sendKeys</code> method you could pass the value or the option text as parameter to the method. For instance if your select field looked like this:</p>
<pre class="brush: xml; gutter: false; title: ; notranslate">
&lt;select name=&quot;state&quot;&gt;
    ...
    &lt;option value=&quot;CA&quot;&gt;California&lt;/option&gt;
    ...
&lt;/select&gt;
</pre>
<p>you could set the field using either</p>
<pre class="brush: java; gutter: false; title: ; notranslate">
driver.findElement(By.name(&quot;state&quot;)).sendKeys(&quot;CA&quot;);
</pre>
<p>or</p>
<pre class="brush: java; gutter: false; title: ; notranslate">
driver.findElement(By.name(&quot;state&quot;)).sendKeys(&quot;California&quot;);
</pre>
<h3>Selecting Radio and checkbox fields</h3>
<p>With choice elements, once you get a handle to the <code>WebElement</code>, you would need to call the <code>click()</code> method.</p>
<pre class="brush: java; gutter: false; title: ; notranslate">
driver.findElement(By.id(&quot;email&quot;)).click();
</pre>
<h3>Form Submit</h3>
<p>There are two way you can submit a form. The first option is locating the submit button and clicking it</p>
<pre class="brush: java; gutter: false; title: ; notranslate">
driver.findElement(By.xpath(&quot;//input[@type='submit']&quot;)).click();
</pre>
<p>The second option is to call the <code>submit()</code> method on any field you had a reference to. If this element is within a form, WebDriver will walk up the DOM until it finds the enclosing form and then calls submit on that. If the element isn’t in a form, then the NoSuchElementException will be thrown</p>
<pre class="brush: java; highlight: [3]; title: ; notranslate">
WebElement state = driver.findElement(By.name(&quot;state&quot;));
state.sendKeys(&quot;California&quot;);
state.submit();
</pre>
<p>Of these two approaches, I recommend the first one because you are specifying precisely which element to look for and click and so it will execute faster. You are also inherently asserting if the submit element exists in the form.<br />
I view the second approach more than just a convenience method. The second approach can be useful when you don&#8217;t want your test to break if there are certain types of changes in the mechanism to submit the form. For instance, if the submit button is replaced with a link that submits the form. This reduces the maintenance cost of your test(s).</p>
<h2>Mouse actions</h2>
<h3>Drag and Drop</h3>
<p>When you need to do mouse actions you could use the <code>Mouse</code> class. There are some common composite actions available in the <code>Actions</code> class. Drag and Drop is one of them. The <code>dragAndDrop</code> method essentially has three actions &#8211; click and hold/ mouse down, mouse move and release/ mouse up.</p>
<p>Let us look at this example:</p>
<pre class="brush: java; highlight: [9,10]; title: ; notranslate">
@Test
public void dragAndDrop() {
    driver.get(&quot;http://referencewebapp.qaautomation.net/dragndrop.php&quot;);

    Actions actions = new Actions(driver);
    WebElement drag = driver.findElement(By.id(&quot;draggable&quot;));
    WebElement to = driver.findElement(By.id(&quot;droppable&quot;));

    actions.dragAndDrop(drag, to);
    actions.perform();
    assertEquals(&quot;Drag-n-Drop didn't work.&quot;, &quot;Dropped!&quot;, to.getText());
}
</pre>
<p>As you can see, the <code>dragAndDrop</code> methods takes two arguments, the element that you want to drag, and the element you want to drop it on.</p>
<p>One of the key differences in the way <code>Mouse</code> is used and <code>Actions</code> is used is that when you call the mouse methods, it gets executed immediately. With <code>Actions</code>, you build the different steps and they all get executed when you call <code>perform()</code>.</p>
<ol id="pagenavigation">
<li class="back">« Back : <a title="Common Assertions using WebDriver" href="http://www.qaautomation.net/?p=498">Common Assertions using WebDriver</a></li>
<li class="next"><a title="Waiting after web page interactions" href="http://www.qaautomation.net/?p=490">Waiting after web page interactions</a> : Next »</li>
</ol>
]]></content:encoded>
			<wfw:commentRss>http://www.qaautomation.net/?feed=rss2&#038;p=443</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>Locating page elements using WebDriver</title>
		<link>http://www.qaautomation.net/?p=388</link>
		<comments>http://www.qaautomation.net/?p=388#comments</comments>
		<pubDate>Wed, 31 Aug 2011 08:44:40 +0000</pubDate>
		<dc:creator>Rahul Poonekar</dc:creator>
				<category><![CDATA[Selenium]]></category>

		<guid isPermaLink="false">http://www.qaautomation.net/?p=388</guid>
		<description><![CDATA[Locators have changed with Selenium 2 with the WebDriver API. Here are code examples of how to locate page elements with WebDriver.]]></description>
				<content:encoded><![CDATA[<h2>Types of Locators</h2>
<p>Locators have changed with Selenium 2 with the WebDriver API. Out of the box WebDriver supports several ways to locate elements on the page using the <code>By</code> abstract class.</p>
<h3>Finding elements by ID</h3>
<p>ids are the preferred way to locate elements on a page for 2 main reasons:</p>
<ul>
<li>According to w3c ids are supposed to be unique on an html page. This makes ids a very explicit and reliable way to locate elements on the page.</li>
<li>Also, all browsers also have highly efficient methods to get an object on the page using their ids. This makes <code>id</code> locators the fastest type of locator in Selenium.</li>
</ul>
<p>Let us now look at how to use id locators using this html code as an example:</p>
<pre class="brush: xml; gutter: false; highlight: [2,3]; title: ; notranslate">
&lt;form name=&quot;loginForm&quot;&gt;
    Login Username: &lt;input id=&quot;username&quot; name=&quot;login&quot; type=&quot;text&quot; /&gt;
    Password: &lt;input id=&quot;password&quot; name=&quot;password&quot; type=&quot;password&quot; /&gt;
    &lt;input name=&quot;login&quot; type=&quot;submit&quot; value=&quot;Login&quot; /&gt;
&lt;/form&gt;
</pre>
<p>In the above code, the username and password text fields are can be set using their ids. The locators for them would be</p>
<p><code>driver.findElement(By.id(username));</code></p>
<p>Even though this is a great locator, it is not realistic for all elements on a page to have ids. The developers add ids to key elements on the page to better control the look and feel or provide the dynamic user interaction. However, ids should also be added to elements that are frequently interacted within tests &#8230; to make the pages more testable. Automated test script authors should consider adding, or requesting addition of, ids to these key elements on the page.</p>
<p>In some cases, the ids on an element cannot be reliably used in a test. For instance, if you are displaying objects stored in the database, the objects ids could contain the database id in it, for instance <code>book1347</code> could be the id for book who&#8217;s database id is 1347. In such situations it may not be possible to predict and use the ids and so you may need to use other ways described below to find elements.</p>
<h3>Finding elements by name</h3>
<p>Generally <code>id</code>s are added to elements when they want to be referenced from css or javascript and <code>name</code>s are added to form fields. When referencing element from javascript either can be used. From a test automation standpoint, whenever id is not available/ usable, you should try to use the name instead.</p>
<p>Using the same example above, the way you would find the submit button would be:</p>
<p><code>driver.findElement(By.name("login"));</code></p>
<p>There is one big difference between the <code>id</code> and <code>name</code> attributes though &#8230; name attributes don&#8217;t have to be unique in a page. If there are multiple elements with the same name, then the first element in the page is selected. So, in this example, if another button or form named &#8220;login&#8221; was present of added later, it could cause the test to fail.</p>
<h3>Finding links by text</h3>
<p>This locator identifies links by the text in them. Let us look at an example:</p>
<pre class="brush: xml; gutter: false; title: ; notranslate">
 &lt;html&gt;
 &lt;body&gt;
    ...
    &lt;a href=&quot;signin.html&quot;&gt;Sign In&lt;/a&gt; to modify your account details.
    ...
&lt;/body&gt;
&lt;/html&gt;
</pre>
<p>To click this hyperlink using the anchor tag&#8217;s text, you can use the <code>By.linkText()</code> locator:</p>
<p><code>driver.findElement(By.linkText("Sign In"));</code></p>
<p>If there are multiple elements with text &#8220;Sign In&#8221;, the first one is selected.</p>
<p>Btw, this is called <code>linkText</code> because it is used for hyperlinks. In Selenium if you used the <code>link=textPattern</code> locator, you could use it to locate other elements like div, span, td etc. In WebDriver, this locator works only for links.</p>
<p>Another common case is when we need to find links by a portion of the text it contains. In such cases you can find it by specifying the partial text. For example:</p>
<p><code>driver.findElement(By.partialLinkText("Sign"));</code></p>
<h3>Finding elements by XPath</h3>
<p>XPath is a very powerful language to express which element to identify. If you use it correctly, it can produce very reliable and low maintenance locators, but if you use it incorrectly, it can create very brittle test cases.</p>
<p>Let us see some examples:</p>
<pre class="brush: xml; gutter: false; highlight: [8]; title: ; notranslate">
 &lt;table name=&quot;cart&quot;&gt;
    &lt;tr id=&quot;item1&quot;&gt;
        &lt;td class=&quot;name item&quot;&gt;Mp3 Download: foobar.mp3&lt;/td&gt;
        &lt;td class=&quot;name item&quot;&gt;&lt;input name=&quot;qty&quot; class=&quot;name item formfield disabled&quot; /&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr id=&quot;item2&quot;&gt;
        &lt;td class=&quot;name item&quot;&gt;Mp3 Player&lt;/td&gt;
        &lt;td class=&quot;name item&quot;&gt;&lt;input id=&quot;item2_quantity&quot; name=&quot;qty&quot; class=&quot;name item formfield required&quot; type=&quot;text&quot; /&gt;&lt;/td&gt;
    &lt;/tr&gt;
    ...
&lt;/table&gt;
</pre>
<p>You can target the highlighted input field using the following XPath expressions:</p>
<p><code><br />
//table/tr[2]/td/input<br />
//input[@id='item2_quantity']<br />
(//table[@name='cart']//input)[2]<br />
//input[contains(@class,'required')]<br />
//input[contains(@class,'required') and type='text']<br />
</code></p>
<p>And for the last option, your java call would look like:<br />
<code>driver.findElement(By.xpath("//input[contains(@class='required') and type='text']"));</code></p>
<p>As you can guess, some of these expressions will not be as reliable as others. Of these <code>//table/tr[2]/td/input</code> is the worst because it would break even with slightest modification to the page structure. It can take some time to learn XPath if you aren&#8217;t familiar with it, but it is worth the time if you plan to spend a lot of time writing UI automated tests. In any case do not rely on tools, including selenium IDE, to generate the right xpath expression for you. They can help you get started but they are usually bad at identifying the more reliable XPaths.</p>
<h4>XPath namespaces</h4>
<p>There are some special cases you should be aware of when you work with XPath, like when you are trying to interact with SVG. Like in the example <a href="http://referencewebapp.qaautomation.net/svg.php" title="SVG example" target="_blank">here</a>, the html looks something like this:</p>
<pre class="brush: xml; gutter: false; highlight: [3]; title: ; notranslate">
&lt;div id=&quot;svgchart&quot;&gt;
  ...
    &lt;svg xmlns=&quot;http://www.w3.org/2000/svg&quot;&gt;
        &lt;g&gt;
            &lt;path .../&gt;
        &lt;/g&gt;
        ...
    &lt;/svg&gt;
  ...
&lt;/div&gt;
</pre>
<p>Here, if you use XPath like:<br />
<code><br />
//svg<br />
</code><br />
you will get <code>ERROR org.openqa.selenium.NoSuchElementException: Unable to locate element</code>. This is because the svg element is in a different namespace. You will have to specify your xpath with the namespace uri like this instead:<br />
<code><br />
//*[local-name()='svg' and namespace-uri()='http://www.w3.org/2000/svg']<br />
</code></p>
<h4>XPath performance</h4>
<p>So, if XPath&#8217;s are so versatile, why doesn&#8217;t everyone prefer these? It&#8217;s because they are often the slowest, especially in older versions of IE! There are <a title="Making Selenium commands using XPaths faster in Internet Explorer" href="http://www.qaautomation.net/?p=216">some ways you can make XPath&#8217;s faster</a>, but they still are a few times slower than ids or names.</p>
<h3>Finding elements by CSS</h3>
<p><code>css</code> locators can be used to identify a large number of elements on a page. Let us look at this html snippet for instance:</p>
<pre class="brush: xml; gutter: false; highlight: [8]; title: ; notranslate">
 &lt;table name=&quot;cart&quot;&gt;
    &lt;tr id=&quot;item1&quot;&gt;
        &lt;td class=&quot;label&quot;&gt;Mp3 Download: foobar.mp3&lt;/td&gt;
        &lt;td class=&quot;item&quot;&gt;&lt;input name=&quot;qty&quot; class=&quot;formfield disabled&quot; /&gt;&lt;/td&gt;
    &lt;/tr&gt;
    &lt;tr id=&quot;item2&quot;&gt;
        &lt;td class=&quot;label&quot;&gt;Mp3 Player&lt;/td&gt;
        &lt;td class=&quot;item&quot;&gt;&lt;input id=&quot;item2_quantity&quot; name=&quot;qty&quot; class=&quot;formfield required&quot; type=&quot;text&quot; /&gt;&lt;/td&gt;
    &lt;/tr&gt;
    ...
&lt;/table&gt;
</pre>
<p>In this case the <code>css</code> locator variations possible for the highlighted input field are:</p>
<p><code><br />
input.required<br />
input[class~='required']<br />
input.required[type='text']<br />
#item2_quantity<br />
input#item2_quantity<br />
</code></p>
<p>The css locator may not be as expressive as XPath, but it generally executes faster.</p>
<h3>Finding elements by class</h3>
<p>This is more of a convinience mechanism to identify elements. In the css example above, instead of using</p>
<p><code>driver.findElements(By.css("input[class~='required']"));</code></p>
<p>you could use</p>
<p><code>driver.findElements(By.class("required"));</code></p>
<h2>Getting elements by DOM</h2>
<p>DOM stands for Document Object Model. DOM is convention for representing objects in HTML documents.</p>
<pre class="brush: xml; gutter: false; highlight: [2]; title: ; notranslate">
&lt;form id=&quot;loginForm&quot;&gt;
    Login Username: &lt;input id=&quot;username&quot; name=&quot;username&quot; type=&quot;text&quot; /&gt;
    Password: &lt;input name=&quot;password&quot; type=&quot;password&quot; /&gt;
    &lt;input name=&quot;login&quot; type=&quot;submit&quot; value=&quot;Log in&quot; /&gt;
&lt;/form&gt;
</pre>
<p>In this page, the dom expression for the highlighted input field would be:</p>
<p><code><br />
document.forms[0].elements[0]<br />
document.forms['loginForm'].elements['username']<br />
document.forms['loginForm'].username<br />
document.getElementById('username')<br />
</code></p>
<p>For those who have used Selenium 1 API, you would expect to find a By.dom() equivalent api, but it doesn&#8217;t exist. However, you still can get a handle to these elements using dom expressions by using the following code snippet instead:</p>
<pre class="brush: java; highlight: [2]; title: ; notranslate">
...
    driver.findElement(byDom(&quot;document.forms[0].elements[0]&quot;));
...

public By byDom(String domExpression) {
    final Object o = ((JavascriptExecutor) driver).executeScript(&quot;return &quot; + domExpression + &quot;;&quot;);

    if (o instanceof WebElement) {
        return new By() {
            @Override
            public List&lt;WebElement&gt; findElements(SearchContext searchContext) {
                return new ArrayList&lt;WebElement&gt;() {
                    {
                        add((WebElement) o);
                    }
                };
            }
        };
    }
}
</pre>
<p>The three key aspects of this code that you should note,</p>
<ul>
<li>The driver can be casted to <code>JavascriptExecutor</code> and other interfaces which will provide additional capabilities.</li>
<li><code>executeScript()</code> in <code>JavascriptExecutor</code> returns an object which can be casted to a <code>WebElement</code> if the javascript expression returns a dom element.</li>
<li>You can create your own implementation of <code>By</code></li>
</ul>
<h3>Some things to note for Selenium 1 users</h3>
<ul>
<li>You will notice that Implicit locators are not supported in WebDriver.</li>
<li>When using name in Selenium 1, you could add other attributes in the expressions to filter the results. For example <code>name=login type=text</code> was valid. You cannot do that any more with the By.name() call.</li>
</ul>
<h2><code>findElement()</code> and <code>findElements()</code></h2>
<p>As you might have noticed in the examples above, the <code>By</code> locators were used within <code>findElement</code> and <code>findElements</code> methods. The purpose of these methods is to return a <code>WebElement</code>, in case of <code>findElement</code>, and a list of <code>WebElement</code>s in the case of <code>findElements</code>.</p>
<p>The <code>WebElement</code> represents an html element on the page. In the next section you will see that it is this <code>WebElement</code> object that you would interact with or read attributes of for validations etc.</p>
<p>When you use these methods on the <code>WebDriver</code> object, the scope within with the elements are located is the entire page.</p>
<h3>Getting child elements</h3>
<p>The <code>WebElement</code> interface also has <code>findElement()</code> and <code>findElements()</code> methods. In this case, it is within the scope of this parent element that child elements are located. This is useful when you want to narrow the scope to find several elements that you would interact with. In most cases, narrowing the scope improves the execution times for locating the elements.</p>
<ol id="pagenavigation">
<li class="back">« Back : <a title="Getting started with Selenium 2 and WebDriver" href="http://www.qaautomation.net/?p=373">Getting started with Selenium 2 and WebDriver</a></li>
<li class="next"><a title="Common Assertions using WebDriver" href="http://www.qaautomation.net/?p=498">Common Assertions using WebDriver</a> : Next »</li>
</ol>
]]></content:encoded>
			<wfw:commentRss>http://www.qaautomation.net/?feed=rss2&#038;p=388</wfw:commentRss>
		<slash:comments>28</slash:comments>
		</item>
		<item>
		<title>Getting started with Selenium 2 and WebDriver</title>
		<link>http://www.qaautomation.net/?p=373</link>
		<comments>http://www.qaautomation.net/?p=373#comments</comments>
		<pubDate>Mon, 29 Aug 2011 20:49:30 +0000</pubDate>
		<dc:creator>Rahul Poonekar</dc:creator>
				<category><![CDATA[Selenium]]></category>

		<guid isPermaLink="false">http://www.qaautomation.net/?p=373</guid>
		<description><![CDATA[Steps to install/ set-up Selenium 2 in your project and code examples of instantiating WebDriver for Firefox, Chrome and Internet Explorer.]]></description>
				<content:encoded><![CDATA[<h2>Download Selenium 2</h2>
<p>To begin adding Selenium to your project, you will have to first <a title="Download Selenium" href="http://seleniumhq.org/download/">download Selenium</a> for the language you develop your framework on.</p>
<p>The download comes as a zip file so you will first have to unzip it. In this unzipped folder contents, you will see <code>selenium-java-2.x.y.jar</code> and several other dependent jar files in the lib directory. Assuming you have a java development environment with the setup similar to the one defined in the <a title="Creating your Java project workspace" href="http://www.qaautomation.net/?p=7">Creating your Java project workspace</a> post, you will have to copy these jar files in your lib directory as well. Most people just copy all the jars over, however, I recommend copying just the libraries you need.</p>
<h3>Starting and stopping Selenium server</h3>
<p>For those who have used earlier versions of Selenium, you are probably familiar with starting and stopping selenium using ant. In Selenium 2, you don&#8217;t need to start the server. Infact, the <code>selenium-java-2.x.y.jar</code> cannot be used to start the server in the first place. You need a separate jar to start the selenium 2 server, which is used only when you need to run Selenium 1 APIs on Selenium 2.</p>
<h3>Selenium-backed WebDriver</h3>
<p>For reasons described in the Selenium 2 introduction, if you plan to use the selenium server you will need to download the <code>selenium-server-2.x.y.zip</code> instead of the <code>selenium-java-2.x.y.jar</code>. You can find the <code>selenium-server-2.x.y.zip</code> on the <a title="Selenium downloads list" href="http://code.google.com/p/selenium/downloads/list">Selenium project download</a> google page.</p>
<h2>Instantiating WebDriver</h2>
<p><code>WebDriver</code> is an interface in the new Selenium 2 API. The different implementations of this WebDriver interface allows programmatically controlling different browsers.</p>
<p>Using the interface you could start a new browser instance, navigate to a url and close the browser using this snippet.</p>
<pre class="brush: java; title: ; notranslate">
WebDriver driver;
Wait wait;

public void instantiateBrowser(BrowserType browserType, String url) {
    driver = getWebDriver(browserType);
    wait = new WebDriverWait(driver, 30);
    driver.get(url);
}

public void closeBrowser() {
    driver.close();
}

public WebDriver getWebDriver(BrowserType browserType) {
    switch (browserType) {
        case FIREFOX:
            // Need to implement
            return null;
        case IE:
            // Need to implement
            return null;
        case CHROME:
            // Need to implement
            return null;
        case HTMLUNIT:
            // Need to implement
            return null;
        default:
            throw new RuntimeException(&quot;Browser type unsupported&quot;);
    }
}

public enum BrowserType {
    FIREFOX, IE, CHROME, HTMLUNIT
}
</pre>
<p>The following sections shows how you can instantiate and configure each browser type:</p>
<h3>Firefox</h3>
<p>In Firefox, it is recommended to create a firefox profile for test automation. I have an entire post dedicated to describing the <a title="Custom Firefox profile for Selenium" href="http://www.qaautomation.net/?p=45">steps to create a firefox profile</a>.</p>
<p>Once you have created this profile, you can instantiate a new firefox session using this code snippet.</p>
<pre class="brush: java; title: ; notranslate">
File profileDirectory = new File(profileDirectory);
FirefoxProfile profile = new FirefoxProfile(profileDirectory);
return new FirefoxDriver(profile);
</pre>
<p>Here <code>profileDirectory</code> is the path to the directory where the profile is created.</p>
<h3>Internet Explorer</h3>
<p>With IE the first challenge I encountered was with security. The error you would get is:</p>
<p><code>org.openqa.selenium.WebDriverException: Unexpected error launching Internet Explorer. Protected Mode must be set to the same value (enabled or disabled) for all zones.</code></p>
<p>There are two ways to solve this:</p>
<p>The first option is that in your Internet Explorer browser set the protected mode enabled or disabled for all zones (Internet, Local Intranet, Trusted Sites and Restricted sites). The problem with this option is that if you are testing a system which does not work with this security setting or you do not have control over the machines where your test code will execute, then you cannot use this approach.</p>
<p>The second option to get around it is by using the <code>INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS</code> capability. You can set this capability by using the following snippet:</p>
<pre class="brush: java; title: ; notranslate">
DesiredCapabilities ieCapabilities = DesiredCapabilities.internetExplorer();
ieCapabilities.setCapability(
        InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);
return new InternetExplorerDriver(ieCapabilities);
</pre>
<p>The problem with this option is that there is a potential that you might get some flakiness/ unreliability while performing certain actions in IE. I haven&#8217;t encountered this flakiness yet though.</p>
<h3>Chrome</h3>
<p>With Chrome, you will have to download the chrome driver first. If you don&#8217;t you will see the error:</p>
<p><code>java.lang.IllegalStateException: The path to the chromedriver executable must be set by the webdriver.chrome.driver system property; for more information, see http://code.google.com/p/selenium/wiki/ChromeDriver. The latest version can be downloaded from http://code.google.com/p/chromium/downloads/list</code></p>
<p>I recommend downloading all three binaries <a title="Chrome driver download page" href="http://code.google.com/p/chromedriver/downloads/list">maintained by the Chromium project</a> i.e. for windows, linux and mac and renaming them to chromedriver-win.exe, chromedriver-lin and chromedriver-mac. This way you can refer to them on the appropriate OS using the following code.</p>
<pre class="brush: java; title: ; notranslate">
DesiredCapabilities chromeCapabilities = DesiredCapabilities.chrome();

String chromeBinary = System.getProperty(&quot; &quot;);
if (chromeBinary == null || chromeBinary.equals(&quot;&quot;)) {
    String os = System.getProperty(&quot;os.name&quot;).toLowerCase().substring(0, 3);
    chromeBinary = &quot;lib/chromedriver-&quot; + os + (os.equals(&quot;win&quot;) ? &quot;.exe&quot; : &quot;&quot;);
    System.setProperty(&quot;webdriver.chrome.driver&quot;, chromeBinary);
}

return new ChromeDriver(chromeCapabilities);
</pre>
<p>One of the things that threw me off initially when I was looking for the <a title="Chrome driver downloads page" href="http://code.google.com/p/chromedriver/downloads/list">binaries of the chrome driver</a> was that I saw a linux 32 and 64 bit binary, but I only saw a win32 bit binary. I wondered if that meant that win64 was not supported. However, when I used the win32 binary on my windows 64bit machine, it worked.</p>
<p>One other thing to keep in mind is that if you do not have Chrome installed in the default location, you could also tell WebDriver where to look for it by adding</p>
<p><code>chromeCapabilities.setCapability("chrome.binary", "/path/to/where/chrome/is/installed/chrome.exe");</code></p>
<p>before creating a new instance of the ChromeDriver.</p>
<ol id="pagenavigation">
<li class="back">« Back : <a title="What is new in Selenium 2" href="http://www.qaautomation.net/?p=230">What is new in Selenium 2</a></li>
<li class="next"><a title="Locating page elements using WebDriver" href="http://www.qaautomation.net/?p=388">Locating page elements</a> : Next »</li>
</ol>
]]></content:encoded>
			<wfw:commentRss>http://www.qaautomation.net/?feed=rss2&#038;p=373</wfw:commentRss>
		<slash:comments>17</slash:comments>
		</item>
		<item>
		<title>Selenium 2 Tutorial and User Guide with examples</title>
		<link>http://www.qaautomation.net/?p=365</link>
		<comments>http://www.qaautomation.net/?p=365#comments</comments>
		<pubDate>Mon, 29 Aug 2011 20:03:41 +0000</pubDate>
		<dc:creator>Rahul Poonekar</dc:creator>
				<category><![CDATA[Selenium]]></category>

		<guid isPermaLink="false">http://www.qaautomation.net/?p=365</guid>
		<description><![CDATA[This User Guide describes how to install and use Selenium 2 for browser test automation. The Web Driver code examples help newbies who are looking for Selenium tutorials as well.]]></description>
				<content:encoded><![CDATA[<p>Welcome to the Selenium 2 Tutorial and User Guide!</p>
<p>I have used Selenium for several years, and continue to use it, at work. I am a fan and so I decided to contribute to it&#8217;s adoption by writing some documentation on Selenium for everyone&#8217;s benefit. My hope is that because I am a user of the tool and I have experienced problems that real users face, this guide will capture the essentials of how to use the tool.</p>
<p>A lot of people look for Selenium tutorials and this guide is written in a manner to help newbies learn how to develop tests in Selenium. This guide also contains code examples that should help both novice and experienced users.</p>
<p>The code examples are currently in Java. I am sure it will still give you the key information you need to allow you to develop in the programming language of your choice, but, if you have snippets in other languages that you think would be useful, please feel free to share them.</p>
<h2>Table of Contents</h2>
<ol>
<li><a title="Introduction to Selenium" href="http://www.qaautomation.net/?p=4">Introduction to Selenium</a></li>
<li><a title="What is new in Selenium 2" href="http://www.qaautomation.net/?p=230">What is new in Selenium 2</a></li>
<li><a title="Getting started with Selenium 2 and WebDriver" href="http://www.qaautomation.net/?p=373">Getting started with Selenium 2 and WebDriver</a></li>
<li><a title="Locating page elements using WebDriver" href="http://www.qaautomation.net/?p=388">Locating page elements</a></li>
<li><a title="Common Assertions using WebDriver" href="http://www.qaautomation.net/?p=498">Common Assertions using WebDriver</a></li>
<li><a title="Interacting with html page elements" href="http://www.qaautomation.net/?p=443">Interacting with page elements</a></li>
<li><a title="Waiting after web page interactions" href="http://www.qaautomation.net/?p=490">Waiting after web page interactions</a></li>
<li>Window, frames and Popup dialog handling</li>
<li>Mobile automation</li>
</ol>
<p>Feedback on these topics would be much appreciated!</p>
<ul id="pagenavigation">
<li class="next"><a title="Introduction to Selenium" href="http://www.qaautomation.net/?p=4">Introduction to Selenium</a> : Next »</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.qaautomation.net/?feed=rss2&#038;p=365</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
		<item>
		<title>Mac OSx 10.7 Lion</title>
		<link>http://www.qaautomation.net/?p=328</link>
		<comments>http://www.qaautomation.net/?p=328#comments</comments>
		<pubDate>Thu, 21 Jul 2011 07:05:50 +0000</pubDate>
		<dc:creator>Rahul Poonekar</dc:creator>
				<category><![CDATA[What's new]]></category>

		<guid isPermaLink="false">http://www.qaautomation.net/?p=328</guid>
		<description><![CDATA[Today Apple released Mac OSx 10.7 Lion. Here are the steps to upgrade OSx and a Software Developer's take on the new OS.]]></description>
				<content:encoded><![CDATA[<p>Today Apple released Mac OSx 10.7 Lion. I thought it would be useful for others to see the steps to upgrade OSx and a Software Developer&#8217;s take on the new OS.</p>
<h1>Installation Steps</h1>
<p>If you are not on Snow Leopard, you will have to upgrade first. Once you are on Snow Leopard and have all the latest updates installed, open App Store application and buy the Mac OSx Lion. For $29.99, I consider this a very good deal!</p>
<p>The installer is about 3.74GB in size and it took me 35 mins to download it. Once it is downloaded and you click the Install button, you will see this screen.</p>
<p><img class="alignnone size-full wp-image-330" title="Mac OSx Lion Installer - Step1" src="http://www.qaautomation.net/wp-content/uploads/2011/07/MacOSxLionInstall_Step1.png" alt="" width="480" height="373" /></p>
<p>Then click Continue.</p>
<p><img class="alignnone size-full wp-image-331" title="Mac OSx Lion Installer - Step 2" src="http://www.qaautomation.net/wp-content/uploads/2011/07/MacOSxLionInstall_Step2.png" alt="Mac OSx Lion Installer - Step 2" width="480" height="373" /></p>
<p>Click Agree. You will be prompted for your mac user password. Enter it.</p>
<p><img class="alignnone size-full wp-image-332" title="Mac OSx Lion Installer - Step 3" src="http://www.qaautomation.net/wp-content/uploads/2011/07/MacOSxLionInstall_Step3.png" alt="Mac OSx Lion Installer - Step 3" width="480" height="373" /></p>
<p>Click Install and first the installer will start preparing for the install.</p>
<p><img class="alignnone size-full wp-image-333" title="Mac OSx Lion Installer - Step 4" src="http://www.qaautomation.net/wp-content/uploads/2011/07/MacOSxLionInstall_Step4.png" alt="Mac OSx Lion Installer - Step  4" width="480" height="373" /></p>
<p>Once it&#8217;s complete you will have to restart the OS to begin the installation.</p>
<p><img class="alignnone size-full wp-image-334" title="Mac OSx Lion Installer - Step 5" src="http://www.qaautomation.net/wp-content/uploads/2011/07/MacOSxLionInstall_Step5.png" alt="Mac OSx Lion Installer - Step 5" width="480" height="373" /></p>
<p>Once you click Restart, it will close any open applications.</p>
<p><img class="alignnone size-full wp-image-335" title="Mac OSx Lion Installer - Step 6" src="http://www.qaautomation.net/wp-content/uploads/2011/07/MacOSxLionInstall_Step6.png" alt="Mac OSx Lion Installer - Step 6" width="480" height="373" /></p>
<p>Once it restarts, the installation automatically starts, which takes about 30 mins.</p>
<p>Once the installation is complete, you will greeted at first by the Setup Assistant.</p>
<p><img class="alignnone size-full wp-image-336" title="Mac OSx Lion Installer - Step 8" src="http://www.qaautomation.net/wp-content/uploads/2011/07/MacOSxLionInstall_Step8.png" alt="Mac OSx Lion Installer - Step 8" width="480" height="373" /></p>
<p>Here you will have to move your mouse over the text that describes how scrolling works and using two fingers scroll down to a button that  says something like continue using Lion, which when you click will finish the Setup Assistant.</p>
<h1>Post Installation thoughts</h1>
<p>As a software developer I first checked if all my developer apps still worked. When I started IntelliJ, I was prompted to install java. Once I did that, IntelliJ worked just fine.</p>
<p><img class="size-full wp-image-338 alignleft" title="Disabled NX Client icon in Lion" src="http://www.qaautomation.net/wp-content/uploads/2011/07/disabled_app_icon.png" alt="Disabled NX Client icon in Lion" width="132" height="125" />I also use NX Client quite a bit at work and the <a title="NX Client 3.x desupported" href="http://www.nomachine.com/news-read.php?idnews=348">current GA version is not supported in Lion anymore</a>. Nomachine released a preview version that is already working for me on Lion though. So, I am all set.</p>
<p>As for the Lion look and feel, Mission control and the ability to create and remove desktops are the most useful to me. I have several apps running at any given point of time and now it does get a lot more convenient to organize them in a way that I can get to them quickly.</p>
<p>The scroll direction is opposite though and I don&#8217;t like it. It was easy to revert that by going to System Preferences &gt; Trackpad &gt; Scroll &amp; Zoom and disable the &#8220;Scroll direction: natural&#8221;.</p>
<p>Finally, it was time for me to check if my test automation tools (what this site really focuses on) continued to work on Lion.  As you might remember Selenium 1.0.1 stopped working after Snow Leopard was released. It was eventually fixed with the release of Selenium 1.0.3. I was glad to see that Selenium 2.3.0 did have any problems with Lion.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.qaautomation.net/?feed=rss2&#038;p=328</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Test Automation Principles</title>
		<link>http://www.qaautomation.net/?p=287</link>
		<comments>http://www.qaautomation.net/?p=287#comments</comments>
		<pubDate>Tue, 19 Jul 2011 10:35:48 +0000</pubDate>
		<dc:creator>Rahul Poonekar</dc:creator>
				<category><![CDATA[Concepts]]></category>

		<guid isPermaLink="false">http://www.qaautomation.net/?p=287</guid>
		<description><![CDATA[Following test automation principles goes a long way to make your testing reliable, which is the foundation for a successful test automation project. Here I have described consequences of deviating from these principles.]]></description>
				<content:encoded><![CDATA[<p>Several years ago, when I started with Test Automation, I hadn&#8217;t read, or wasn&#8217;t even aware  that there were any, principles of Test Automation. Initially I couldn&#8217;t get the tests to run reliably release over release. With a small number of tests it wasn&#8217;t too bad. But as the tests grew I would pretty much baby sit the execution. I would watch the execution and as soon as it would fail I would start investigating that failure. Once the problem was determined, whether it was a product bug or test issue, I would resume running the tests from that point onwards. I also would find myself running the tests in a certain order and worried about removing a test because something else could fail as a result of that. It didn&#8217;t feel very fulfilling even though I had my tests &#8220;automated&#8221;.</p>
<p>Over time I found that building tests in a certain way made the tests more reliable. I also started discussing with others what they did to keep their test suite robust to validate what I had learnt the hard way. Unfortunately searching for test automation principles on the internet wasn&#8217;t as useful as I hoped. Some of those principles, like &#8220;minimize untestable code&#8221; seemed like it was a product development principle as opposed to a test automation principle. Some others like &#8220;verify one condition per test&#8221; are good for unit testing but impractical for functional/ system tests. I also found some key principles missing in some of those lists. So, I am taking a stab here at describing what I think should be the Principles of Test Automation.</p>
<h2>Choose the right type of test automation methodology</h2>
<p>I broadly categorize automated testing as Unit, Component and System testing.</p>
<h3>Unit testing</h3>
<p>Unit testing is validation of the smallest part of the application. This smallest part in procedural languages is a function and in object oriented languages is a method in a class.</p>
<p>Since the focus of the unit test is very small, these tests can cover the entire code base, even if it&#8217;s not exercised by user flows. Also, they need the least amount of setup and teardown, so fewer things can go wrong &#8230; making them the least brittle. A combination of fewest assertions and least setup and teardown, make them the fastest as well. For these reasons, you should strive to have as much coverage as possible using unit tests.</p>
<p>There are several unit testing frameworks. In Java for instance, the commonly used ones are JUnit and TestNG. What causes confusion sometimes is that people use these frameworks to write tests that test a lot more than a function or a method. For example you could write a UI test using JUnit. That does not mean this is a unit test though. What advantages I described earlier about unit testing pertains to those tests that validate whether a function or method works correctly.</p>
<h3>Component testing</h3>
<p>When there are several components in the system, testing each component in isolation is called component testing. Most people are aware of the design practice of separating the Model View and Controller in the system. If you were to test the entire system integrated together, you would not be able to test capabilities in the Controller, for instance, that the Model and View weren&#8217;t utilizing. So, to test the Controller thoroughly, you would have to write component tests without Model and View.</p>
<p>The problem with writing tests against a component is that you need some system to provide the input to the component and/ or consume and validate the output of the component. In the real world, that would be what other dependent components would do. But for component testing, you have to add mocks or simulators for these dependent components that would mimic their expected behavior. The other big benefit of this is that it removes the possibility of failures due to bugs in those components.</p>
<p>As you can tell, component testing gives you more coverage of various execution paths than functional testing but not as much statement level coverage as unit testing.</p>
<h3>System or Functional testing</h3>
<p>The purpose of System testing, also called as Functional testing, is that it tests the entire system interacting with each other from an end user&#8217;s perspective.</p>
<p>When designing System tests and frameworks to execute system tests, you should be thinking black box testing. If the end user never interacts with the database the application uses for instance, ideally the system tests should not be validating data in the database. It should validate what the users see. This prevents the possibility of a false positive when the internals of the application is undergoing change even when the end user shouldn&#8217;t notice a change.</p>
<p>When running reliably, these tests tend to have the highest ROI. Especially when you are running the use cases that bring the highest value to the end user or generates revenue for the application/ service. The challenge ofcourse is to keep Functional tests reliable is the tricky part. Besides being brittle, they are slow making it hard to scale these tests. Also, they can cover only the code that is exposed to the end user. For these reason it&#8217;s best to automate only the high value flows and understand what the point of diminishing returns is.</p>
<h2>Keep the tests short</h2>
<p>Most of the times people write a unit test that tests one function. But frequently people forget that a unit test should contain a single assertion. They add multiple assertions for a single function, each time passing different input data combinations to the function under test. In this case when any assertion fails, it does not run the rest of the assertions and so the results don&#8217;t provide the granularity into all possible failures that exist.</p>
<p>For the same reason, keep the number of assertions as less as possible in component and system tests as well. Also, the longer the test, the more brittle it gets. The main reason why people tend to write long tests is because they want to cover an entire use case. Also they think while we are at this step, we can validate a few other things you normally would with manual testing. Don&#8217;t fall for these temptations and break your scripts into multiple tests with as few steps as possible in each of them.</p>
<h2>Keep tests independent</h2>
<p>No test should be dependent on another.</p>
<p>This isn&#8217;t very hard to follow but is one of the most common mistakes people make. When a use case has several steps, often people write every step as a separate test and then make the tests dependent on each other. The problem with this approach is ofcourse that you need to cannot run any one test in isolation, or you can&#8217;t easily choose a category of tests based on which area of the product is changing. Also, you need to track dependencies between them. One of the ways, I have seen people achieve time and time again, is by simply naming them in alphabetical order. This then leads to several problems when the workflow changes and the tests have to be reworked, or if your tests scale and you realize you can&#8217;t easily run the tests concurrently.</p>
<p>The right solution is to ensure that each test is independent and validates one step. Several times you can avoid the previous steps in the workflow by setting up the dependent data in the database baseline. When that is not possible, you can make them part of the setup of the test.</p>
<p>If you make it part of the setup, I prefer that the reports don&#8217;t show them as test failures. If I can&#8217;t show them as &#8220;not run&#8221; for any reason, I prefer to not have them in the report at all. This way you can avoid analysis paralysis and steps that really have failures are the only ones that are investigated.</p>
<h2>Tests should be idempotent</h2>
<p>If the tests can be executed over and over again and with the same results, they are considered idempotent. If the tests aren&#8217;t designed to be idempotent, then you have to take a lot of measures to ensure they are executed just once and then the test environment is rebuilt. This makes it cumbersome to reproduce failures while debugging and can lead to undesired inefficiency and/or inflexibility in the way tests are executed.</p>
<h2>Tests should be deterministic</h2>
<p>Having indeterminacy in tests undermines any test automation effort because no body trusts the results. One of the easy ways to tell if a test is indeterminant is if it fails because of a false positive. A false positive is when a test case fails not because of a bug in the System Under Test (SUT) or Application Under Test (AUT) but because of a problem in the test or the framework/ tools it is built upon.</p>
<p>What most people don&#8217;t realize is that tests that never fail dues to false positives can also be indeterminant. Imagine the AUT is an application that allows you to make purchases using credit cards or reward points. If the tests were written in such a way that you would use the reward points on a test credit card to make a purchase if you had enough points and use credit if not, the test wouldn&#8217;t fail because one or the other scenario would work. But, you wouldn&#8217;t know for sure if both the code paths were covered. If you had a million points before running the suite, it could be that every test ran using the rewards code path and it would fail to catch potential bugs in the credit code path. A determinant test on the other hand would always test one code path or the other no matter how many times you ran the test.</p>
<h2>Minimize incidental test coverage</h2>
<p>Incidental test coverage means that you are exercising code of the SUT that you aren&#8217;t intending to test. This happens when you essentially cover code by performing necessary steps to reach the validation point (assertion) that you really want to test. If you use code coverage tools, this gives you a false feeling of confidence that you have good coverage. In such situations, you should add tests for those areas of your product that you are covering as part of setup or teardown steps.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.qaautomation.net/?feed=rss2&#038;p=287</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
	</channel>
</rss>
