IT Staff

Blog về chuyên ngành IT

Selenium FAQ Collection

leave a comment »

Selenium

Selenium webdriver

/* TIP [1]
* ———————————————————————————
* Take a screenshot with Selenium WebDriver – Stack Overflow
* ———————————————————————————
*/

JAVA

WebDriver driver = new FirefoxDriver();
driver.get("http://www.google.com/");
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
// Now you can do whatever you need to do with it, for example copy somewhere
FileUtils
.copyFile(scrFile, new File("c:\\tmp\\screenshot.png"));

C# Jimmy’s Blog

IWebDriver driver = new FirefoxDriver();
driver.Navigate().GoToUrl(“https://itstaff.wordpress.com“);
Screenshot ss = ((ITakesScreenshot) driver ).GetScreenshot ();
ss.SaveAsFile(“c:\\tmp\\screenshot.png“, ImageFormat.Png);

/* TIP [2]
* ———————————————————————————
* How can I get site’s favicon using Selenium – Stack Overflow
* ———————————————————————————
*/

I need to get web site’s favicon.

How can I do that?

You won’t be able to get the favicon with Selenium you would have to use another program to grab it. The only way you would be able to get it is if your website rendered the favicon.ico as a link such as

<link rel="shortcut icon" href="http://example.com/myicon.ico" /> 

However typically websites just store the favicon.ico in the root directory and on page request the browser retrieves it and drops it in the address bar or tab or wherever favicons are used. If this is how your favicon is rendered then there will be no code or anything to search for with Selenium.

Also the above code while it does work has some buggy support for IE7.

/* TIP [3]
* ———————————————————————————
* Running Selenium Tests with C# & NUnit – Jimmy’s Blog
* ———————————————————————————
*/

Download requirements:

Now, let’s create the actual test:

  1. Launch Visual Studio 2010 and create a new class library project.
  2. Add a reference to nunit.framework.dll. This can be found under the NUnit installation directory at ‘bin\net-2.0\framework’.
  3. Add references to all the DLL’s contained in the Selenium Client Driver package you downloaded earlier.
  4. We’re now ready to add the code that will run a Selenium test. Add the following code to your class library project:
C#
using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.IE;namespace FirstSeleniumTest
{
[TestFixture]
    public class SeleniumTest
{
private IWebDriverdriver;        [SetUp]
public void SetUp()
{
driver = new InternetExplorerDriver();
}[Test]
public void TestGoogle()
{
driver.Navigate().GoToUrl(“http://www.google.com“);
}[TearDown]
public void TearDown()
{
driver.Quit();
driver.Dispose();
}
}
}

The above code should be pretty easy to understand. Notice the annotations around the functions.

  • [SetUp] – This is where any test setup should be completed. In the above example we’re creating a new instance of InternetExplorerDriver, setting it up for our test to run later.
  • [Test] – This is where the test steps are defined. In this example, we’re just navigating to Google.
  • [TearDown] – In this section, any steps to be taken to cleanup the environment after your test has run can be defined. Here, all we’ll do is close Internet Explorer

Now that we have written a simple test, let’s try running it using NUnit. Before moving on, ensure that the above code builds successfully in your environment.

To run the test it’s just a matter of launching NUnit and opening up the DLL built from the Visual Studio project created above. You should see the ‘TestGoogle’ test listed. Simply select the test and hit the ‘Run’ button to initiate the test. You will see Internet Explorer launch, and then close.

NUnit

One thing you may need to do, depending on your IE version, is to disable protected mode for Internet and Restricted Zones in Internet Explorer Security Settings (don’t forget to re-enable these once you’ve finished experimenting with Selenium).

/* TIP [4]
* ———————————————————————————
* Find a selected radiobutton via Selenium/Webdriver – Stack Overflow
* ———————————————————————————
*/

I’m using Selenium 2 (Webdriver) for automating tests on a webpage. However I wonder if there is way to find out if a radiobutton is selected or not using webdriver framework?

I can find the element and click it by using Click() method. I would like to test that it actually was set, or is that implicit done by the Click() method on IWebElement object?

(Using C# and NUnit)

You can determine if an element is selected by catching the element and then checking selected.

IWebElement thisElement = driver.FindElement(By.ID(//radiobutton id));  if(thisElement.Selected) { //do something here. }  you can do this other ways but the .Selected is what you are looking for. 

/* TIP [5]
* ———————————————————————————————
* How to test RichFaces combobox with Selenium Webdriver? – Stack Overflow
* ———————————————————————————————
*/

We have an application based on RichFaces 3.3.3 . We have created automated tests with Selenium IDE that run fine. Since the RichFaces comboboxes are not real html comboboxes but an input field with a bunch of javascript, in Selenium we need to select a value with the following trick:

type field_id "field value" typeKeys field_id "field value" fireEvent field_id "blur" 

In order to integrate the tests into our continuous integration system, we have transformed the test to jUnit tests that use WebDriver (Selenium 2.5.0) as the backend. Unfortunately the combobox trick stopped working.

All type and typeKeys commands are translated as shown below:

// ERROR: Caught exception [ERROR: Unsupported command [fireEvent]] driver.findElement(By.id("patientCreateDataForm:patientBirthDateInputDate")).clear(); driver.findElement(By.id("patientCreateDataForm:patientBirthDateInputDate")).sendKeys("16.06.1910"); 

Does anyone have any working solution to test RichFaces combobox elements?

Thanks in advance!


The solution is as follows:

  1. click in the RichFaces combobox
  2. select the item (male or female) and copy path with help FirePath
  3. thereafter use Actions method in jUnit test. In the following example, button parameter is a combobox button id, element parameter is selected items xpath:
private void comboboxSolution(String element, String button)
{
WebElement btn = driver.findElement(By.id(button));
    btn.click();
    WebElement myElement = driver.findElement(By.xpath(element));
    Actions builder = new Actions(driver);
    builder.moveToElement(myElement).click().perform();
}
/* TIP [5]
 * ---------------------------------------------------------------------------------------------
 * Selenium - Exception while executing selenium.stop()? - Stack Overflow 
 * ---------------------------------------------------------------------------------------------
 */
Here's is code which is executing the stop() command 
public class orkut extends SeleneseTestCase { public void setUp() throws Exception { setUp("https://www.google.com/"); } public void testOrkut() throws Exception { Parser parser = new Parser(); try { ....... ....... ....... }catch(Exception ex) { }finally { parser.closeConnection(); selenium.shutDownSeleniumServer(); } } public static Test suite() { return new TestSuite(orkut.class); } public void tearDown(){ selenium.stop(); } public static void main(String args[]) { junit.textui.TestRunner.run(suite()); } } 

It looks like your shutting down the Selenium server before the command to close the browser session. Try commenting out the line with selenium.shutDownSeleniumServer();

/* TIP [6]
  * ———————————————————————————————
  * HttpHostConnectException occured while executing multiple test
  * in junit using Selenium2 WebDriver – Stack Overflow
  * ———————————————————————————————
  */

I am using Selenium 2.0 with the WebDriver. I am not using the TestCaseBase, etc. I am using only the webdriver.

I am also using JUnit with the Parameterized test. When running tests with the IEDriver – the first test runs fine, the second test gets a org.apache.http.conn.HttpHostConnectException.

Does anyone have experience with this? Does this seem like a bug or bad code?

Thanks in advance.

try use driver.quit() instead of driver.close()

see this: http://groups.google.com/group/webdriver/browse_thread/thread/6ade9e6ae1861a2/e1fd6423589b5d1d?lnk=gst&q=internetexplorerdriver+connection++refuse#e1fd6423589b5d1d

/* TIP [7]
  * ———————————————————————————————
  * Selenium Exception : “return not in a function”Stack Overflow
  * ———————————————————————————————
  */

I am writing Selenium test scripts in C#.Net and I keep bumping into this exception –

ERROR:Threw an exception:return not in function 

Here is my line of code which throws the error –

string code = selenium.GetEval(    "var win = this.browserbot.getUserWindow(); "+    "return win.editAreaLoader.GetValue(win.loadedCodeEditorID);");

Can anyone please suggest why the exception is coming and what could be the best way to get a return value from GetValue javascript function?

From the selenium documentation for GetEval:

Gets the result of evaluating the specified JavaScript snippet. The snippet may have multiple lines, but only the result of the last line will be returned.

Therefore you simply need to leave off the return:

string code = selenium.GetEval(    "var win = this.browserbot.getUserWindow(); "+    "win.editAreaLoader.GetValue(win.loadedCodeEditorID);"); 

/* TIP [8]
  * ———————————————————————————————————————-
  * Selenium exception when attempting to click ID of a button Stack Overflow
  * ———————————————————————————————————————-
  */


I’m attempting to use the Java Selenium client with JBehave to interact with a simple web page as a demonstration of BDD techniques.

When running the test, i’m trying to do a simple

selenium.click("joinButton");

but i’m getting a

(com.thoughtworks.selenium.SeleniumException: joinButton is not defined)

exception thrown.

I’ve tried qualifying the ID as a dom ID using id=joinButton, as a css selector and even as xpath but to no avail.

The element is definitely rendered in the page. I’m clearly doing something daft here.

I realised what the issue was here.  The Selenium class was being 
extended, and the click method overridden to only accept CSS selectors. 
 With this cruft now removed, the operation works as expected.

/* TIP [9]
  * ———————————————————————————————————————-
  * C# Exception: NullReferenceExceptionStack Overflow
  * ———————————————————————————————————————-
  */


I am getting the following message whilt running my test.

Message:

Test method Automation.Test1.General threw exception: System.NullReferenceException: Object reference not set to an instance of an object.

Automation.Library.CheckLogIn() in C:\Documents and Settings\Administrator\My Documents\Visual Studio 2010\Projects\Automation\Automation\Library.cs: line 152

Automation.Test1.General() in C:\Documents and Settings\Administrator\My Documents\Visual Studio 2010\Projects\Automation\Automation\Test1.cs: line 72

Library.cs (superclass)

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading; using Microsoft.VisualStudio.TestTools.UnitTesting; using Selenium; using System.IO; using System.Reflection; using System.Net; using System.Configuration; namespace Automation{[TestClass]publicclassLibrary{     publicISeleniumSel;     // Open browser     publicvoidOpenBrowser(outISelenium selenium,outStringBuilder verificationErrors)     {         selenium =newDefaultSelenium(GetAppConfig("TestMachine"),4444,GetAppConfig("Browser"),GetAppConfig("URL"));         selenium.Start();         selenium.Open(GetAppConfig("URL"));         verificationErrors =newStringBuilder();     }     // Returns the value of the passed key from App.config     publicstringGetAppConfig(string key)     {         returnConfigurationManager.AppSettings[key].ToString();     }     // Check for  Login     publicvoidCheckLogIn()     {         if(Sel.IsElementPresent(GetAppConfig("SignOn")))         {             Sel.Type(GetAppConfig("UserNameField"),GetAppConfig("UserName"));             Sel.Type(GetAppConfig("PWDField"),GetAppConfig("PWD"));             Sel.Click(GetAppConfig("Go"));         }         else         {             // do nothing         }     }}

}

Test1.cs (sub class)

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading; using Microsoft.VisualStudio.TestTools.UnitTesting; using Selenium; using System.IO; using System.Reflection; using System.Net; using System.Configuration; namespace Automation{[TestClass]publicclassTest1{     publicISeleniumSel;     publicStringBuilderErr;     Boolean bNextFlag =false;     LibraryLib=newLibrary();     // Constructor     publicTest1()     {         // Launch browser with application URL         Lib.OpenBrowser(outSel,outErr);         Sel.WindowMaximize();         Lib.CheckLogIn();     }     [TestMethod]     publicvoidGeneral()     {         // Verify  Tab         if(Sel.IsElementPresent(Lib.GetAppConfig("TAB")))         {             Sel.Click(Lib.GetAppConfig("TAB"));             bNextFlag =true;         }         else         {            // do something         }     }}

}

app.config.xml

<?xml version="1.0" encoding="utf-8"?>
<add key="TestMachine" value="localhost"/><add key="Browser" value="*iexplore"/><add key="URL" value="http://localhost//Default.aspx"/><!--CheckLogIn--><add key="SignOn" value="//*[@id=&quot;LogIn&quot;]"/><add key="UserNameField" value="//*[@id=&quot;username&quot;]"/><add key="PWDField" value="//*[@id=&quot;pwd&quot;]"/><add key="Go" value="//*[@id=&quot;gobutton&quot;]"/><add key="UserName" value="admin"/><add key="PWD" value="password"/><!--End of  CheckLogIn--><!--ObjectDefinitions--><add key="TAB" value="//*[@id=&quot;Tab&quot;]"/><!--End of ObjectDefinitios-->

Well I don’t really see a question in your post, so I suppose I will point out the obvious…

Your error is telling you that you have a NullReferenceException being thrown somewhere in this method:

publicvoidCheckLogIn(){     if(Sel.IsElementPresent(GetAppConfig("SignOn")))     {         Sel.Type(GetAppConfig("UserNameField"),GetAppConfig("UserName"));         Sel.Type(GetAppConfig("PWDField"),GetAppConfig("PWD"));         Sel.Click(GetAppConfig("Go"));     }     else     {         // do nothing     }}

Sel is null. Nowhere in your code do you actually initialize it. You’ll need to initialize it somewhere like:

Sel=newSomeTypeThatImplementsISelenium();

Also, GetAppConfig is depricated per the docs.

/* TIP [10]
  * ———————————————————————————————————————-
  Stack Overflow
  * ———————————————————————————————————————-
  */

DRAFT

IWebElement thisElement = driver.FindElement(By.ID(//radiobutton id));
if(thisElement.Selected) { //do something here. }

 


ere’s is code which is executing the stop() command

public class orkut extends SeleneseTestCase { public void setUp() throws Exception { setUp("https://www.google.com/"); } public void testOrkut() throws Exception { Parser parser = new Parser(); try { ....... ....... ....... }catch(Exception ex) { }finally { parser.closeConnection(); selenium.shutDownSeleniumServer(); } } public static Test suite() { return new TestSuite(orkut.class); } public void tearDown(){ selenium.stop(); } public static void main(String args[]) { junit.textui.TestRunner.run(suite()); } } 

Written by Xavier

Tháng Tư 5, 2012 lúc 5:08 sáng

Gửi phản hồi

Mời bạn điền thông tin vào ô dưới đây hoặc kích vào một biểu tượng để đăng nhập:

WordPress.com Logo

Bạn đang bình luận bằng tài khoản WordPress.com Log Out / Thay đổi )

Twitter picture

Bạn đang bình luận bằng tài khoản Twitter Log Out / Thay đổi )

Facebook photo

Bạn đang bình luận bằng tài khoản Facebook Log Out / Thay đổi )

Google+ photo

Bạn đang bình luận bằng tài khoản Google+ Log Out / Thay đổi )

Connecting to %s

%d bloggers like this: