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'
}

Friday, March 4, 2016

Java : System.out.print not displaying

System.out.print not displaying





http://stackoverflow.com/questions/3963708/gradle-how-to-display-test-results-in-the-console-in-real-time


Example :


test {
    testLogging {
 events "passed", "skipped", "failed", "standardOut", "standardError"
 showStandardStreams = true
 
 }
}

Thursday, March 3, 2016

Eclipse : Git and Git hub basics

Eclipse has a built-in Git functionality

1.Project>rt ck
2. Team>Share project
3. Check  CheckBox: Use or Create Project in Parent Repository in parent folder of Project
4. Click on the Project in Project Window- Create Repository becomes enabled
5. Note down the git name ie "ABC.git" (Same as your project name)- which is at the end of the project.
6. Click on finish

7. Login to GIThub
8. Click on new Repository
9. Enter name noted in step 5 or you project name in Repository name field and click on create repositorybutoon
10 . Note down the "http" address of the repository
11. In Eclipse >Rt ck on project
12. Team>Commit
13. Select required files , add a comment and click on Commit and push button.
14. In destinatiron Git Repository window enter URL from step 10 and add relavant information
15. Click on Finish



1. Creating new Git repository (Moving current project to local repository)
    a)Select project rt click>Team>Share project>Git
    b) Click on Create Repository button
    c) Select folder path (give name  starting 'local_'
    d) finish
    e)close open the opened file
    f)goto the project moved to repository rtck>observer location
   
   
2. Adding Git views to perspective
        a)window>show view>other>Git>select both Git Staging and Git Repository
        b)window>show view>other>team>history
       
3.Enable Git buttons in tool bar
    a)Window>Customize perspective
    b) Select tab Command groups Availability
    c)enable git
    d) Ok
   
4.Commit code
    a)Project right ck
    b)team>Commit
    c) In commit chnages window >enter message
    d)Select files to check in (no need to check in class files)
    e)click on commit
    f)goto git repository window>local_xxx>branchs>local>"Masterxxx"+comment
   
5. to view history
        a)select the branch in git repository
        b)Rt ck>show in>history
       
6. To Integrate with github
    a)create account in github
    b)ck on new repository button
    c) enter a name in "Repository name" field"
    d)click on "Create repository"
    e) copy the SSH "url"
   
    f)In ecplise>open the same project
    g)goto git repository
    h)Rt ck on "remotes"
    i)configure push selected ,origin
    j)enter the URL copied , enter usn and pass
    k)In the nect window , click advanced
    l)under ource ref>select master
    m)save
    n)finish
   
    o)goto >remotes>origin>click on "red arrow out"symbol or right ck and push
    p)goto github and validate
   
7)Checkin in git and github
    a)use checkin button in the tools bar
    b) enter comments
    c)click on push (only pushes to local)
    d)goto Branches>master>rt ck and  push
    e)verify the same in github
   

8)show all files
    a)window>show view>other>navigator
   
9)ignore
    a)rt ck>team>ignore (generates ignore file)
    b)select gitignorefile and click on commit button
    c)ck commit
    d)ck on push button

Java : Building Better GUI (GUI for framework ),without looping

Building Better GUI (GUI for framework)


Use following steps as guideline :
  1. Use Eclipse .
  2. Add window builder plugin to eclipse 
  3. While Creating Swing file , Select "Dialog" in Swing Designer 
  4. Create a GUI as required
  5. Right click on components to add listeners .
  6. In the Main class (calling function) , use below Code :

CODE :
public class test3 {

public static boolean bGUI_Yes=false;
public static void main(String[] args) {
GUI2 f2=new GUI2();// GUI2 is the GUI created using window builder
f2.setModal(true); //Modal tells thread to wait until user enters data ,should always be visible
f2.setVisible(true);

if(test3.bGUI_Yes==true) // set to true in the action listener inside OK button
System.out.println(f2.bGUI_UseExcel+ " "+f2.sGUI_testcases+" "+f2.sBrowser);
else
System.out.println("closed");
}
}


Note :
Cant stress enough - Select Dialog never select Jframe for this case  .
 

Java : Custom Dialog box (JDialog)

Custom Dialog box (JDialog)



JTextField username = new JTextField();
JTextField password = new JPasswordField();
Object[] message = {
    "Username:", username,
    "Password:", password
};

int option = JOptionPane.showConfirmDialog(null, message, "Login", JOptionPane.OK_CANCEL_OPTION);
if (option == JOptionPane.OK_OPTION) {
    if (username.getText().equals("h") && password.getText().equals("h")) {
        System.out.println("Login successful");
    } else {
        System.out.println("login failed");
    }
} else {
    System.out.println("Login canceled");
}

Wednesday, March 2, 2016

Selenium :Run Testng.xml using a Java file

Run Testng.xml using a Java file

http://stackoverflow.com/questions/23272861/how-to-call-testng-xml-from-java-main-method




// Create object of TestNG Class
TestNG runner=new TestNG();

// Create a list of String 
List<String> suitefiles=new ArrayList<String>();

// Add xml file which you have to execute
suitefiles.add("C:\\Automation Test\\Git\\vne_automation\\testng.xml");

// now set xml file for execution
runner.setTestSuites(suitefiles);

// finally execute the runner using run method
runner.run();