The map is a well known functional programming concept which is incorporated into Java 8. Map is a function defined in java.util.stream.Streams class, which is used to transform each element of the stream. Because of this property, you can use Map in Java 8 to transform a Collection, List, Set or Map. For example, if you have a list of String and you want to convert all of them into upper case, how will you do this? Prior to Java 8, there is no function to do this. You had to iterate through List using a for loop or foreach loop and transform each element. In Java 8, you get the stream, which allow you to apply many functional programming operators like the map, reduce and filter. By using Map function, you can apply any function to every element of Collection. It can be any predefined function or a user-defined function. You not only can use the lambda expression but also, you can also use method references.
Read more »
Search
Saturday, January 31, 2015
Friday, January 30, 2015
The 11AM Avalanche Wedge
Hey everyone,
I wanted to share a post on a "DAY TRADE" setup i look for daily. I call these the 11AM Avalanche Wedges. Over the last few months, what i have noticed is around 11AM (somewhere between 10:30AM and 11:15AM stocks that fall in an "avalanche" manner intra day, tend to find bottoms around 11AM). I don't know why or how it happens, it could be Algo related. Not exactly sure why but i see often enough where i take these intra day trades often. Here's a perfect example of a trade i did today in AMGN.
This trade was good for a quick $1,700 profit.
I like to enter in 2 or 3 pieces by slowly layering into the trade as the stock starts to wedge and show signs of sellers "drying up". Has to be a very sharp selloff from the open, a GAP UP that fades in an avalanche selloff that forms a WEDGE is the most ideal setup.
Hope this helps!
Wednesday, January 28, 2015
Selenium Latest Questions
Part 22
103 : How to customize Firefox browser profile for webdriver software test?
Answer : You can do It In two different ways.
- You can create your desired firefox browser profile before running software automation test and then you can use It In your selenium webdriver software test. VIEW EXAMPLE.
- You can customize your firefox browser profile run time before launching webdriver's Firefox browser Instance. VIEW EXAMPLE.
104 : What is Difference between getAttribute() and getText()?
Answer :
- getAttribute() method Is useful to read software web app element's attribute value like id, name, type etc. VIEW EXAMPLE.
- getText() method Is useful to read text from element or alert. VIEW EXAMPLE.
105 : What is the difference between WebDriver and Remote WebDriver?
Answer : Simple answer for this questions Is as bellow.
- WebDriver : Webdriver Is an Interface or we can say software testing tool using which we can create automated test cases for web application and then run on different browsers like IE, Google chrome, Firefox etc.. We can create test cases In different languages. VIEW MORE DETAIL.
- Remote WebDriver : Remote WebDriver Is useful to run test cases In same machine or remote machines using selenium Grid.
106 : I have total 200 test cases. I wants to execute only 20 test cases out of them. Can I do It In selenium WebDriver? How?
Answer : Yes. If you are using TestNG with selenium webdriver software testing tool then you can do Is using grouping approach as described In THIS PAGE. Create separate group for those 20 test cases and configure testng.xml file accordingly to run only those 20 test cases.
Also If you are using data driven framework then you can configure It In excel file. You can configure such data driven framework at your own by following steps given on THIS PAGE.
Also If you are using data driven framework then you can configure It In excel file. You can configure such data driven framework at your own by following steps given on THIS PAGE.
107 : Can you tell me three different ways to refresh page. Do not use .refresh() method.
Answer : We can refresh browser In many different ways. Three of them are as bellow.
driver.get(driver.getCurrentUrl());
driver.navigate().to(driver.getCurrentUrl());
driver.findElement(By.xpath("//h1[@class='title']")).sendKeys(Keys.F5);
Tuesday, January 27, 2015
Selecting Checkbox From Table Based On Preceding Or Following Sibling Column Value In WebDriver
Locating element's by Its own references Is easy but sometime you need to located them based on reference of other elements. Earlier we have learn how to locate checkbox based on Its position In THIS POST. Now I have one table and first column of table Is checkbox. 2nd column Is value(some
text) and based on that following sibling column's value(text), I wants to select check box from 1st column. I have this scenario In one of my current project. Same way, I have to select checkbox based on preceding sibling column's value(text). See Image bellow.Here check box do not have Its own Identifier bet we have to Identify It based on related previous or next cell's text value. In this case, We can use sibling concept In XPath to locate preceding or following sibling element.
following-sibling
To select Dog checkbox, We have to use following-sibling In xpath as checkbox cell Is following to "Dog" text cell In table. So XPath to locate Dog checkbox Is as bellow.
//td[contains(text(),'Dog')]/following-sibling::td/input[@type='checkbox']
Here,
- //td[contains(text(),'Dog')] will locate "Dog" text cell.
- /following-sibling will locate all siblings after the current node.
- td/input[@type='checkbox'] will locate the checkbox
preceding-sibling
Here Is reverse condition. Checkbox comes first and value text comes last so concept Is same but we have to use word preceding-sibling In XPath as bellow.
//td[contains(text(),'Cow')]/preceding-sibling::td/input[@type='checkbox']
Here,
- //td[contains(text(),'Cow')] will locate "Cow" text cell.
- /preceding-sibling will locate all siblings before the current node.
- td/input[@type='checkbox'] will locate the checkbox
package Testing_Pack;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
public class Slibings {
WebDriver driver;
@BeforeTest
public void setup() throws Exception {
driver =new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("http://only-testing-blog.blogspot.in/2015/01/table-with-checkbox.html");
}
@Test
public void selectCheck(){
//Locating element using preceding-sibling In XPath.
driver.findElement(By.xpath("//td[contains(text(),'Cow')]/preceding-sibling::td/input[@type='checkbox']")).click();
//Locating element using following-sibling In XPath.
driver.findElement(By.xpath("//td[contains(text(),'Dog')]/following-sibling::td/input[@type='checkbox']")).click();
}
}
You can use this sibling concept anywhere to locate any element like checkbox, radiobutton, textbox etc. If It Is dependent on other value.
Sunday, January 25, 2015
Select Checkbox Using Position() and last() Functions In XPath In WebDriver
Selecting checkbox Is not big task In selenium webdriver If check box has ID, Name or any other proper locator. You can check It very easily using .Click() method. .Click() Is generic method and you can use It to click on any element like select radio button, check the check box or clicking on
any other element. But supposing you have a list of Items with checkbox and any checkbox do not have any Identifier then how will you select specific checkbox? NEXT POST will describe how to select checkbox from table using following-sibling and following-siblingSolution 1 : Using Absolute XPath
Consider checkbox list given on THIS PAGE. All the checkbox have type attribute with same value checkbox. Any of them do not have any proper locator using which I can locate specific checkbox. I wants to select check box which Is located In "Cow" row. One way Is using absolute XPath as bellow.
//div[@id='post-body-536524247070242612']/div[1]/table/tbody/tr[3]/td[1]/input
At place of using absolute XPath, We can use functions like last() and position() In XPath to locate specific checkbox.
Read more webdriver tips and tricks on THIS PAGE.
Read more webdriver tips and tricks on THIS PAGE.
Solution 2 : Using position() Function In XPath
In bellow given xpath, [@type='checkbox'] will locate checkbox and function [position()=3] will locate checkbox which Is located on 3rd position from top. You can change your position number as per requirement.
xpath=(//input[@type='checkbox'])[position()=3]
Solution 3 : Using last() Function In XPath
In bellow given xpath, [last()-1] function will locate 2nd last checkbox which Is for Lion.
xpath=(//input[@type='checkbox'])[last()-1]
To locate last checkbox, You can use It as bellow.
xpath=(//input[@type='checkbox'])[last()]
Here Is the practical webdriver example to select checkbox using position() and last() functions.
package Testing_Pack;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
public class Checkboxpos {
WebDriver driver;
@BeforeTest
public void setup() throws Exception {
driver =new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("http://only-testing-blog.blogspot.in/2014/09/temp.html");
}
@Test
public void selectCheck(){
//To select Cow checkbox using position() function.
driver.findElement(By.xpath("(//input[@type='checkbox'])[position()=3]")).click();
//To select Lion checkbox using last() function.
driver.findElement(By.xpath("(//input[@type='checkbox'])[last()-1]")).click();
//To select Tiger checkbox using last() function.
driver.findElement(By.xpath("(//input[@type='checkbox'])[last()]")).click();
}
}
You can use same thing for any element to locate It from list of same Items. You can learn how to get XPath or CSS path of any element using firebug and firepath as described in THIS POST.
What are Inner Classes and its types (Regular, Method local,Anonymous ) In Java
Inner classes are one of the most fundamental topics of java . So in this post first we will discuss what are inner classes and what are the different type of inner classes. Inner classes is an important topic if you are about to give OCJP exam. Although in real world coding , inner classes are not used frequently. But It is better to have an idea , what classes are inner and how to write it in java.
Read Also : Difference between == and equals method
What is Inner Class ?
Inner class is the class with in a class . It is treated like a member of the outer class and has access to all the members of the outer class even those which are declared as private .
For example :
How to compile the above code :
Simple , just write the name of the outer class and following with .java extension
So , we can compile the above code as
javac Outer.java
On executing the above line , you will notice that , it produces the twins (that is two classes , in one command ) , namely ,
Outer.class (expected)
Outer$Inner.class (byproduct)
Now , come the turn to execute the byte code
You can not write
java Outer$Inner.java , As the regular inner class can not have static declarations of any kind . The only way you can access the inner class is through the live instance of the Outer Class .
or in other words
One can interact with Inner class at runtime only , after creating the Outer class instance .
RULE OF THUMB :
To create the instance of the inner class you need to have the instance of the outer class .
Now if you want to access the inner class outside the Outer class , then you need to write down the following code :
public static void main (Strings args[])
{
Outer outerclassobject = new Outer();
Outer.Inner innerclassobject = outerclassobject.new Inner();
}
if you want to write the above code in one line then
Outer.Inner innerclassobject = new Outer().new Inner();
Instantiating an inner class is the only scenario in which you'll invoke new on an instance as opposed to invoking new to construct an instance.
Following modifiers can be applied to a regular inner class
public ,protected ,private ,final , static and strictfp
Method Local Inner Class
There is also another type of inner class called as Method-Local inner class .The regular inner class can be scoped inside one class but outside the method . But the method local inner class is defined inside the method body itself.
Below is the example showing instantiation of the method local inner class .
For the inner class to be used, you must instantiate it, and that instantiation must happen within the same method, but after the class definition code. A method-local inner class cannot use variables declared within the method (including parameters) unless those variables are marked final .
Anonymous Inner Classes
As the name suggests , word anonymous means not identified with name. So,
There is no name of the anonymous inner classes , and their type must be either a subclass of the named type or an implementer of the named interface.
Please find the example of Anonymous class below :
Note :
An anonymous inner class is always treated like a statement in the class code , and remember to close the statement after the class definition with a curly brace. It is rare to found the curly braced followed by semi colon in java .
See the last line of the above code
Read Also : File Handling Java Code with Example
Points to remember about Anonymous Inner Class :
1. Due to polymorphism, the only methods you can call on an anonymous inner class reference are those defined in the reference variable class (or interface), even though the anonymous class is really a subclass or implementer of the reference variable type.
2. An anonymous inner class can extend one subclass or implement one interface. Unlike non-anonymous classes (inner or otherwise), an anonymous inner class cannot do both. In other words, it cannot both extend a class and implement an interface, nor can it implement more than one interface.
3. An argument-defined inner class is declared, defined, and automatically instantiated as part of a method invocation. The key to remember is that the class is being defined within a method argument, so the syntax will end the class definition with a curly brace, followed by a closing parenthesis to end the method call, followed by a semicolon to end the statement: });
Please mention in the comments in case if you have any doubts related to inner class and its type.
Read Also : Difference between == and equals method
What is Inner Class ?
Inner class is the class with in a class . It is treated like a member of the outer class and has access to all the members of the outer class even those which are declared as private .
For example :
class Outer
{
private name ;
class Inner { } // Inner class can access the name member
// of the Outer class even though it is
// declared as private
}
How to compile the above code :
Simple , just write the name of the outer class and following with .java extension
So , we can compile the above code as
javac Outer.java
On executing the above line , you will notice that , it produces the twins (that is two classes , in one command ) , namely ,
Outer.class (expected)
Outer$Inner.class (byproduct)
Now , come the turn to execute the byte code
You can not write
java Outer$Inner.java , As the regular inner class can not have static declarations of any kind . The only way you can access the inner class is through the live instance of the Outer Class .
or in other words
One can interact with Inner class at runtime only , after creating the Outer class instance .
RULE OF THUMB :
To create the instance of the inner class you need to have the instance of the outer class .
Now if you want to access the inner class outside the Outer class , then you need to write down the following code :
public static void main (Strings args[])
{
Outer outerclassobject = new Outer();
Outer.Inner innerclassobject = outerclassobject.new Inner();
}
if you want to write the above code in one line then
Outer.Inner innerclassobject = new Outer().new Inner();
Instantiating an inner class is the only scenario in which you'll invoke new on an instance as opposed to invoking new to construct an instance.
Following modifiers can be applied to a regular inner class
public ,protected ,private ,final , static and strictfp
Method Local Inner Class
There is also another type of inner class called as Method-Local inner class .The regular inner class can be scoped inside one class but outside the method . But the method local inner class is defined inside the method body itself.
Below is the example showing instantiation of the method local inner class .
class Outer2 {
private String x = "Outer2";
void doStuff() {
class Inner {
public void seeOuter() {
System.out.println("Outer x is " + x);
} // close inner class method
} // close inner class definition
Inner one = new MyInner(); // This line must come after the class
one.seeOuter();
} // close outer class method doStuff()
} // close outer class
For the inner class to be used, you must instantiate it, and that instantiation must happen within the same method, but after the class definition code. A method-local inner class cannot use variables declared within the method (including parameters) unless those variables are marked final .
Anonymous Inner Classes
As the name suggests , word anonymous means not identified with name. So,
There is no name of the anonymous inner classes , and their type must be either a subclass of the named type or an implementer of the named interface.
Please find the example of Anonymous class below :
class Apple {
public void iphone() {
System.out.println("iphone");
}
}
class Mobile {
Apple apple = new Apple() {
public void iphone() {
System.out.println("anonymous iphone");
}
};
Note :
An anonymous inner class is always treated like a statement in the class code , and remember to close the statement after the class definition with a curly brace. It is rare to found the curly braced followed by semi colon in java .
See the last line of the above code
Read Also : File Handling Java Code with Example
Points to remember about Anonymous Inner Class :
1. Due to polymorphism, the only methods you can call on an anonymous inner class reference are those defined in the reference variable class (or interface), even though the anonymous class is really a subclass or implementer of the reference variable type.
2. An anonymous inner class can extend one subclass or implement one interface. Unlike non-anonymous classes (inner or otherwise), an anonymous inner class cannot do both. In other words, it cannot both extend a class and implement an interface, nor can it implement more than one interface.
3. An argument-defined inner class is declared, defined, and automatically instantiated as part of a method invocation. The key to remember is that the class is being defined within a method argument, so the syntax will end the class definition with a curly brace, followed by a closing parenthesis to end the method call, followed by a semicolon to end the statement: });
Please mention in the comments in case if you have any doubts related to inner class and its type.
Saturday, January 24, 2015
How to Generate Random Number between 1 to 10 - Java Example
There are many ways to generate random numbers in Java e.g. Math.random() utility function, java.util.Random class or newly introduced ThreadLocalRandom and SecureRandom, added on JDK 1.7. Each has there own pros and cons but if your requirement is simple, you can generate random numbers in Java by using Math.random() method. This method returns a psuedorandom positive double value between 0.0 and 1.0, where 0.0 is inclusive and 1.0 is exclusive. It means Math.random() always return a number greater than or equal to 0.0 and less than 1.0. Internally it uses java.util.Random class. So when you first call this method, it creates instance of Random class and cache it for future use. Any further call is just equivalent of Random.nextDouble(). If your requirement is more sophisticated i.e. you need random numbers between a range or multiple threads needs to generate random number simultaneously, then you should look other random solution available in Java. Since Math.random() method is properly synchronized to ensure correct value is returned when used by multiple thread, it also become bottleneck when multiple thread simultaneously uses it. To solve this problem, JDK 1.7 introduces ThreadLocalRandom class, which allows each thread to keep their own psuedo random number to reduce contention. In a scalable environment, ThreadLocalRandom can improve performance significantly as it keeps the instance of random number generator in a ThreadLocal variable to reduce contention. If security is your concern then you have another option in terms of SecureRandom, which provides a cryptographically strong random number generator. If you are interested to learn more about ThreadLocalRandom and SecureRandom classes then I suggest reading Java Performance The Definitive Guide By Scott Oaks, he has covered them in good detail in a separate section.
Read more »
Thursday, January 22, 2015
How To Convert Map to List in Java with Example
Before converting a Map to a List in Java, we should be very clear about these data structures which is widely used in Java. So lets begin with Map. What is Map? Map is an Interface in Java which store key and value object. It's Java representation of popular hash table data structure which allows you to search an existing element in O(1) time, at the same time also makes insertion and removal easier. We use key object to retrieve the value object by using hashing functionality provided by Map. As we have seen in how get method of HashMap works, In Java, equals() and hashcode() method are integral part of storing and retrieving object from it. Map allows duplicate values but no duplicate keys. Map has its implementation in various classes like HashMap, ConcurrentHashMap and TreeMap. The Map interface also provides three collection views, which allow a map's contents to be viewed as a set of keys, collection of values, or set of key-value mappings. Now let's understand what is a List in Java, It is also an interface to provide an ordered collection based on index. Elements can be inserted and deleted using positions and duplicate elements are allowed in the list. There are multiple implementation of List is available in Java e.g. ArrayList, which is based in array and LinkedList which is based in linked list data structure. Now let's see a Java program which is used to convert a Map to List.
Read more »
Wednesday, January 21, 2015
How To Disable JavaScript Using Custom Profile For selenium WebDriver Test
Many times you need to disable JavaScript In your browser to verify that function or validation Is working fine even If JavaScript Is disabled. Simple example Is you need to disable JavaScript of Firefox browser to check server side validation of Input text field. Enabling or disabling JavaScript Is
simple task If you will do It manually but how to do same thing In selenium webdriver test?As you know, Selenium webdriver launch fresh browser every time so your current browser's settings will not work In webdriver launched browser. So we need to write some special code In test case to disable JavaScript run time. Earlier I have provided example of how to enable or disable JavaScript In selenium IDE on THIS POST. Now let us learn how to do It In selenium WebDriver.
WebDriver has very good feature which allows us to create custom profile for firefox browser and then we can set/update browser's settings run time. Earlier we have set and used browser's custom profile run time to download different files as described In THIS POST. We will use same thing here to disable javascript.
Bellow given syntax will create new firefox profile and set JavaScript disabled.
FirefoxProfile profile = new FirefoxProfile();
profile.setPreference("javascript.enabled", false);
and then we can use that custom profile In webdriver launched browser using bellow given syntax.
WebDriver driver = new FirefoxDriver(profile);
So now your webdriver browser's JavaScript Is disabled. To verify It practically, Run bellow given example In eclipse. It will click on Show Me Alert button but due to the disabled Javascript, Alert will not not prompted. Used checkAlertPresent() function to verify If alert Is present or not on page.
package Testing_Pack;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.NoAlertPresentException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
public class jscript {
WebDriver driver;
@BeforeTest
public void setup() throws Exception {
//Create new firefox custom profile.
FirefoxProfile profile = new FirefoxProfile();
//Disable javascript for newly created profile.
profile.setPreference("javascript.enabled", false);
//Use custom profile which has javascript disabled In webdriver launched browser.
driver = new FirefoxDriver(profile);
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("http://only-testing-blog.blogspot.in/2014/01/textbox.html");
}
@Test
public void getCoordinates(){
//Click on button to get Javascript alert.
driver.findElement(By.xpath("//input[@value='Show Me Alert']")).click();
//Check If alert Is present or not.
if(checkAlertPresent()){
//If alert present then bellow given code will be executed.
Alert alert = driver.switchTo().alert();
System.out.println(alert.getText());
System.out.println("Alert present");
alert.accept();
}
}
public boolean checkAlertPresent(){
try{
//It will return true If alert present.
driver.switchTo().alert();
return true;
}catch(NoAlertPresentException ex){
//It will return false If alert not present and print bellow given message In console.
System.out.println("No Alert present. Verify If javascript Is disabled.");
return false;
}
}
}
This way you can disable javascript In your selenium webdriver test using custom profile.
Monday, January 19, 2015
How To Capture Element Screenshot Using Selenium WebDriver
I have received many requests from blog readers to share example on how to capture specific element screenshot In selenium webdriver. As you know, Capturing entire page screenshot Is very easy task as described In THIS POST. But If you wants to capture screenshot of specific web
element then you will feel that It Is little challenging task. Let me try to make It easy for you.We need to use many different classes and methods of java and selenium webdriver to capture web element screenshot. Test execution sequence to capture screenshot of element Is as bellow.
- Locate Image element and call captureElementScreenshot function to capture Its screenshot.
- Capture full screenshot as buffered Image
- Get element's height and width using getSize() method as described In THIS POST.
- Get element's X Y coordinates using Point class as described In THIS POST.
- Read buffered Image.
- Crop buffered Image using element's x y coordinate position and height width parameters.
- Save cropped Image at destination location physically.
Bellow given example will be executed as execution sequence described above. Detailed description Is provided with each syntax.
Example to capture screenshot of Image element.
package Testing_Pack;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import javax.imageio.ImageIO;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.Point;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
public class elementScreenshot {
WebDriver driver;
@BeforeTest
public void setup() throws Exception {
driver =new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("http://only-testing-blog.blogspot.in/2014/09/selectable.html");
}
@Test
public void captureScreenshot() throws Exception {
//Locate Image element to capture screenshot.
WebElement Image = driver.findElement(By.xpath("//img[@border='0']"));
//Call captureElementScreenshot function to capture screenshot of element.
captureElementScreenshot(Image);
}
public void captureElementScreenshot(WebElement element) throws IOException{
//Capture entire page screenshot as buffer.
//Used TakesScreenshot, OutputType Interface of selenium and File class of java to capture screenshot of entire page.
File screen = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
//Used selenium getSize() method to get height and width of element.
//Retrieve width of element.
int ImageWidth = element.getSize().getWidth();
//Retrieve height of element.
int ImageHeight = element.getSize().getHeight();
//Used selenium Point class to get x y coordinates of Image element.
//get location(x y coordinates) of the element.
Point point = element.getLocation();
int xcord = point.getX();
int ycord = point.getY();
//Reading full image screenshot.
BufferedImage img = ImageIO.read(screen);
//cut Image using height, width and x y coordinates parameters.
BufferedImage dest = img.getSubimage(xcord, ycord, ImageWidth, ImageHeight);
ImageIO.write(dest, "png", screen);
//Used FileUtils class of apache.commons.io.
//save Image screenshot In D: drive.
FileUtils.copyFile(screen, new File("D:\\screenshot.png"));
}
}
Run above example In eclipse and open D: drive at the end of test execution. There will be created new file with name "screenshot.png". Open It to verify screenshot Is proper. This way, You can capture screenshot of any web element.
Sunday, January 18, 2015
Selenium WebDriver Tips And Tricks
Sometimes you need to take tricky actions on software web application page. Selenium webdriver software testing tool do not have any direct method to perform such tricky actions. So you need to use some tricks in your webdriver test script to perform some actions on software web application page. Bellow given links will show you some tricks using which you can perform complex actions In selenium webdriver tests very easily.
- How To Get X Y Coordinates Of Element
- How To Get Height And Width Of Element
- How To Capture Element Screenshot
- How To Disable JavaScript Using Custom Profile
- Selecting Checkbox Using Position() and last() Functions In XPath
- Select Checkbox From Table using Preceding/Following Sibling
- Set/Get Window Position And Size In Selenium Test
- Handling Stale Element Reference Exception In Selenium
- Scroll Down-Up Web Page In Selenium Webdriver
- Verify Scroll Present On Browser In Selenium WebDriver Test
- How To Record Selenium WebDriver Test Execution Video
- Zoom In And Zoom Out Page In Selenium Test
- Wait For Page To Load/Ready In Selenium
- Capture Page JavaScript Errors Using WebDriver
- Open New Tab And Switching Between Tabs In WebDriver
- Switching between Iframes In webdriver
- Handle SSL Certificate Error In FF For Selenium WebDriver
- Set Proxy Settings In Selenium WebDriver
- Automating Pie Chart In Selenium WebDriver
- WebDriver Element Locator Add-On To Get XPath
- Closing All Tabs Using Robot Class In Selenium
- Data Driven Test Using CSV File In Selenium
How To Get Height And Width Of Element In Selenium WebDriver
As you know, Every web element has Its own height and width or we can say size of element. Sometimes you need to perform pixel to pixel testing as per client's requirement like each and every button's height should be x(some pixels) and width should be y(some pixels) through out the site.
Now If you go for measuring height and width of every element manually then It Is time consuming on every test cycle. Automation Is best solution to measure height and width of elements because It Is one time exercise and then you can use It In every test cycle.
Now If you go for measuring height and width of every element manually then It Is time consuming on every test cycle. Automation Is best solution to measure height and width of elements because It Is one time exercise and then you can use It In every test cycle.
We have learnt how to get x y coordinates of element using selenium webdriver In previous post. Now let us learn how to get size of element. I have prepared simple example to explain you how to get height and width of Image In selenium webdriver. As you can see In bellow example, I have used getSize() method to get height and width of element.
package Testing_Pack;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
public class getElementSize {
WebDriver driver;
@BeforeTest
public void setup() throws Exception {
driver =new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("http://only-testing-blog.blogspot.in/2014/09/selectable.html");
}
@Test
public void getSize() throws Exception {
//Locate element for which you wants to get height and width.
WebElement Image = driver.findElement(By.xpath("//img[@border='0']"));
//Get width of element.
int ImageWidth = Image.getSize().getWidth();
System.out.println("Image width Is "+ImageWidth+" pixels");
//Get height of element.
int ImageHeight = Image.getSize().getHeight();
System.out.println("Image height Is "+ImageHeight+" pixels");
}
}
When you run above test In eclipse, It will print height and width of element In console as bellow.
Image width Is 212 pixels
Image height Is 191 pixels
We can use Height And Width Of Element to capture element's screenshot as described In THIS POST.
This way you can find any element's size In selenium test.
Friday, January 16, 2015
Second Highest Salary in MySQL and SQL Server - LeetCode Solution
Write a SQL query to get the second highest salary from the Employee table.
+----+--------+
| Id | Salary |
+----+--------+
| 1 | 100 |
| 2 | 200 |
| 3 | 300 |
+----+--------+
For example, given the above Employee table, the second highest salary is 200. If there is no second highest salary, then the query should return NULL. You can write SQL query in any of your favorite database e.g. MySQL, Microsoft SQL Server or Oracle. You can also use database specific feature e.g. TOP, LIMIT or ROW_NUMBER to write SQL query, but you must also provide a generic solution which should work on all database. In fact, there are several ways to find second highest salary and you must know couple of them e.g. in MySQL without using LIMIT keyword, in SQL Server without using TOP and in Oracle without using RANK and ROWNUM. Once you solve the problem, Interviewer will most likely increase the difficulty level by either moving to Nth salary direction or taking away this buit-in utilities.
Read more »
+----+--------+
| Id | Salary |
+----+--------+
| 1 | 100 |
| 2 | 200 |
| 3 | 300 |
+----+--------+
For example, given the above Employee table, the second highest salary is 200. If there is no second highest salary, then the query should return NULL. You can write SQL query in any of your favorite database e.g. MySQL, Microsoft SQL Server or Oracle. You can also use database specific feature e.g. TOP, LIMIT or ROW_NUMBER to write SQL query, but you must also provide a generic solution which should work on all database. In fact, there are several ways to find second highest salary and you must know couple of them e.g. in MySQL without using LIMIT keyword, in SQL Server without using TOP and in Oracle without using RANK and ROWNUM. Once you solve the problem, Interviewer will most likely increase the difficulty level by either moving to Nth salary direction or taking away this buit-in utilities.
Wednesday, January 14, 2015
WebDriver Latest Questions
Part 21
98 : Do you know any external API name using which we can read data from excel file?
Answer :
- We can use jxl API (Java Excel API) to read data from excel file. VIEW EXAMPLE
- We can use one more powerful API known as Apache POI API to read and write data In excel file. I have created data driven framework using Apache POI API. You can VIEW DATADRIVEN FRAMEWORK CREATION TUTORIALS step by step.
Answer : WebDriver's different 5 exceptions are as bellow.
- TimeoutException - This exception will be thrown when command execution does not complete In given time.
- NoSuchElementException - WebDriver will throw this exception when element could not be found on page.
- NoAlertPresentException - This exception will be generated when webdriver ties to switch to alert popup but there Is not any alert present on page.
- ElementNotSelectableException - It will be thrown when webdriver Is trying to select unselectable element.
- ElementNotVisibleException - Thrown when webdriver Is not able to Interact with element which Is available In DOM but It Is hidden.
- StaleElementReferenceException - VIEW DESCRIPTION.
100 : Tell me different ways to type text In text box In selenium test.
Answer : We can type text In text box of web page using bellow given ways In selenium test.
1.Using .SendKeys() method
2. Using JavascriptExecutor
3. Using Java Robot class VIEW EXAMPLE
1.Using .SendKeys() method
driver.findElement(By.xpath("//input[@id='fname']")).sendKeys("Using sendKeys");
2. Using JavascriptExecutor
((JavascriptExecutor)driver).executeScript("document.getElementById('fname').value='Using JavascriptExecutor'");
3. Using Java Robot class VIEW EXAMPLE
driver.findElement(By.xpath("//input[@id='fname']")).click();
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_U);
robot.keyPress(KeyEvent.VK_S);
robot.keyPress(KeyEvent.VK_I);
robot.keyPress(KeyEvent.VK_N);
robot.keyPress(KeyEvent.VK_G);
robot.keyPress(KeyEvent.VK_SPACE);
robot.keyPress(KeyEvent.VK_R);
robot.keyPress(KeyEvent.VK_O);
robot.keyPress(KeyEvent.VK_B);
robot.keyPress(KeyEvent.VK_O);
robot.keyPress(KeyEvent.VK_T);
101 : Tell me different ways to verify element present or not on page.
Answer : We can check If element Is present or not using bellow given 2 simple ways.
1. Using .size() method
2. Using .isEmpty() method
1. Using .size() method
Boolean elePresent = driver.findElements( By.id("ID of element") ).size() != 0;
If above syntax return "false" means element Is not present on page and "true" means element Is present on page.2. Using .isEmpty() method
Boolean elePresent = driver.findElements(By.id("ID of element")).isEmpty();
If this returns "true" means element Is not present on page and "false" means element Is present on page.102 : Why we need to customize Firefox browser profile In webdriver test?
Answer : Webdriver launch fresh browser Instance when we run tests In Firefox browser using selenium webdriver. Fresh browser Instance do not have any Installed add-ons, saved passwords, bookmarks and any other user preferences. So we need to create custom profile of Firefox browser to get any of this thing In Webdriver launched browser. VIEW MORE DETAIL WITH EXAMPLE
Tuesday, January 13, 2015
Core Java Coding / Programming Questions and Answers : Technical Interview in Java
If you want to be a java developer , then you must have faced core java technical round during the recruitment process .There may be few tricky java interview questions , but sadly , most of the students find it the hardest round in the interview process . The problem lies in the practicing part but it can be overcome . The solution is to prepare must know questions of the technical round . So knowing those questions gives us an edge over others . So here I am sharing coding/programming questions and answers of core java which are frequently asked by the interviewer in Technical round of Java programming language.
Read Also : Top 25 frequently asked core java interview questions
Due to slow internet connection , some of our readers were not able to view all the questions . So ,
we decided to split this image rich post into two pages.
Let us discuss one by one ,
* Interviewer shows you the following code
Is the code compiles ? If yes then what will be the output ?
Answer >>
Compile : Yes
Output : String
Next Question >>
Is the code compiles ? If yes then what will be the output ?
Answer >>
Compile : No , Error at line 23
Reason : Method is ambiguous
Next Question >>
Is the code compiles ? If yes then what will be the output ?
Answer >>
Compile : Yes
Output : ArithmeticException
Next Question >>
Is the code compiles ? If yes then what will be the output ?
Answer >>
Compile : Yes
Output : Java Hungry Blogspot
Next Question >>
Is the code compiles ? If yes then what will be the output ?
Answer >>
Compile : Yes
Output : I am born new
Next Question >>
Is the code compiles ? If yes then what will be the output ?
Answer >>
Read Also : Top 25 frequently asked core java interview questions
Due to slow internet connection , some of our readers were not able to view all the questions . So ,
we decided to split this image rich post into two pages.
Let us discuss one by one ,
* Interviewer shows you the following code
Is the code compiles ? If yes then what will be the output ?
Answer >>
Compile : Yes
Output : String
Next Question >>
Is the code compiles ? If yes then what will be the output ?
Answer >>
Compile : No , Error at line 23
Reason : Method is ambiguous
Next Question >>
Is the code compiles ? If yes then what will be the output ?
Answer >>
Compile : Yes
Output : ArithmeticException
Next Question >>
Is the code compiles ? If yes then what will be the output ?
Answer >>
Compile : Yes
Output : Java Hungry Blogspot
Next Question >>
Is the code compiles ? If yes then what will be the output ?
Answer >>
Compile : Yes
Output : I am born new
Next Question >>
Is the code compiles ? If yes then what will be the output ?
Answer >>
Sum of Digits using Recursion in Java
This is the second part of our article to solve this coding interview question, how to find sum of digits of a integer number in Java. In first part, we have solved this problem without using recursion i.e. by using while loop and in this part we will solve it by using recursion. It's good to know different approaches to solve the same problem, this will help you to do well on coding interviews. While finding recursive algorithm, always search for base case, which requires special handling. Once you find the base case, you can easily code the method by delegating rest of processing to method itself, i.e. by using recursion. In this problem, base case is when the number becomes zero, at that time our program is complete and we return the sum of digits of given number. Another property of a recursive algorithm is that with each passing steps your program approaches to result and problems becomes shorter. For example in this coding problem, after each call one digit from the number is reduced. So if you provide 5 digit number then it will require five steps to complete. One key thing you need to know to solve this problem is the trick to get last digit of an integral number. You can use modulo operator to do that, number%10 always return the last digit.
Read more »
Subscribe to:
Posts (Atom)