Showing posts with label Selenium. Show all posts
Showing posts with label Selenium. Show all posts

Tuesday, November 29, 2016

Selenium :Firefox Driver (Gecko Driver)

Firefox Driver (Gecko Driver)



 Gecko Driver :https://github.com/mozilla/geckodriver/releases

 public static void main(String[] args) {
             System.setProperty("webdriver.gecko.driver","path\\geckodriver.exe");
            WebDriver driver = new FirefoxDriver();
            driver.get("https://www.google.com");
}

Friday, March 18, 2016

Selenium : Page Object Model (By) VS Page Factory (@FindBy)


 Page Object Model (By) VS Page Factory (@FindBy)


1) Page Object Model

- Page Object Model - Initialize all object locators separately using "By"

 Code Here :
class starttest{
     @Test
      public void LoginTest() {    
            By usernameField = By.xpath("//*[text()=login_login_username]")
            By passwordField = By.name("//*[text()=login_login_password]")
            By loginButton = By.xpath("//*[text()=login_submit]");
          
            WebDriver driver=new FireFoxDriver();
            driver.get("http://some-login-page");
          
            driver.findElement(usernameField).sendKeys("my name");
            driver.findElement(passwordField).sendKeys("my password");
            driver.findElement(loginButton).click();
      }
  }

 2) Page Factory (@FindBy and PageFactory.initElements(driver, .class))

 1) @FindBy can accept tagName, partialLinkText, name, linkText, id, css, className, xpath as attributes.

2)  @FindBy(xpath="//*[text()=login_login_username]")
    private WebElement usernameField;
 

Is  Same as 

WebElement usernameField=By.xpath("//*[text()=login_login_username]")

3)
  @FindBy(xpath="//*[@id='']")    is same as     //@FindBy(how = How.xpath, using ="//*[@id='']")
 @FindBy(name="username")        is same as     //@FindBy(how = How.NAME, using = "username")
 @FindBy(className="radio")       is same as       //@FindBy(how = How.CLASSNAME, using = "radio")

 Code Here :


class starttest{

     @Test
      public void LoginTest() {   
        WebDriver driver=new FireFoxDriver();
        driver.get("http://some-login-page");
       
        LoginPage loginPage=PageFactory.initElements(driver, LoginPage.class); //Initialize Login Page     
        loginPage.login("student1","Testing1");
      }
  }


 public class LoginPage {

    @FindBy(xpath="//*[text()=login_login_username]")
    private WebElement usernameField;   \\
By usernameField = By.xpath("//*[text()=login_login_username]")   
   

 @FindBy(xpath="//*[text()=login_login_password]")
    private WebElement passwordField;   
   
    @FindBy(xpath="//*[text()=login_submit]")
    private WebElement loginButton;        

   
    public void login(String usernametext,String passwordtext)    {
        usernameField.sendKeys(usernametext);
        passwordField.sendKeys(passwordtext);
        loginButton.click();
    }   
}

Thursday, March 10, 2016

TestNg: @BeforeTest

@BeforeTest



BeforeTest execution = No of times you have defines <test name>.Below example you have used <test name> twice therefore Beforetest excutes twice













import org.testng.annotations.*;

public class testng_annotations {
   
    @BeforeSuite
    public void Beforesuite(){
        System.out.println("beforesuite");       
    }
   
    @BeforeTest
    public void Beforetest(){
        System.out.println("beforetest");
    }
   
    @DataProvider
    public Object[][] dataprovider(){
        Object[][] obj=new Object[2][2];
        obj[0][0]=1;
        obj[1][0]=2;
        obj[0][1]=3;
        obj[1][1]=4;
        return obj;
    }
   
    @Test(dataProvider="dataprovider")
    public void test(int i,int y) {   
            System.out.println("Data " + i+y);// execute 2nd       
    }
}

 

 Result

 

Sunday, March 6, 2016

Java : Mockito

Java : Mockito

Mockito is used for creating mock objects ie., creating Virtual methods for a class or interface before development happens and validating the result .

Below is a simple example of an interface Bulb Switch without implementation . We know that when press_on is pressed the bulb will turn on and vis versa .Below is the Junit test implementation

Example :

-----------------------------------------------------------------------
public interface Bulb_Switch {

    public String press_on();   
    public String press_off();
}

-----------------------------------------------------------------------
 import static org.mockito.Mockito.*;
import org.junit.*;

public class runner {
Bulb_Switch switch_on_off;

    @Before
    public void runner() {
        switch_on_off= mock(Bulb_Switch.class);  //'switch_on_off'= object , "Bulb_Switch"=Interface
        when(switch_on_off.press_on()).thenReturn("on");  //Designing return values for unimplemented methods
        when(switch_on_off.press_off()).thenReturn("on");  //Designing  return values
for unimplemented methods
    }
   
    @Test  // Positive test
    public void test1(){
        Assert.assertEquals("on", switch_on_off.press_on());  // Validating if the expected matches with return values
    }
   
    @Test //Negative test
    public void test2(){
        Assert.assertEquals("off", switch_on_off.press_off());// Validating if the expected matches with return values
    }
}

