Showing posts with label selenium. Show all posts
Showing posts with label selenium. Show all posts

Thursday, May 29, 2014

Selenium WebDriver test in C#

I was trying simple C# test by using Selenium. It is very simple to use and noticed that few changes. You should have NUnit, Visual Studio 2013 and Selenium DLLs. You can go through the links, which are available at the end of post.

Bing Search - Selenium Test - C# Code

using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using OpenQA.Selenium; using OpenQA.Selenium.Support; using OpenQA.Selenium.IE; using NUnit.Framework; namespace BingSearch { [TestClass] public class SearchTests { public static IWebDriver WebDriver; [TestInitialize] public void setupAppTest() { try { System.Console.WriteLine("Test setup started..."); InternetExplorerOptions ieOptions = new InternetExplorerOptions(); ieOptions.IntroduceInstabilityByIgnoringProtectedModeSettings = true; ieOptions.IgnoreZoomLevel = true; WebDriver = new InternetExplorerDriver(ieOptions); } catch (Exception ex) { System.Console.WriteLine("Exception Occured in Init @ " + ex.Source); } } [TestMethod] public void testBingSearch() { //Navigate to the site WebDriver.Navigate().GoToUrl("http://www.bing.com"); // Get Search text field info IWebElement query = WebDriver.FindElement(By.Name("q")); // Enter Search String query.SendKeys("Selenium"); // Submit the form query.Submit(); // Sleep for 5 seconds System.Threading.Thread.Sleep(5000); //Get all the links from result page System.Collections.ObjectModel.ReadOnlyCollection links = WebDriver.FindElements(By.TagName("a")); //Print all the links foreach (IWebElement link in links) { System.Console.WriteLine(link.GetAttribute("href")); } //Assert the title text Assert.AreEqual("Selenium - Bing", WebDriver.Title); } [TestCleanup] public void testCleanup() { // Cleanup activites WebDriver.Quit(); WebDriver.Dispose(); System.Console.WriteLine("Test cleanedup & completed successfully.."); } } }


Below links might be useful to make setup to execute the Selenium tests.
How To - Setup C#, NUnit, Selenium
Capturning Screenshots

Monday, February 22, 2010

Selenium RC configuration for Java

Few months back, I was trying to run selenium script with Selenium RC Java. Initially I faced few issues to configure the classpath settings. We need to pass the proxy details, if the net connection is based on proxy. I created three batch scripts to run the server and client. You should have latest java version. For more info about Selenium RC, check out Selenium RC documentation .

Selenium Server to start with proxy
Here user can set the username and password for proxy connection. Checkout java options to do that.

REM ******************************************** REM To Run Selenium server REM Author: Palani Selvam REM ******************************************** REM Selenium server path set SeleniumServer=D:\Selenium_trial\tool\selenium-remote-control-0.9.2\selenium-server-0.9.2 REM to run the Selenium server with proxy d: cd %SeleniumServer% java -Dhttp.proxyHost=proxy.mycompany.com -Dhttp.proxyPort=8080 -jar selenium-server.jar

Selenium Server to start without proxy
It will be useful for non-proxy connection.
REM ******************************************** REM To Run Selenium server REM Author: Palani Selvam REM ******************************************** REM Selenium server path set SeleniumServer=D:\Selenium_trial\tool\selenium-remote-control-0.9.2\selenium-server-0.9.2 REM to run the Selenium server without proxy d: cd %SeleniumServer% java -jar selenium-server.jar

To run the Selenium client
Below I have given the batch script to run the GetAllStockQuotes.java. Source code is available at Indian Stock Quotes through Selenium

REM ******************************************** REM To Run Selenium client (Java). Also sets path and classpath REM Author: Palani Selvam REM ******************************************** REM to set class path and path env variables to run selenium set javaClientPath=D:\Selenium_trial\tool\selenium-remote-control-1.0.1\selenium-java-client-driver-1.0.1 Set javaClientJars=%javaClientPath%\selenium-java-client-driver.jar REM JUnit jar Set jUnitJars=D:\java\JUnit\junit46.jar REM Selenium Script (Java) dir path set Stockspath=D:\Selenium_trial REM Setting classpath set classpath=%classpath%;%javaClientJars%;%jUnitJars%;%Stockspath%\classes; d: cd %Stockspath% REM Compiling test scripts Selenium-java code javac -d classes GetAllStockQuotes.java REM Running the test scripts java junit.textui.TestRunner com.palani.tests.GetAllStockQuotes

For more details of Selenium tools configuration, you can refer 5 Minute Guide To Selenium IDE and Selenium Remote Control (Java) Test Tools

Saturday, January 30, 2010

Indian Stock Quotes through Selenium

I thought to get the current indian (NSE) stock quotes by using Selenium tool. I chose Selenium RC and Java language. I have developed a java class for all file related tasks. Another java program used to get the stock values from set of given scrips.

Selenium RC required set of configuration to run the tests. We need to give the proxy details (with or without proxy) for internet connection. I'm planning to cover the configuration in upcoming posts. Below I have given the java code to get current stock values.

Current Stock quotes - Selenium RC with Java
Note: FileHandlerLib class - file related tasks.

/* To get all stockquotes * To Compile: javac GetAllStockQuotes.java -Xlint:unchecked * To Run: java junit.textui.TestRunner com.palani.tests.GetAllStockQuotes * To Run: java GetAllStockQuotes * Note: Recompile with -Xlint:unchecked for details. * javac FileHandlerLib.java -Xlint:unchecked */ package com.palani.tests; // import FileHandlerLib; import com.palani.utils.*; import com.thoughtworks.selenium.*; import junit.framework.*; import java.util.regex.Pattern; import java.io.*; import java.util.*; import java.text.DateFormat; import java.text.SimpleDateFormat; public class GetAllStockQuotes extends SeleneseTestCase { private Selenium selenium; private FileHandlerLib fhNew = new FileHandlerLib(); // @Before public void setUp() throws Exception { selenium = new DefaultSelenium("localhost", 4444, "*iexplore", "http://www.nseindia.com/"); selenium.start(); } // @Test public void testGetAllStockQuotes() throws Exception { // Variables String sScripsFile; String sQuotesFile; String sUrlPart; String sCurrentDate; String sQuote; String sQuoteValue; String sOutput; ArrayList aData = new ArrayList(); // Initialization // sCurrentDate = "20100101" ; sCurrentDate = fhNew.getDateTime(); sQuotesFile = "D:\\Stocks\\"+sCurrentDate+"_stocks.txt"; fhNew.DeleteFile (sQuotesFile); sScripsFile = "D:\\Stocks\\StockScrips.txt"; sUrlPart="/marketinfo/companyinfo/companysearch.jsp?cons="; aData = fhNew.ReadFileToArray (sScripsFile); Object[] elements = aData.toArray(); System.out.println ("SCRIPs File: " + sScripsFile); System.out.println ("Quotes File: " + sQuotesFile); selenium.open("/content/equities/cmquote.htm"); Thread.sleep(2000); for(int iIndex=0; iIndex < elements.length ; iIndex++) { sQuote=(String)elements[iIndex]; sQuote=sQuote.trim(); sQuoteValue = "0"; System.out.println("Quote:"+elements[iIndex]+ " ,index: " + iIndex); if (!(sQuote.equals("") ) ) { if (selenium.isElementPresent("companyname")) { selenium.type("companyname", sQuote); } else { selenium.type("company", sQuote); } selenium.click("submit1"); Thread.sleep(2000); for (int second = 0;; second++) { if (second >= 150) System.out.println("timeout"); try { if (selenium.isElementPresent("//div[@id='PI4']/b")) { sQuoteValue = selenium.getText("//div[@id='PI4']/b"); System.out.println ("Quote Value: " + sQuoteValue); sOutput=sQuote.trim()+","+sQuoteValue.trim(); fhNew.FileWrite (sQuotesFile,sOutput); break; } // end if } catch (Exception e) { System.out.println("Selenium Run: " + e.getMessage() + "\n"); e.printStackTrace(); } Thread.sleep(1000); } } // End If } // end for loop } // @After public void tearDown() { selenium.stop(); } // To run Selenium Testcase using JUnit public static Test suite() { return new TestSuite(GetAllStockQuotes.class); } // To run Selenium Testcase public static void main(String args[]) { junit.textui.TestRunner.run(suite()); } }

Sunday, August 2, 2009

Selenium Overview

Selenium is a suite of tools to automate web app testing across many platforms. It is a GUI based automation tool. Initially it is built by ThoughtWorks. It supports various browsers on various platforms.

Selenium Home Page
Selenium Projects
Tool History
Platform Support

Selenium Projects
Selenium has many projects. Following projects are mostly used by testers.


  1. Selenium IDE (IDE)
    Selenium IDE can be used only in FireFox. It is an add-on for FireFox. User can record the actions and can edit and debug the tests. It can be used to identify IDs, name and XPath of objects. Only one test at a time.

  2. Selenium Core (CORE)
    Selenium Core is the original Javascript-based testing system. This technique should work with any JavaScript enabled browser. It is the engine of both, Selenium IDE and Selenium RC (driven mode), but it also can be deployed on the desired application server. It is used specifically for the acceptance testing.
    User can record the tests using Selenium IDE and can use the same tests to run in other browsers with minimal modifications. It provides support to run the tests in HTA (HTML Applications) Mode. This mode works only in IE.

  3. Selenium Remote Control (RC)
    Selenium Remote Control is a test tool that allows user to write automated web application UI tests in few programming languages against any HTTP website using any mainstream JavaScript-enabled browser. User can write the tests (More expressive programming language than the Selenese HTML table format) in Java, DotNet, Perl, Ruby and PHP. Also it supports few testing frameworks.

  4. Selenium Grid
    Selenium Grid allows easily to run multiple tests in parallel, on multiple machines, in an
    heterogeneous environment by cutting down the time required for test execution. Using this, user can run multiple instances of Selenium Remote Control in parallel.

Supported browsers
Selenium tools can run in following browsers.
  • Internet Explorer
  • FireFox
  • Opera
  • Safari
  • Seamonkey

Supported Operating Systems
Users can execute the selenium tests in following OS.
  • Windows
  • Linux
  • Solaris
  • OS X

Supported Programming languages
Below languages are supported by Selenium RC.
  • C# (DotNet)
  • Java
  • Perl
  • Ruby
  • Python
  • PHP

Lot of presentations and documents about Selenium are shared in SlideShare. You can do simple search and get many docs.

Recorded Selenese code through IDE
 

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head profile="http://selenium-ide.openqa.org/profiles/test-case">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="selenium.base" href="" />
<title>GoogleSearch2</title>
</head>
<body>
<table cellpadding="1" cellspacing="1" border="1">
<thead>
<tr><td rowspan="1" colspan="3">GoogleSearch2</td></tr>
</thead><tbody>
<tr>
<td>open</td>
<td>/</td>
<td></td>
</tr>
<tr>
<td>type</td>
<td>q</td>
<td>silk4j tutorial</td>
</tr>
<tr>
<td>click</td>
<td>btnG</td>
<td></td>
</tr>
<tr>
<td>waitForPageToLoad</td>
<td>30000</td>
<td></td>
</tr>
<tr>
<td>type</td>
<td>q</td>
<td>Silktest extension kit</td>
</tr>
<tr>
<td>click</td>
<td>btnG</td>
<td></td>
</tr>
<tr>
<td>waitForPageToLoad</td>
<td>30000</td>
<td></td>
</tr>
<tr>
<td>click</td>
<td>btnG</td>
<td></td>
</tr>
<tr>
<td>waitForPageToLoad</td>
<td>30000</td>
<td></td>
</tr>

</tbody></table>
</body>
</html>

Java code - Selenium RC
 

package com.example.tests;

import com.thoughtworks.selenium.*;
import java.util.regex.Pattern;

public class NewTest extends SeleneseTestCase {
public void setUp() throws Exception {
setUp("http://www.google.com/", "*chrome");
}
public void testNew() throws Exception {
selenium.open("/");
selenium.type("q", "silk4j tutorial");
selenium.click("btnG");
selenium.waitForPageToLoad("30000");
selenium.type("q", "Silktest extension kit");
selenium.click("btnG");
selenium.waitForPageToLoad("30000");
selenium.click("btnG");
selenium.waitForPageToLoad("30000");
System.out.println("New Test is completed.");
}
public void tearDown() {
browser.stop();
}
}

Sunday, July 5, 2009

Silk4J Overview & Analysis

Silk4j was introduced from Silktest 2008. Hereafter user can use Java as test scripting language with the help of Silk4J Package. It is supported only with Open Agent. I hope that Borland might target developers too. User can write java unit tests as well as GUI tests.

From Silktest Help - Silk4J Eclipse Plugin

Silk4J enables user to create functional tests using the Java programming language. Silk4J provides a Java runtime library that includes test classes for all the classes that Silk4J supports for testing. This runtime library is compatible with JUnit, which means you can leverage the JUnit infrastructure and run and create tests using JUnit. You can also use all available Java libraries in your testcases.

The testing environments that Silk4J supports include:

  • Adobe Flex applications
  • Java SWT applications
  • Windows Presentation Foundation (WPF) applications
  • Windows API-based client/server applications
  • xBrowser applications


Silk4J with Open Agent - Google Search testcase

I have gone through documents such as Silk4J_QuickStartGuide_en.pdf and Silk4J_AdvancedUserGuide_en.pdf. I created the sample code and it works fine.

package com.palani;
import org.junit.Before;
import org.junit.Test;

import com.borland.silktest.jtf.Desktop;
import com.borland.silktest.jtf.TechDomain;
import com.borland.silktest.jtf.xbrowser.BrowserWindow;
import com.borland.silktest.jtf.xbrowser.DomButton;
import com.borland.silktest.jtf.xbrowser.DomTextField;

public class GoogleSearch {
private Desktop desktop = new Desktop();
private BrowserWindow browser;

@Before
public void setUp() throws Exception {

browser = (BrowserWindow)desktop.executeBaseState(
"C:/Program Files/Internet Explorer/iexplore.exe", null, null,
".//BrowserWindow", TechDomain.XBROWSER);
browser.navigate("http://www.google.co.in/");
}

@Test
public void testSimpleGoogleSearch() throws Exception {

DomTextField searchText = (DomTextField)browser.find (".//DomTextField[@title='Google Search' and @name='q']");
searchText.setText("");
searchText.setText("silk4j tutorial");
DomButton btn = (DomButton)browser.find(
".//DomButton[@type='submit' and @name='btnG']");
btn.click();
}
}


4Test with Open Agent - Google Search testcase
The same case is written in 4Test. SilkTest supports a subset of the XPath query language. It gives dynamic object recognition.

[ ]
[-] testcase GoogleSearch1 () appstate none //DefaultBaseState
[ ] STRING sUrl="http://www.google.co.in/"
[ ]
[-] if (! InternetExplorer.Exists(2))
[ ] InternetExplorer.Invoke ()
[ ] InternetExplorer.SetActive ()
[ ] InternetExplorer.Maximize ()
[ ]
[ ] WINDOW wMain = Desktop.Find(".//BrowserApplication")
[ ] WINDOW wBrowser = wMain.Find(".//BrowserWindow")
[ ]
[ ] wMain.SetActive()
[ ] wBrowser.Navigate (sUrl)
[ ] WINDOW wText1=wBrowser.Find(".//DomTextField[@title='Google Search' and @name='q']")
[ ] wText1.SetText("Silk4j Tutorial")
[ ] wBrowser.Find(".//DomButton[@name='btnG' ]").Click ()
[ ]
[ ] WINDOW wText2=wBrowser.Find(".//DomTextField[@name='q']")
[ ] wText2.SetText("Silktest Extension Kit")
[ ] wBrowser.Find(".//DomButton[@name='btnG' ]").Click ()
[ ]
[ ]


Selenium RC Java format - Google Search testcase

Selenium is a open source tool and can be used only web based applications. But user can choose different languages to develop the suite. Selenium tests can be written with Selenese, PHP, Perl, Python, Ruby, DotNet and Java.

import org.openqa.selenium.server.SeleniumServerTest;
import com.thoughtworks.selenium.*;
import junit.framework.*;
import org.openqa.selenium.server.SeleniumServer;

public class TestSearch extends SeleniumServerTest {
private Selenium browser;
public void setUp() throws Exception {
SeleniumServer seleniumServer = new SeleniumServer();
browser = new DefaultSelenium("localhost", 5555, "*firefox", "http://www.google.com");
seleniumServer.start();
browser.start();
}

public void testGoogle() {
browser.open("/webhp?hl=en");
browser.type("q", "hello world");
browser.click("btnG");
browser.waitForPageToLoad("5000");
assertEquals("hello world - Google Search", browser.getTitle());
}

public void tearDown() {
browser.stop();
}
}


Few Questions

Now Silktest and selenium both supports in Java language. Silktest supports many type of applications. In other end, Selenium supports many Operating Systems and browsers. I have few questions on Silk4J.
  1. Can Silk4J utilize silktest features such as TestcaseEnter,TestcaseExit,scriptEnter and ScriptExit?
  2. Target audience?
  3. Any Success stories (implementations)?