http://automationtestingutilities.blogspot.nl/p/blog-page_11.html
Selenium Grid
Step 1: Start the hub
The Hub is the central point that will receive all the test request and distribute them the right nodes.
Open a command prompt and navigate to the directory where you copied the selenium-server-standalone file. Type the following command:
java -jar selenium-server-standalone-2.14.0.jar -role hub
The hub will automatically start-up using port 4444 by default. To change the default port, you can add the optional parameter -port when you run the command. You can view the status of the hub by opening a browser window and navigating to: http://localhost:4444/grid/console
Step 2: Start the nodes
Regardless on whether you want to run a grid with new WebDriver functionality, or a grid with Selenium 1 RC functionality, or both at the same time, you use the same selenium-server-standalone jar file to start the nodes.
java -jar selenium-server-standalone-2.14.0.jar -role node -hub http://localhost:4444/grid/register
java -jar selenium-server-standalone-2.42.2.jar -role webdriver -hub http://10.74.197.103:4444/grid/register -port 5555 -Dwebdriver.ie.driver=C:\IEDriverServer.exe
For Safari In Mac OS X
java -jar selenium-server-standalone-2.39.0.jar -role node -hub http://xx.xxx.xxx.xxx:4444/grid/register -browser browserName=safari,platform=MAC
Sample project for Selenium Grid:-
TestBase.java
package com.seleniumgrid.TestBase;
import java.net.MalformedURLException;
import java.net.URL;
import org.openqa.selenium.Platform;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Parameters;
public class TestBase {
protected WebDriver driver;
@BeforeTest
public void init(){
DesiredCapabilities caps = DesiredCapabilities.chrome();
caps.setPlatform(Platform.VISTA);
caps.setBrowserName(“chrome”);
try {
driver = new RemoteWebDriver(new URL(“http://10.74.196.211:4444/wd/hub”),caps);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@AfterTest
public void teardown(){
driver.quit();
}
}
Create some 4 test classes as shown below:-
package com.seleniumgrid.TestScripts;
import org.testng.annotations.Test;
import com.seleniumgrid.TestBase.TestBase;
public class Test1 extends TestBase{
@Test
public void test1() {
driver.get(“http://www.google.com/”);
}
}
TestNG XML file should be as shown below:-
Maven Command to create maven project
mvn archetype:generate –DgroupId=com.mycompany.app -DartifactId=my-app -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
mvn archetype:generate: – This command is used to create a project from an existing template. In Maven 3.1.1 there are 1000+ templates. When you run this command maven does the following
- Downloads maven-archetype-plugin’s latest version.
- If you type only this command (i.e., mvn archetype:generate) It will lists all the archetype’s that can be used to create a project from.
groupId: – This is generally unique amongst an organization or a project.
artifactId: – The artifactId is generally the name that the project
archetypeArtifactId: – If you want to create a specific type of application, you should find the archetype matching your needs. Here we are creating maven-archetype-quickstart archetype which basically creates a maven Hello World project with source and test classes.
interactiveMode: – If you know which archetypeArtifactId to use, we can skip the command in interactive mode by giving ‘false’ to interactiveMode
Once you run this command Maven will download the most recent artifacts (plugin jars and other files) into your local repository. You may also need to execute the command a couple of times before it succeeds. This is because the remote server may time out before your downloads are complete. Don’t worry, there are ways to fix that.
You will notice that the generate goal created a directory with the same name given as the artifactId. Change into that directory.
cd my-app
What is the POM?
POM stands for “Project Object Model”. It is an XML representation of a Maven project held in a file named pom.xml. The POM contains information about the project and various configuration detail used by Maven to build the project(s).
pom.xml file contains the goals that can be executed, the goals or plugins are now configured in the pom.xml. When executing a task or goal, Maven looks for the POM in the current directory. It reads the POM, gets the needed configuration information, then executes the goal. Some of the configuration that can be specified in the POM are the project dependencies, the plugins or goals that can be executed, the build profiles, and so on. Other information such as the project version, description, developers, mailing lists and such can also be specified.
In short the pom.xml will have all information to build your project.
For example you want to build a project and you have only the pom.xml sent to you via mail. If there are enough entries in the pom.xml then that is all you need! You can import it to Eclipse, Maven will download your source code from CVS, download various dependency jars (like Spring, Apache Commons), run your test cases, build the jar/war, deploy to your jboss/app server, generate a report of your code quality (using Sonar, maybe). Each task you want to do will be mentioned as a goal.
Check-out the code from SVN repository using pom.xml
<project xmlns=”http://maven.apache.org/POM/4.0.0″
xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”
xsi:schemaLocation=”http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd”>
<modelVersion>4.0.0</modelVersion>
<groupId>de.xxx.internet</groupId>
<artifactId>my-app</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>Maven Quick Start Archetype</name>
<url>http://www.mySite.de</url>
<scm>
<connection>scm:svn:http://svn-repo-adress:8080/repo/myDirectory</connection>
<developerConnection>http://svn-repo-adress:8080/repo/myDirectory</developerConnection>
<tag>HEAD</tag>
<url>http://svn-repo-adress:8080/repo/myDirectory</url>
</scm>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-scm-plugin</artifactId>
<version>1.6</version>
<configuration>
<goals>checkout</goals>
<checkoutDirectory>target/checkout</checkoutDirectory>
<username>username</username>
<password>userpassword</password>
</configuration>
<executions>
<execution>
<id>check-out-project1</id>
<phase>generate-sources</phase>
<goals>
<goal>checkout</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
After I executed “mvn scm:checkout” on the cmd console it did work.
I think the important point was to add the scm tag first, before I had executed the build tag.
Configuring TestNG
To get started with TestNG, include the following dependency in your project (replacing the version with the one you wish to use):
<dependencies>
[…]
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.8.8</version>
<scope>test</scope>
</dependency>
[…]
</dependencies>
If you are using an older version of TestNG (<= 5.11), the dependency would instead look like this:
This is the only step that is required to get started – you can now create tests in your test source directory (e.g., src/test/java). As long as they are named in accordance with the defaults such as *Test.java they will be run by Surefire as TestNG tests.
If you’d like to use a different naming scheme, you can change the includes parameter, as discussed in the Inclusions and Exclusions of Tests example.
Inclusions and Exclusions of Tests
Inclusions
By default, the Surefire Plugin will automatically include all test classes with the following wildcard patterns:
- “**/Test*.java”- includes all of its subdirectories and all Java filenames that start with “Test”.
- “**/*Test.java”- includes all of its subdirectories and all Java filenames that end with “Test”.
- “**/*TestCase.java”- includes all of its subdirectories and all Java filenames that end with “TestCase”.
If the test classes do not follow any of these naming conventions, then configure Surefire Plugin and specify the tests you want to include.
<project>
[…]
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.18.1</version>
<configuration>
<includes>
<include>Sample.java</include>
</includes>
</configuration>
</plugin>
</plugins>
</build>
[…]
</project>
Exclusions
There are certain times when some tests are causing the build to fail. Excluding them is one of the best workarounds to continue the build. Exclusions can be done by configuring the excludes property of the plugin.
<project>
[…]
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.18.1</version>
<configuration>
<excludes>
<exclude>**/TestCircle.java</exclude>
<exclude>**/TestSquare.java</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
[…]
</project>
Regular Expression Support
An include/exclude pattern can be an ant-style path expression, but regular expressions are also supported through this syntax:
<project>
[…]
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.18.1</version>
<configuration>
<includes>
<include>%regex[.*[Cat|Dog].*Test.*]</include>
</includes>
</configuration>
</plugin>
</plugins>
</build>
[…]
</project>
Note the syntax %regex[expr], where expr is the actual expression and the rest is just wrapping. Also note that regex matches are done over *.class files and not *.java files.
Using Suite XML Files
Another alternative is to use TestNG suite XML files. This allows flexible configuration of the tests to be run. These files are created in the normal way, and then added to the Surefire Plugin configuration:
<plugins>
[…]
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.18.1</version>
<configuration>
<suiteXmlFiles>
<suiteXmlFile>testng.xml</suiteXmlFile>
</suiteXmlFiles>
</configuration>
</plugin>
[…]
</plugins>
This configuration will override the includes and excludes patterns and run all tests in the suite files.
Specifying Test Parameters
Your TestNG test can accept parameters with the @Parameters annotation. You can also pass parameters from Maven into your TestNG test, by specifying them as system properties, like this:
<plugins>
[…]
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.18.1</version>
<configuration>
<systemPropertyVariables>
<propertyName>firefox</propertyName>
</systemPropertyVariables>
</configuration>
</plugin>
[…]
</plugins>
For more information about setting system properties in Surefire tests, see System Properties.
Using Groups
TestNG allows you to group your tests. You can then execute one or more specific groups. To do this with Surefire, use the groups parameter, for example:
<plugins>
[…]
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.18.1</version>
<configuration>
<groups>functest,perftest</groups>
</configuration>
</plugin>
[…]
</plugins>
Likewise, the excludedGroups parameter can be used to run all but a certain set of groups.
Running Tests in Parallel
TestNG allows you to run your tests in parallel, including JUnit tests. To do this, you must set the parallel parameter, and may change the threadCountparameter if the default of 5 is not sufficient. For example:
</plugins>
[…]
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.18.1</version>
<configuration>
<parallel>methods</parallel>
<threadCount>10</threadCount>
</configuration>
</plugin>
[…]
</plugins>
This is particularly useful for slow tests that can have high concurrency, or to quickly and roughly assess the independence and thread safety of your tests and code.
See also Fork Options and Parallel Test Execution.
Using Custom Listeners and Reporters
TestNG provides support for attaching custom listeners, reporters, annotation transformers and method interceptors to your tests. By default, TestNG attaches a few basic listeners to generate HTML and XML reports.
You can configure multiple custom listeners like this:
</plugins>
[…]
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.18.1</version>
<configuration>
<properties>
<property>
<name>usedefaultlisteners</name>
<value>false</value> <!– disabling default listeners is optional –>
</property>
<property>
<name>listener</name>
<value>com.mycompany.MyResultListener,com.mycompany.MyAnnotationTransformer,com.mycompany.MyMethodInterceptor</value>
</property>
<property>
<name>reporter</name>
<value>listenReport.Reporter</value>
</property>
</properties>
</configuration>
</plugin>
[…]
</plugins>
For more information on TestNG, see the TestNG web site.
Maven Surefire Plugin
The Surefire Plugin is used during the test phase of the build lifecycle to execute the unit tests of an application. It generates reports in two different file formats:
- Plain text files (*.txt)
- XML files (*.xml)
By default, these files are generated at ${basedir}/target/surefire-reports.
For an HTML format of the report, please see the Maven Surefire Report Plugin.
Running a Single Test
During development, you may run a single test class repeatedly. To run this through Maven, set the test property to a specific test case.
mvn -Dtest=TestCircle test
The value for the test parameter is the name of the test class (without the extension; we’ll strip off the extension if you accidentally provide one).
You may also use patterns to run a number of tests:
mvn -Dtest=TestCi*le test
And you may use multiple names/patterns, separated by commas:
mvn -Dtest=TestSquare,TestCi*le test
Running a Set of Methods in a Single Test Class
As of Surefire 2.7.3, you can also run only a subset of the tests in a test class.
NOTE : This feature is supported only for Junit 4.x and TestNG.
You must use the following syntax:
mvn -Dtest=TestCircle#mytest test
You can use patterns too
mvn -Dtest=TestCircle#test* test
As of Surefire 2.12.1, you can select multiple methods (JUnit 4.x only at this time; patches welcome!):
mvn -Dtest=TestCircle#testOne+testTwo test
#maven, #surefire-plugin, #test-classes
WebElement element = driver.findElement(By.id("id_of_element"));
((JavascriptExecutor) driver).executeScript("arguments[0].scrollIntoView(true);", element);
Thread.sleep(500);
//do anything you want with the element
ScrollIntoView Method :- Scrolls the specified element into the visible area of the document.
By default, the top side of the element will be aligned to the top side of the closest scrollable ancestor element (in the DOM hierarchy), but you can change the alignment type with the first parameter of the scrollIntoView method. Sometimes exact alignment is not possible, in that case the scrollIntoView method scrolls the object to the position nearest to the required. After that, it repeats this procedure to the scrollable ancestor element recursively.
- The position of an element’s scrollbars can be set or retrieved with the scrollLeft and scrollTop properties.
- To get the maximum scrolling positions, use the scrollWidth, scrollHeight and clientWidth, clientHeight properties.
- If you want to set the position of the document’s scrollbars, use the scrollTo or scrollBy method.
Syntax:
object.scrollIntoView([alignToTop]);
Parameters:
| alignToTop | Optional. Boolean that indicates the type of the align.
One of the following values:
|
Return value:
<head> <script type="text/javascript"> function ScrollRed (alignToTop) { var redText = document.getElementById ("redText"); redText.scrollIntoView (alignToTop); } </script> </head> <body> <div style="width:300px; height:200px; overflow:auto; background-color:#e0d0b0;"> <div style="height:200px;"></div> <span id="redText" style="color:red">Red text for scroll test.</span> <div style="height:200px;"></div> </div> <br /><br /> <button onclick="ScrollRed (true);">Scroll the red text into the top of visible area!</button> <br /> <button onclick="ScrollRed (false);">Scroll the red text into the bottom of visible area!</button> </body>
The arguments object (arguments[0] in the above code) When control enters the execution context of a function an arguments object is created. Thearguments object has an array-like structure with an indexed property for each passed argument and alength property equal to the total number of parameters supplied by the caller. Thus the length of thearguments object can be greater than, less than or equal to the number of formal parameters in the function definition (which we can get by querying the function’s length property):
|
Use testng-xslt.xsl file For generating testng-xslt report for your project do the following:
- Download the from testng-xslt or alternatively from here
- Unzip and copy the testng-results.xsl from the testng-xslt folder(testng-xslt- 1.1\src\main\resources) to your own project folder.
- Now copy the saxon library from (testng-xslt-1.1\lib\saxon-8.7.jar)to your project lib folder.
Now use following build.xml (I have tried to update as per you but if some change required, do by yourself)
<project name=”ProjectName” basedir=”.”>
<property name=”src.dir” value=”${basedir}/src”/>
<property name=”lib.dir” value=”${basedir}/lib”/>
<property name=”report.dir” value=”${basedir}/test-output”/>
<property name=”reportXslt.dir” value=”${basedir}/testng-xslt”/>
<property name=”classes.dir” value=”${basedir}/bin”/><path id=”ProjectName_WebDriver.classpath”>
<pathelement location=”bin”/>
<pathelement location=”lib/selenium-2.37.0/libs/apache-mime4j-0.6.jar”/>
<pathelement location=”lib/selenium-2.37.0/libs/bsh-1.3.0.jar”/>
<pathelement location=”lib/selenium-2.37.0/libs/cglib-nodep-2.1_3.jar”/>
<pathelement location=”lib/selenium-2.37.0/libs/commons-codec-1.6.jar”/>
<pathelement location=”lib/selenium-2.37.0/libs/commons-collections-3.2.1.jar”/>
<pathelement location=”lib/selenium-2.37.0/libs/commons-exec-1.1.jar”/>
<pathelement location=”lib/selenium-2.37.0/libs/commons-io-2.2.jar”/>
<pathelement location=”lib/selenium-2.37.0/libs/commons-jxpath-1.3.jar”/>
<pathelement location=”lib/selenium-2.37.0/libs/commons-lang3-3.1.jar”/>
<pathelement location=”lib/selenium-2.37.0/libs/commons-logging-1.1.1.jar”/>
<pathelement location=”lib/selenium-2.37.0/libs/cssparser-0.9.11.jar”/>
<pathelement location=”lib/selenium-2.37.0/libs/guava-15.0.jar”/>
<pathelement location=”lib/selenium-2.37.0/libs/hamcrest-core-1.3.jar”/>
<pathelement location=”lib/selenium-2.37.0/libs/hamcrest-library-1.3.jar”/>
<pathelement location=”lib/selenium-2.37.0/libs/htmlunit-2.13.jar”/>
<pathelement location=”lib/selenium-2.37.0/libs/htmlunit-core-js-2.13.jar”/>
<pathelement location=”lib/selenium-2.37.0/libs/httpclient-4.3.1.jar”/>
<pathelement location=”lib/selenium-2.37.0/libs/httpcore-4.3.jar”/>
<pathelement location=”lib/selenium-2.37.0/libs/httpmime-4.3.1.jar”/>
<pathelement location=”lib/selenium-2.37.0/libs/ini4j-0.5.2.jar”/>
<pathelement location=”lib/selenium-2.37.0/libs/jcommander-1.29.jar”/>
<pathelement location=”lib/selenium-2.37.0/libs/jetty-websocket-8.1.8.jar”/>
<pathelement location=”lib/selenium-2.37.0/libs/jna-3.4.0.jar”/>
<pathelement location=”lib/selenium-2.37.0/libs/jna-platform-3.4.0.jar”/>
<pathelement location=”lib/selenium-2.37.0/libs/json-20080701.jar”/>
<pathelement location=”lib/selenium-2.37.0/libs/junit-dep-4.11.jar”/>
<pathelement location=”lib/selenium-2.37.0/libs/nekohtml-1.9.19.jar”/>
<pathelement location=”lib/selenium-2.37.0/libs/netty-3.5.7.Final.jar”/>
<pathelement location=”lib/selenium-2.37.0/libs/operadriver-1.5.jar”/>
<pathelement location=”lib/selenium-2.37.0/libs/phantomjsdriver-1.0.4.jar”/>
<pathelement location=”lib/selenium-2.37.0/libs/protobuf-java-2.4.1.jar”/>
<pathelement location=”lib/selenium-2.37.0/libs/sac-1.3.jar”/>
<pathelement location=”lib/selenium-2.37.0/libs/serializer-2.7.1.jar”/>
<pathelement location=”lib/selenium-2.37.0/libs/testng-6.8.5.jar”/>
<pathelement location=”lib/selenium-2.37.0/libs/xalan-2.7.1.jar”/>
<pathelement location=”lib/selenium-2.37.0/libs/xercesImpl-2.10.0.jar”/>
<pathelement location=”lib/selenium-2.37.0/libs/xml-apis-1.4.01.jar”/>
<pathelement location=”lib/selenium-2.37.0/selenium-java-2.37.0-srcs.jar”/>
<pathelement location=”lib/selenium-2.37.0/selenium-java-2.37.0.jar”/>
<pathelement location=”lib/log4j-1.2.17.jar”/>
<pathelement location=”lib/poi-3.9-20121203.jar”/>
<pathelement location=”lib/commons-codec-1.5.jar”/>
<pathelement location=”lib/commons-logging-1.1.jar”/>
<pathelement location=”lib/dom4j-1.6.1.jar”/>
<pathelement location=”lib/poi-excelant-3.9-20121203.jar”/>
<pathelement location=”lib/poi-ooxml-3.9-20121203.jar”/>
<pathelement location=”lib/poi-ooxml-schemas-3.9-20121203.jar”/>
<pathelement location=”lib/poi-scratchpad-3.9-20121203.jar”/>
<pathelement location=”lib/stax-api-1.0.1.jar”/>
<pathelement location=”lib/xmlbeans-2.3.0.jar”/>
<pathelement location=”lib/saxon-8.7.jar”/>
<pathelement location=”lib/SaxonLiaison.jar”/>
</path><target name=”run”>
<antcall target=”clean” />
<antcall target=”compile” />
<antcall target=”runTests” />
<antcall target=”generateXsltReport” />
</target><!– Delete old data and create new directories –>
<target name=”clean”>
<echo>Initlizing…</echo><delete dir=”${classes.dir}” />
<mkdir dir=”${classes.dir}” /><delete dir=”${report.dir}” />
<mkdir dir=”${report.dir}” /><delete dir=”${reportXslt.dir}” />
<mkdir dir=”${reportXslt.dir}” /></target>
<!– Compiles the java files –>
<target name=”compile”>
<echo>Compiling…</echo><javac debug=”true” srcdir=”${src.dir}” destdir=”${classes.dir}” classpathref=”ProjectName.classpath” includeantruntime=”false” includes=”**/**” />
<copy todir=”${classes.dir}”>
<fileset dir=”${src.dir}” excludes=”**/*.java” />
</copy></target>
<!– Runs the file and generate report –>
<target name=”runTests” description=”Running tests”>
<echo>Running Tests…</echo><taskdef name=”testng” classname=”org.testng.TestNGAntTask” classpathref=”ProjectName.classpath” />
<testng outputdir=”${report.dir}” classpathref=”ProjectName.classpath” workingdir=”${basedir}”>
<xmlfileset dir=”${basedir}” includes=”WebCSR.xml” />
</testng></target>
<!– Target to make XSLT reports –>
<target name=”generateXsltReport”><xslt in=”${report.dir}/testng-results.xml” style=”${basedir}/testng-results.xsl” out=”${reportXslt.dir}/index.html” processor=”SaxonLiaison” classpathref=”ProjectName.classpath”>
<param name=”testNgXslt.outputDir” expression=”${reportXslt.dir}/” />
<param name=”testNgXslt.showRuntimeTotals” expression=”true” />
</xslt></target>
</project>
Save the all the element locators in the Object Repository Property file in the below format:
For Ex: Link web element the naming convention should be as below:-
LINK_MODULENAME_PAGENAME_XPATH –> If XPATH
LINK_MODULENAME_PAGENAME_ID –> if ID
LINK_MODULENAME_PAGENAME_CSS –> if CSS
LINK_MODULENAME_PAGENAME_NAME –> if NAME
Method to get the web element
public static WebElement getWebElement(String locator){
String[] tokens = locator.split("_");
String locatorType = tokens[tokens.length-1];
String strlocator = OR.getProperty(locator).trim();
WebElement webElement = null;
try{
if(locatorType.equalsIgnoreCase("XPATH")){
webElement = driver.findElement(By.xpath(strlocator));
}else if(locatorType.equalsIgnoreCase("ID")){
webElement = driver.findElement(By.id(strlocator));
}else if(locatorType.equalsIgnoreCase("NAME")){
webElement = driver.findElement(By.name(strlocator));
}else if(locatorType.equalsIgnoreCase("CSS")){
webElement = driver.findElement(By.cssSelector(strlocator));
}else if(locatorType.equalsIgnoreCase("LINKTEXT")){
webElement = driver.findElement(By.linkText(strlocator));
}
}catch(NoSuchElementException e){
e.printStackTrace();
log.error(strlocator + " Element not found");
Assert.fail(strlocator + " Element not found");
}
return webElement;
}
Method to handle button web element
public static void buttonClick(String locator, String name){
try{
if(getWebElement(locator).isEnabled()){
getWebElement(locator).click();
log.info("Clicked on "+"'"+name+"'"+ " button");
}else{
log.error("'"+name+"'" + " : Button is not enabled");
Assert.fail("'"+name+"'" + " : Button is not enabled");
}
}catch(NoSuchElementException e){
e.printStackTrace();
log.error(locator + " : Button not found");
Assert.fail(locator + " : Button not found");
}catch(ElementNotVisibleException e){
e.printStackTrace();
log.error(locator + " : Button not visible");
Assert.fail(locator + " : Button not visible");
}
}
To open the work book
public static Workbook openWorkbook() {
String workBookPath = TestBase.ReportFilePath;
FileInputStream fis = null;
Workbook workbook = null;
try {
fis = new FileInputStream(workBookPath);
workbook = WorkbookFactory.create(fis);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (InvalidFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return workbook;
}
public static void UpdateTestStatus(String pageName, String actualPageTitle) {
String reportFilePath = TestBase.ReportFilePath;
String sheetName = config.getProperty("autoPageTitleVerification");
String colName = config.getProperty("colName");
String expPageTitleCol = config.getProperty("expPageTitleCol");
String osBrowserName = config.getProperty("currentOSName").trim() + "-" + config.getProperty("browserName").trim();
Workbook workbook = null;
int colCount = 0;
int rowNum = 0;
int colPgNmNum = 0;
int expPgTitleColNum = 0;
int osBrowserCol = 0;
// Open the workbook
workbook = TestUtil.openWorkbook();
Sheet sheet = workbook.getSheet(sheetName);
if(sheet.getRow(0)!=null){
colCount = sheet.getRow(0).getLastCellNum();
}
// Loop to collect the "PageName" column number
for (int i = 0; i <= colCount-1; i++) {
if(sheet.getRow(0).getCell(i).getStringCellValue().equalsIgnoreCase(colName)){
colPgNmNum = i;
break;
}
}
// Loop to collect the "Expected_Page_Title" column number
for (int i = 0; i <= colCount-1; i++) {
if(sheet.getRow(0).getCell(i).getStringCellValue().equalsIgnoreCase(expPageTitleCol)){
expPgTitleColNum = i;
break;
}
}
// Loop to collect the current OS-Browser combination column number
for (int j = 0; j <= colCount-1; j++) {
if(sheet.getRow(0).getCell(j).getStringCellValue().trim().equalsIgnoreCase(osBrowserName.trim())){
osBrowserCol = j;
break;
}
}
// Collect total row count.
rowNum = sheet.getLastRowNum();
// Compaire the page name and Update the summary sheet with the staus as PASS.
if(osBrowserCol != 0){
for (int i = 0; i <= rowNum; i++) {
if (pageName.trim().equals(sheet.getRow(i).getCell(colPgNmNum).getStringCellValue().trim())) {
if(actualPageTitle.trim().equals(sheet.getRow(i).getCell(expPgTitleColNum).getStringCellValue().trim())){
sheet.getRow(i).createCell(osBrowserCol).setCellValue("Pass");
try {
FileOutputStream fos = new FileOutputStream(reportFilePath);
workbook.write(fos);
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else {
sheet.getRow(i).createCell(osBrowserCol).setCellValue("Fail");
try {
FileOutputStream fos = new FileOutputStream(reportFilePath);
workbook.write(fos);
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Assert.fail("Expected Page title : "+sheet.getRow(i).getCell(expPgTitleColNum).getStringCellValue().trim()+" But it is displaying as "+actualPageTitle.trim());
log.error("Actual Page title : "+actualPageTitle.trim()+" But it is displaying as "+sheet.getRow(i).getCell(expPgTitleColNum).getStringCellValue().trim());
}
}
}
} else{
}
// Close the workbook
/*try {
FileOutputStream fos = new FileOutputStream(reportFilePath);
workbook.write(fos);
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}*/
}
boolean isDirCreated = false;//to create Screenshot directory just once
//Create Screenshot Directory.
public static void createDir(String ScreenshotDirAddress){
if(!isDirCreated){
File file= new File(ScreenshotDirAddress);
if (!file.exists())
file.mkdirs();
isDirCreated=true;
}
}
//hyperlink screenshot
public static void hyperlinkScreenshot(XSSFCell cell, String FileAddress){
XSSFWorkbook wb=cell.getRow().getSheet().getWorkbook();
CreationHelper createHelper = wb.getCreationHelper();
CellStyle hlink_style = wb.createCellStyle();
Font hlink_font = wb.createFont();
hlink_font.setUnderline(Font.U_SINGLE);
hlink_font.setColor(IndexedColors.BLUE.getIndex());
hlink_style.setFont(hlink_font);
Hyperlink hp = createHelper.createHyperlink(Hyperlink.LINK_FILE);
FileAddress=FileAddress.replace("\\", "/");
hp.setAddress(FileAddress);
cell.setHyperlink(hp);
cell.setCellStyle(hlink_style);
}
//take screenshot
public static void takeScreenShot(WebDriver driver, String screenshotName, XSSFCell cell){
createDir();
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
try {
String FullAddress=System.getProperty("user.dir")+"/"+ScreenshotDirAddress+"/"+screenshotName+".png";
FileUtils.copyFile(scrFile, new File(FullAddress));
hyperlinkScreenshot(cell, FullAddress);
} catch (IOException e) {
e.printStackTrace();
}
}
Selendroid is a test automation framework which drives off the UI of Android native and hybrid applications (apps) and the mobile web. Tests are written using the Selenium 2 client API – that’s it!
1) Selendroid can be downloaded from the Selendroid website and save this jar file in your project folder.
2) Before you can start setting up Selendroid and writing tests, you need to download and install the latest Android SDK first. Clear instructions on how to do this can be found here. Make sure you also create at least one Android virtual device (AVD) and test whether it can be run properly.
3) If you want to create AVD from Eclipse. click here
4) Add the Selendroid jar file downloaded in step(1) to Projects’s build path.
Creating a SelendroidDriver using the below code:-
DesiredCapabilities caps = SelendroidCapabilities.android();
WebDriver driver = new SelendroidDriver(caps);
5) Starting the Selendroid Server. Go to the path where you have downloaded the Selendroid jar file and type the below command.
java -jar selendroid-standalone-x.x.x-with-dependencies.jar
6) It will start selendroid-server on port number 4444 by default.
Need to Update…..next steps….coming soon!!
To handle multiple windows i.e., more than 2 windows in Selenium WebDriver.
public static String switchToPopupWindow(WebDriver driver, By by) {
Set<String> handles = driver.getWindowHandles();
int size = handles.size();
WebElement we = driver.findElement(by);
we.click();
Set<String> handles2 = null;
int size2;
do {
handles2 = driver.getWindowHandles();
size2 = handles2.size();
Thread.sleep(250);
} while(size2 – size != 1);
handles2.removeAll(handles);
String newWindowHandle = (String)handles2.toArray()[0];
return newWindowHandle;
}
The logic here is:
– Get a list of window handles
– Click the element which opens the new window
– Get a second list of window handles
– Subtract the first set from the second set
Whatever remains in the second set will be the handle for the new window.


Recent Comments