-----------------------------------------------------------------------  

Run as Junit test






Ref :
http://mvnrepository.com/artifact/org.mockito/mockito-all/1.10.19      -- (Download jar)
http://luckyacademy.blogspot.in/2014/09/mockito-tutorial-part1.html
https://www.youtube.com/watch?v=ShO_Z64sGwI
https://www.youtube.com/watch?v=79eXGJ2rKZs
https://gojko.net/2009/10/23/mockito-in-six-easy-examples/

Saturday, March 5, 2016

Gradle : Complete build file

Gradle : Complete build file


https://github.com/codeborne/selenide/blob/master/build.gradle



buildscript {
  repositories { jcenter() }
  dependencies {
    classpath 'info.solidsoft.gradle.pitest:gradle-pitest-plugin:1.1.9'
    classpath 'de.undercouch:gradle-download-task:2.1.0'
  }
}

apply plugin: 'java'
apply plugin: 'maven'
apply plugin: "jacoco"
apply plugin: 'findbugs'
apply plugin: 'checkstyle'
apply plugin: 'de.undercouch.download'

group='com.codeborne'
archivesBaseName = 'selenide'
version='3.4'

[compileJava, compileTestJava]*.options.collect {options -> options.encoding = 'UTF-8'}
[compileJava, compileTestJava]*.options.collect {options -> options.debug = true}
compileJava.options.debugOptions.debugLevel = "source,lines,vars"
sourceCompatibility = 1.7
targetCompatibility = 1.7

defaultTasks 'check', 'test', 'install'

repositories {
  mavenCentral()
}

configurations {
  provided
  compile.extendsFrom provided
}

dependencies {
  compile('org.seleniumhq.selenium:selenium-java:2.52.0') {
    exclude group: 'org.seleniumhq.selenium', module: 'selenium-htmlunit-driver'
    exclude group: 'org.seleniumhq.selenium', module: 'selenium-android-driver'
    exclude group: 'org.seleniumhq.selenium', module: 'selenium-iphone-driver'
    exclude group: 'org.seleniumhq.selenium', module: 'selenium-safari-driver'
    exclude group: 'org.webbitserver', module: 'webbit'
    exclude group: 'commons-codec', module: 'commons-codec'
    exclude group: 'cglib', module: 'cglib-nodep'
  }
  runtime('com.codeborne:phantomjsdriver:1.2.1') {
    exclude group: 'org.seleniumhq.selenium', module: 'selenium-java' 
    exclude group: 'org.seleniumhq.selenium', module: 'selenium-remote-driver' 
  }
  compile 'com.google.guava:guava:19.0'
  runtime 'commons-codec:commons-codec:1.10'
  provided group: 'org.seleniumhq.selenium', name: 'selenium-htmlunit-driver', version: '2.52.0', transitive: false
  provided group: 'net.sourceforge.htmlunit', name: 'htmlunit', version: '2.20', transitive: false
  testRuntime group: 'net.sourceforge.htmlunit', name: 'htmlunit', version: '2.20'
  provided 'junit:junit:4.12'
  provided 'org.testng:testng:6.9.10'
 
  // For BrowserMob Proxy:
  testCompile group: 'net.lightbody.bmp', name: 'browsermob-proxy', version: '2.0.0', transitive: false
  testRuntime group: 'org.slf4j', name: 'slf4j-jdk14', version: '1.7.18'
  testRuntime group: 'net.sf.uadetector', name: 'uadetector-resources', version: '2014.10'
  testRuntime 'com.fasterxml.jackson.core:jackson-databind:2.7.2'

  testCompile 'org.mockito:mockito-core:1.10.19'
  testCompile 'org.eclipse.jetty:jetty-server:9.2.15.v20160210'
  testCompile 'org.eclipse.jetty:jetty-servlet:9.2.15.v20160210'
  testCompile 'commons-fileupload:commons-fileupload:1.3.1'
}

task libs(type: Sync) {
  from configurations.compile
  from configurations.runtime
  from configurations.testCompile
  from configurations.testRuntime
  into "$buildDir/lib"
}

compileJava.dependsOn libs

findbugs {
  toolVersion = "3.0.1"
  sourceSets = [sourceSets.main]
  effort = "max"
  reportsDir = file("$project.buildDir/reports/findbugs")
  excludeFilter = file("$rootProject.projectDir/config/findbugs/excludeFilter.xml")
}

tasks.withType(FindBugs) {
  reports {
    xml.enabled = false
    html.enabled = true
  }
}

task checkstyleHtmlMain << {
  ant.xslt(in: checkstyleMain.reports.xml.destination,
    style: file('config/checkstyle/checkstyle-noframes-sorted.xsl'),
    out: new File(checkstyleMain.reports.xml.destination.parent, 'main.html'))
}

task checkstyleHtmlTest << {
  ant.xslt(in: checkstyleTest.reports.xml.destination,
    style: file('config/checkstyle/checkstyle-noframes-sorted.xsl'),
    out: new File(checkstyleTest.reports.xml.destination.parent, 'test.html'))
}

checkstyleMain.finalizedBy checkstyleHtmlMain
checkstyleTest.finalizedBy checkstyleHtmlTest

jacoco {
  toolVersion = "0.7.6.201602180812"
}

jacocoTestReport {
  reports {
    xml.enabled false
    csv.enabled false
    html.destination "${buildDir}/reports/jacocoHtml"
  }
}

apply plugin: 'info.solidsoft.pitest'

pitest {
  targetClasses = ["com.codeborne.selenide*"]
  timestampedReports = false
  threads = 4
  outputFormats = ['XML', 'HTML']
  enableDefaultIncrementalAnalysis = true
}

test {
  include 'com/codeborne/selenide/**/*'
}

import de.undercouch.gradle.tasks.download.Download

task downloadIEDriverZip(type: Download) {
  src 'http://selenium-release.storage.googleapis.com/2.52/IEDriverServer_Win32_2.52.0.zip'
  dest new File(buildDir, 'IEDriverServer.zip')
  quiet false
  overwrite true
  onlyIfNewer true
  compress false
  println "Download IE driver: " + src
}

task downloadAndUnzipIEDriver(dependsOn: downloadIEDriverZip, type: Copy) {
  println "Unzip IE driver: " + downloadIEDriverZip.dest
  from zipTree(downloadIEDriverZip.dest)
  into buildDir
}

task ie(type: Test, dependsOn: downloadAndUnzipIEDriver) {
  println 'Use IE driver: ' + buildDir + '/IEDriverServer.exe'
  systemProperties['selenide.browser'] = 'ie'
  systemProperties['webdriver.ie.driver'] = new File(buildDir, 'IEDriverServer.exe')
  systemProperties['selenide.timeout'] = '8000'
  include 'integration/**/*'
  exclude '**/AlertText.*'
  exclude '**/ConfirmTest.*'
  exclude 'com/codeborne/selenide/**/*'
}

import org.gradle.internal.os.OperatingSystem;

task downloadChromeDriverZip(type: Download) {
  if (OperatingSystem.current().isMacOsX()) {
    src 'http://chromedriver.storage.googleapis.com/2.21/chromedriver_mac32.zip'
  }
  else if (OperatingSystem.current().isLinux()) {
    src 'http://chromedriver.storage.googleapis.com/2.21/chromedriver_linux64.zip'
  }
  else {
    src 'http://chromedriver.storage.googleapis.com/2.21/chromedriver_win32.zip'
  }
  dest new File(buildDir, 'chromedriver.zip')
  quiet false
  overwrite true
  onlyIfNewer true
  compress false
  println "Download Chrome driver: " + src + " to " + dest
}

task downloadAndUnzipChromeDriver(dependsOn: downloadChromeDriverZip, type: Copy) {
  println "Unzip Chrome driver: " + downloadChromeDriverZip.dest
  from zipTree(downloadChromeDriverZip.dest)
  into buildDir
}

task chrome(type: Test, dependsOn: downloadAndUnzipChromeDriver) {
  println 'Use Chrome driver: ' + buildDir + '/chromedriver'
  systemProperties['selenide.browser'] = 'chrome'
  systemProperties['webdriver.chrome.driver'] = new File(buildDir, 'chromedriver')
  include 'integration/**/*'
  exclude 'com/codeborne/selenide/**/*'
}

task htmlunit(type: Test) {
  systemProperties['selenide.browser'] = 'htmlunit'
  include 'integration/**/*'
  exclude 'com/codeborne/selenide/**/*'
}

task phantomjs(type: Test) {
  systemProperties['selenide.browser'] = 'phantomjs'
  include 'integration/**/*'
  exclude 'com/codeborne/selenide/**/*'
}

task firefox(type: Test) {
  systemProperties['selenide.browser'] = 'firefox'
  include 'integration/**/*'
  exclude 'com/codeborne/selenide/**/*'
}

tasks.withType(Test).all { testTask ->
  testTask.systemProperties['file.encoding'] = 'UTF-8'
  testTask.testLogging.showStandardStreams = true
  testTask.systemProperties['BUILD_URL'] = System.getenv()['BUILD_URL']
  testTask.maxParallelForks = 2
  testTask.jacoco {
    enabled = true
    includes = ['com/codeborne/selenide/**/*']
  }
  testTask.outputs.upToDateWhen { false }
}

task allTests(dependsOn: ['clean', 'test', 'chrome', 'firefox', 'htmlunit', 'phantomjs']) {}

jar {
  manifest {
    attributes(
      "Implementation-Title": project.group + '.' + project.name,
      "Implementation-Version": version,
      "Implementation-Vendor": "Codeborne")
  }
}

task sourcesJar(type: Jar, dependsOn:classes) {
  classifier = 'sources'
  from sourceSets.main.allSource
}

javadoc {
  failOnError=false
}

task javadocJar(type: Jar, dependsOn:javadoc) {
  classifier = 'javadoc'
  from javadoc.destinationDir
}

artifacts {
  archives jar
  archives sourcesJar
  archives javadocJar
}

task wrapper(type: Wrapper) {
  gradleVersion = '2.11'
  jarFile = './gradle-wrapper/gradle-wrapper.jar'
  scriptFile = './gradle'
}