Maven - Build Tool - Invocation of JUNIT & TESTNG from POM (Project Object Model)

11:53 PM 0 Comments






Maven is a build automation tool. From Selenium perspective we should be mainly understanding the following sections of the POM (Project Object Model)

1. DEPENDENCIES : 
           Selenium Web-driver mainly depends on  jar for compilation and execution of program. Also if we implement Java Framework - TESTNG / JUNIT, we need add the dependencies for TESTNG / JUNIT as well. Also dependencies gives you the information, that what is the version of the jar we are using for compiling and executing the program.
Also, all the required jars are downloaded into the folder c:\\users\.m2 folder.
.m2 folder is repository folder created by maven, used for referring to the jars required for compilation and execution of program.

SELENIUM DEPENDENCIES:
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>2.45.0</version>
</dependency>
REFERENCE:
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.8.8</version>
</dependency>
REFERENCE:
http://mvnrepository.com/artifact/org.testng/testng/6.8.8

JUNIT DEPENDENCIES:
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.4</version>
</dependency>
REFERENCE:
http://mvnrepository.com/artifact/junit/junit/4.4       
         
2. PLUGINS

Plugins helps to execute the JUNIT/TESTNG programs to execute.
Also in case of JUNIT we have to include Suite class. And in the case of TESTNG we have to include the testng.xml file.

JUNIT PLUGIN INFORMATION
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.18.1</version>
    <dependencies>
      <dependency>
        <groupId>org.apache.maven.surefire</groupId>
        <artifactId>surefire-junit47</artifactId>
        <version>2.18.1</version>
      </dependency>
    </dependencies>
    <configuration>
<includes>
            <include>JunitTestSuite.java</include>
          </includes>
    </configuration>
</plugin>
REFERENCES
http://maven.apache.org/surefire/maven-surefire-plugin/examples/inclusion-exclusion.html

TESTNG PLUGIN INFORMATION:
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.18.1</version>
    <dependencies>
      <dependency>
        <groupId>org.apache.maven.surefire</groupId>
        <artifactId>surefire-junit47</artifactId>
        <version>2.18.1</version>
      </dependency>
    </dependencies>
    <configuration>
<includes>
            <include>testng.xml</include>
          </includes>
    </configuration>

</plugin>
REFERENCES:
http://maven.apache.org/surefire/maven-surefire-plugin/examples/testng.html

0 comments:

Implementation of Page Object Model - Java Design Pattern:

11:10 PM 1 Comments

Page Object Model is the most popular Design pattern used by the developers as a best practice to develop the project.  Before get into the Page Object Model lets discuss the steps to follow once joined as a Automation Tester in the Company.
Steps to Follow:
1. Acquire Domain knowledge for the project.
2. Understand the (SRS) Software Requirement Specification. 
3. Understanding Manual Test cases Ex: Sanity or Regression Test cases     
4. Executing manual Test cases     
5. Identify the Actions perform in each and every page.  
Example: Consider the website Wikipedia. In the main page user can do the search by providing the input and Select the Language and click on Go button as shown below:








void enterText(String inputData)- To enter the text the Search Text-box Ex: India
void selectLanguage(String lang)- To Select a language Ex: English
void clickOnNext()-> To click on the Go Button
boolean verifyText(String expected)->To verify the Text
SearchResultsPage search(String inputData,String lang)-> Clicking on the Go button, navigates to the Search Result Page. So, this function returns an next page object.
Usually the Methods return the Other Page Objects.
6. Write down the methods in every Page.java. 
7. Identify common functions related to Framework.  
getDriverInstance(String browserType)
launchApp(String url)
closeBrowser()
readExcel(String FileName)     
8. Write testcases using Testng Java Framework and invoke the Page related methods in testcases as shown the below program:
Testng Program: WikiTests.java
package com.wiki.tests;
import org.junit.Assert;
import org.openqa.selenium.WebDriver;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
import com.wiki.lib.AppLibrary;
import com.wiki.pages.HomePage;
import com.wiki.pages.SearchResultsPage;

public class WikiTests {

AppLibrary appLib;
static WebDriver driver;
HomePage hPage;
SearchResultsPage sPage;

@Parameters({"browserType","url"})
@BeforeClass
public void invokeBrowser(String browserType,String url)
{
appLib = new AppLibrary();
driver =appLib.getDriverInstance(browserType);
appLib.launchApp(url);

}
@Parameters({"searchInput","lang"})
@Test
public void verifySearchResults(String searchInput,String lang)
{
hPage = new HomePage(driver);
sPage = hPage.search(searchInput,lang);
boolean result = sPage.verifyText(searchInput);
Assert.assertTrue(result);
}
}
HomePage.java
package com.wiki.pages;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.Select;
public class HomePage {
WebDriver driver;
public HomePage(WebDriver driver) 
{
this.driver= driver;
}
public void enterText(String inputData)
{
                    driver.findElement(By.id("searchInput")).sendKeys(inputData);
}
public void selectLanguage(String lang)
{
Select select = new Select(driver.findElement(By.id("searchLanguage")));
select.selectByVisibleText(lang);
}
public void clickOnNext()
{
driver.findElement(By.name("go")).click();
}
 
public boolean verifyText(String expected)
{
String actual = driver.findElement(By.xpath("//a[@href='//www.wikidata.org/']/text()")).getText();
boolean b=false;
if(actual.equals(expected))
{
b= true;
}
return b;

}
public SearchResultsPage search(String inputData,String lang)
{
enterText(inputData);  
selectLanguage(lang) ;  
clickOnNext();  

SearchResultsPage s1 =new SearchResultsPage(driver);
return s1;
}



}

References:
 https://code.google.com/p/selenium/wiki/PageObjects

 Advantages of Page Object Model: 
1. Maintenance of Code is easily  done.   
2. Duplication of Code is removed   
3. Save Time & Effort   




1 comments:

Reading the Parameter Values using org.testng.xml.XmlTest TestNG API- Selenium WebDriver(Java Framework)

2:43 AM 1 Comments

TestNG is the java framework mainly useful to automate the manual testcases and insert verification points.

1. Testng & Junit are both Java Frameworks used by developers to perform unit testing of their code.
2. Junit is subset of Testng. Testng is so powerful due to its advanced features which are as below

a. Grouping of testcases- Group=Sanity 10testcases,Group=Regression 100-Done
b. Paramterization of testcases
c. Parlell execution of testcass
d. Passing multiple values to the testcases using Excel-Done
3. Testng generates very good html reports which are useful to showcase to the stake holders.

Select the project and Press f5 to the see the test-output folder.
a. index.html
b. emailable-report.html


4. TEstng doesnt have main method
5. Testng has annotations.
6. Testng executes the @Test methods in alphabetical order.

For all the testng documentation pls refer to this link ->http://testng.org/doc/documentation-main.html


1 comments:

Selenium Webdriver Encrypting and Decrypting a password/string in Core Java!!!

12:04 AM 1 Comments

For Security reasons, most of the companies has restriction that security information like passwords should not written any where in the programs or xls file in plain text format.

So, in Selenium Webdriver instead of passing plain text for password as an input for the program. We can encrypt the password and pass the encrypted string in the program or xls, and while entering the data in the webpage we can decrypt and enter the password.

This way we can manage the security information, not to steal from others. In order to implement this we should under a concept called cryptography.

Cryptography is a method of storing and transmitting data in a particular form so that only those for whom it is intended can read and process it. The term is most often associated with scrambling plaintext (ordinary text, sometimes referred to as cleartext) into ciphertext (a process called encryption), then back again (known as decryption).













DES(Data Encryption Standard) works by using the same key to encrypt and decrypt a message, so both the sender and the receiver must know and use the same private key. Once the go-to, symmetric-key algorithm for the encryption of electronic data, DES has been superseded by the more secure Advanced Encryption Standard (AES) algorithm.

Encodes the bytes to Base64 using the class Base64.Encoder.


UTF-8 (U from Universal Character Set + Transformation Format—8-bit[1]) is a character encoding capable of encoding all possible characters (called code points) in Unicode.



Program for Implementing the Encryption and Decryption of the password:

package javaprograms;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;

public class EncryptDecryptPassword {
Cipher ecipher;
Cipher dcipher;

EncryptDecryptPassword(SecretKey key) throws Exception {
ecipher = Cipher.getInstance("DES");
dcipher = Cipher.getInstance("DES");
ecipher.init(Cipher.ENCRYPT_MODE, key);
dcipher.init(Cipher.DECRYPT_MODE, key); 
}

public String encrypt(String str) throws Exception {
// Encode the string into bytes using utf-8
byte[] utf8 = str.getBytes("UTF8");

// Encrypt
byte[] enc = ecipher.doFinal(utf8);

// Encode bytes to base64 to get a string
return new sun.misc.BASE64Encoder().encode(enc);
}

public String decrypt(String str) throws Exception {
// Decode base64 to get bytes
byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);

byte[] utf8 = dcipher.doFinal(dec);

// Decode using utf-8
return new String(utf8, "UTF8");
}

public static void main(String[] args) throws Exception {

SecretKey key = KeyGenerator.getInstance("DES").generateKey();
EncryptDecryptPassword encrypter = new EncryptDecryptPassword(key);
String password="selenium";
String encryptedPassword = encrypter.encrypt(password);
String decryptedPassword = encrypter.decrypt(encryptedPassword);
System.out.println(encryptedPassword);
System.out.println(decryptedPassword);
}

}

Output:

Encrypted Password: as/OOfwqcj6ODk6DZshWzQ==

Decrypted Password: selenium

1 comments:

Selenium Interview Questions & Anwsers WebDriver,RC,IDE !!!

3:57 AM 2 Comments

Q: What is WebDriver?

A: WebDriver is a tool for writing automated tests of websites. It aims to mimic the behaviour of a real user, and as such interacts with the HTML of the application.

Q: So, is it like Selenium? Or Sahi?

A: The aim is the same (to allow you to test your webapp), but the implementation is different. Rather than running as a Javascript application within the browser (with the limitations this brings, such as the "same origin" problem), WebDriver controls the browser itself. This means that it can take advantage of any facilities offered by the native platform.

Q: What is Selenium 2.0?

A: WebDriver is part of Selenium. The main contribution that WebDriver makes is its API and the native drivers.

Q: How do I migrate from using the original Selenium APIs to the new WebDriver APIs?

A: The process is described in the Selenium documentation at http://seleniumhq.org/docs/appendix_migrating_from_rc_to_webdriver.html

Q: Which browsers does WebDriver support?

A: The existing drivers are the ChromeDriverInternetExplorerDriverFirefoxDriverOperaDriver and HtmlUnitDriver. For more information about each of these, including their relative strengths and weaknesses, please follow the links to the relevant pages. There is also support for mobile testing via the AndroidDriver, OperaMobileDriver and IPhoneDriver.

Q: What does it mean to be "developer focused"?

A: We believe that within a software application's development team, the people who are best placed to build the tools that everyone else can use are the developers. Although it should be easy to use WebDriver directly, it should also be easy to use it as a building block for more sophisticated tools. Because of this, WebDriver has a small API that's easy to explore by hitting the "autocomplete" button in your favourite IDE, and aims to work consistently no matter which browser implementation you use.

Q: How do I execute Javascript directly?

A: We believe that most of the time there is a requirement to execute Javascript there is a failing in the tool being used: it hasn't emitted the correct events, has not interacted with a page correctly, or has failed to react when an XmlHttpRequest returns. We would rather fix WebDriver to work consistently and correctly than rely on testers working out which Javascript method to call.
We also realise that there will be times when this is a limitation. As a result, for those browsers that support it, you can execute Javascript by casting the WebDriver instance to a JavascriptExecutor. In Java, this looks like:
WebDriver driver; // Assigned elsewhere
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("return document.title");
Other language bindings will follow a similar approach. Take a look at the UsingJavascript page for more information.

Q: Why is my Javascript execution always returning null?

A: You need to return from your javascript snippet to return a value, so:
js.executeScript("document.title");
will return null, but:
js.executeScript("return document.title");
will return the title of the document.

Q: My XPath finds elements in one browser, but not in others. Why is this?

A: The short answer is that each supported browser handles XPath slightly differently, and you're probably running into one of these differences. The long answer is on the XpathInWebDriver page.

Q: The InternetExplorerDriver does not work well on Vista. How do I get it to work as expected?

A: The InternetExplorerDriver requires that all security domains are set to the same value (either trusted or untrusted) If you're not in a position to modify the security domains, then you can override the check like this:
DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
capabilities.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);
WebDriver driver = new InternetExplorerDriver(capabilities);
As can be told by the name of the constant, this may introduce flakiness in your tests. If all sites are in the same protection domain, you shouldbe okay.

Q: What about support for languages other than Java?

A: Python, Ruby, C# and Java are all supported directly by the development team. There are also webdriver implementations for PHP and Perl. Support for a pure JS API is also planned.

Q: How do I handle pop up windows?

A: WebDriver offers the ability to cope with multiple windows. This is done by using the "WebDriver.switchTo().window()" method to switch to a window with a known name. If the name is not known, you can use "WebDriver.getWindowHandles()" to obtain a list of known windows. You may pass the handle to "switchTo().window()".

Q: Does WebDriver support Javascript alerts and prompts?

A: Yes, using the Alerts API:
// Get a handle to the open alert, prompt or confirmation
Alert alert = driver.switchTo().alert();
// Get the text of the alert or prompt
alert.getText();  // And acknowledge the alert (equivalent to clicking "OK")
alert.accept();

Q: Does WebDriver support file uploads?

A: Yes.
You can't interact with the native OS file browser dialog directly, but we do some magic so that if you call WebElement#sendKeys("/path/to/file") on a file upload element, it does the right thing. Make sure you don't WebElement#click() the file upload element, or the browser will probably hang.
Handy hint: You can't interact with hidden elements without making them un-hidden. If your element is hidden, it can probably be un-hidden with some code like:
((JavascriptExecutor)driver).executeScript("arguments[0].style.visibility = 'visible'; arguments[0].style.height = '1px'; arguments[0].style.width = '1px'; arguments[0].style.opacity = 1", fileUploadElement);

Q: The "onchange" event doesn't fire after a call "sendKeys"

A: WebDriver leaves the focus in the element you called "sendKeys" on. The "onchange" event will only fire when focus leaves that element. As such, you need to move the focus, perhaps using a "click" on another element.

Q: Can I run multiple instances of the WebDriver sub-classes?

A: Each instance of an HtmlUnitDriverChromeDriver and FirefoxDriver is completely independent of every other instance (in the case of firefox and chrome, each instance has its own anonymous profile it uses). Because of the way that Windows works, there should only ever be a singleInternetExplorerDriver instance at one time. If you need to run more than one instance of the InternetExplorerDriver at a time, consider using the Remote!WebDriver and virtual machines.

Q: I need to use a proxy. How do I configure that?

A: Proxy configuration is done via the org.openqa.selenium.Proxy class like so:
Proxy proxy = new Proxy();
proxy.setProxyAutoconfigUrl("http://youdomain/config");
// We use firefox as an example here.
DesiredCapabilities capabilities = DesiredCapabilities.firefox();
capabilities.setCapability(CapabilityType.PROXY, proxy);
// You could use any webdriver implementation here
WebDriver driver = new FirefoxDriver(capabilities);

Q: How do I handle authentication with the HtmlUnitDriver?

A: When creating your instance of the HtmlUnitDriver, override the "modifyWebClient" method, for example:
WebDriver driver = new HtmlUnitDriver() {
  protected WebClient modifyWebClient(WebClient client) {
    // This class ships with HtmlUnit itself
    DefaultCredentialsProvider creds = new DefaultCredentialsProvider();

    // Set some example credentials
    creds.addCredentials("username", "password");

    // And now add the provider to the webClient instance
    client.setCredentialsProvider(creds);

    return client;
  }
};

Q: Is WebDriver thread-safe?

A: WebDriver is not thread-safe. Having said that, if you can serialise access to the underlying driver instance, you can share a reference in more than one thread. This is not advisable. You /can/ on the other hand instantiate one WebDriver instance for each thread.

Q: How do I type into a contentEditable iframe?

A: Assuming that the iframe is named "foo":
driver.switchTo().frame("foo");
WebElement editable = driver.switchTo().activeElement();
editable.sendKeys("Your text here");
Sometimes this doesn't work, and this is because the iframe doesn't have any content. On Firefox you can execute the following before "sendKeys":
((JavascriptExecutor) driver).executeScript("document.body.innerHTML = '<br>'");
This is needed because the iframe has no content by default: there's nothing to send keyboard input to. This method call inserts an empty tag, which sets everything up nicely.
Remember to switch out of the frame once you're done (as all further interactions will be with this specific frame):
driver.switchTo().defaultContent();

Q: WebDriver fails to start Firefox on Linux due to java.net.SocketException

A: If, when running WebDriver on Linux, Firefox fails to start and the error looks like:
Caused by: java.net.SocketException: Invalid argument
        at java.net.PlainSocketImpl.socketBind(Native Method)
        at java.net.PlainSocketImpl.bind(PlainSocketImpl.java:365)
        at java.net.Socket.bind(Socket.java:571)
        at org.openqa.selenium.firefox.internal.SocketLock.isLockFree(SocketLock.java:99)
        at org.openqa.selenium.firefox.internal.SocketLock.lock(SocketLock.java:63)
It may be caused due to IPv6 settings on the machine. Execute:
sudo sysctl net.ipv6.bindv6only=0
To get the socket to bind both to IPv6 and IPv4 addresses of the host with the same calls. More permanent solution is disabling this behaviour by editing /etc/sysctl.d/bindv6only.conf

Q: WebDriver fails to find elements / Does not block on page loads

A: This problem can manifest itself in various ways:
  • Using WebDriver.findElement(...) throws ElementNotFoundException, but the element is clearly there - inspecting the DOM (using Firebug, etc) clearly shows it.
  • Calling Driver.get returns once the HTML has been loaded - but Javascript code triggered by the onload event was not done, so the page is incomplete and some elements cannot be found.
  • Clicking on an element / link triggers an operation that creates new element. However, calling findElement(s) after click returns does not find it. Isn't click supposed to be blocking?
  • How do I know when a page has finished loading?
Explanation: WebDriver has a blocking API, generally. However, under some conditions it is possible for a get call to return before the page has finished loading. The classic example is Javascript starting to run after the page has loaded (triggered by onload). Browsers (e.g. Firefox) will notify WebDriver when the basic HTML content has been loaded, which is when WebDriver returns. It's difficult (if not impossible) to know when Javascript has finished executing, since JS code may schedule functions to be called in the future, depend on server response, etc. This is also true for clicking - when the platform supports native events (Windows, Linux) clicking is done by sending a mouse click event with the element's coordinates at the OS level - WebDriver cannot track the exact sequence of operations this click creates. For this reason, the blocking API is imperfect - WebDriver cannot wait for all conditions to be met before the test proceeds because it does not know them. Usually, the important matter is whether the element involved in the next interaction is present and ready.
Solution: Use the Wait class to wait for a specific element to appear. This class simply calls findElement over and over, discarding the NoSuchElementException each time, until the element is found (or a timeout has expired). Since this is the behaviour desired by default for many users, a mechanism for implicitly-waiting for elements to appear has been implemented. This is accessible through theWebDriver.manage().timeouts() call. (This was previously tracked on issue 26).

Q: How can I trigger arbitrary events on the page?

A: WebDriver aims to emulate user interaction - so the API reflects the ways a user can interact with various elements.
Triggering a specific event cannot be achieved directly using the API, but one can use the Javascript execution abilities to call methods on an element.

Q: Why is it not possible to interact with hidden elements?

A: Since a user cannot read text in a hidden element, WebDriver will not allow access to it as well.
However, it is possible to use Javascript execution abilities to call getText directly from the element:
WebElement element = ...;
((JavascriptExecutor) driver).executeScript("return arguments[0].getText();", element);

Q: How do I start Firefox with an extension installed?

A:
FirefoxProfile profile = new FirefoxProfile()
profile.addExtension(....);
WebDriver driver = new FirefoxDriver(profile);

Q: I'd like it if WebDriver did....

A: If there's something that you'd like WebDriver to do, or you've found a bug, then please add an add an issue to the WebDriver project page.

Q: Selenium server sometimes takes a long time to start a new session ?

A: If you're running on linux, you will need to increase the amount of entropy available for secure random number generation. Most linux distros can install a package called "randomsound" to do this.
On Windows (XP), you may be running into http://bugs.sun.com/view_bug.do?bug_id=6705872, which usually means clearing out a lot of files from your temp directory. temp directory.

Q: What's the Selenium WebDriver API equivalent to TextPresent ?

A:
driver.findElement(By.tagName("body")).getText()
will get you the text of the page. To verifyTextPresent/assertTextPresent, from that you can use your favourite test framework to assert on the text. To waitForTextPresent, you may want to investigate the WebDriverWait class.

Q: The socket lock seems like a bad design. I can make it better

A: the socket lock that guards the starting of firefox is constructed with the following design constraints:
  • It is shared among all the language bindings; ruby, java and any of the other bindings can coexist at the same time on the same machine.
  • Certain critical parts of starting firefox must be exclusive-locked on the machine in question.
  • The socket lock itself is not the primary bottleneck, starting firefox is.
The SocketLock is an implementation of the Lock interface. This allows for a pluggable strategy for your own implementation of it. To switch to a different implementation, subclass the FirefoxDriver and override the "obtainLock" method.

Q: Why do I get a UnicodeEncodeError when I send_keys in python

A: You likely don't have a Locale set on your system. Please set a locale LANG=en_US.UTF-8 and LC_CTYPE="en_US.UTF-8" for example.

2 comments:

Selenium WebElement Methods(sendKeys(),getAttribute(),getTagName(),getSize(),getPosition(),getCssValue(String PropertName))

1:13 AM 0 Comments

In Selenium WebDriver when ever we try to idenfity the elements we get the return type as WebElement.

In the below example we are going to explore the different methods available in the WebElement:

HTML Source Code for textbox in Facebook:
<input type="text" class="inputtext _58mg _5dba _2ph-" data-type="text" name="firstname" aria-required="1" placeholder="" id="u_0_1" aria-label="First name"/>

SELENIUM WEBDRIVER CODE:
WebElement element = driver.findElement(By.id("u_0_1"));

Actions performed on the Textbox
element.sendKeys("firstname");
element.clear();
element.click();
element.getAttribute("value");
element.getTagName();
element.getSize();
element.getPosition();
element.isDisplayed()
element.isEnabled()
element.getCssValue(String propertyName) 
 Ex: The propertyName can be background-color.


Actions performed on the button
element.click();
element.submit();

Difference between click() and submit() methods.
If the button is available in the html form then we have to use
submit() method else we have to use click() method.
Refer to the screenshot as displayed below for more information for submit() method:











Misc Information about the WebElement
Apart from the methods mentioned we can findElement() and findElements() methods available.

element.findElement(By)
element.findElements(By)

0 comments:

Installation of Firebug in Chrome and Usage of Firebug in Chrome Browser!!!

1:05 AM 0 Comments


0 comments:

Capturing full Screenshot in Selenium WebDriver using java.awt.Robot Class!!!

12:59 AM 0 Comments

AWT stands for (Abstract Window Toolkit) is mainly useful to develop windows based applications using Core Java.

Basic Example using AWT as shown below:

import java.awt.Button;
import java.awt.Frame;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
/*
 * Basic Example in AWT, Opens a frame with a button having text 'click me;.
 * Clicking on the button closes the frame.
 * 
 */
class BasicAwtEx 
{  
public static void main(String[] args) {
BasicAwtEx b  = new BasicAwtEx();
b.openDialog();
}
public void openDialog()
{
final Frame f = new Frame();
Button b=new Button("click me");  
b.setBounds(30,100,80,30);// setting button position  
b.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
        f.dispose();
        }
     });
 
f.add(b);//adding button into frame  
f.setSize(300,300);//frame size 300 width and 300 height  
f.setLayout(null);//no layout manager  
f.setVisible(true);//now frame will be visible, by default not visible  


}


}

Output:






















Basic Example for taking screenshot using java.awt.Robot Class as shown below:

import java.awt.AWTException;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.GregorianCalendar;
import javax.imageio.ImageIO;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
/*
 * 
 * Taking a screenshot using Robot class in java rather than 
 * TakesScreenshot Interface in Selenium Webdriver.
 *
 */

public class CaptureFullScreen {

public static void main(String[] args) throws AWTException {
try 
{
WebDriver driver = new FirefoxDriver();
driver.get("http://www.google.com");

//Implementing the Robot Class
Robot robot = new Robot();
String format = "jpg";  
String imgFileName= new SimpleDateFormat("mm-dd-yyyy_HH-ss").
format( new GregorianCalendar().getTime());
System.out.println(new GregorianCalendar().getTime());

Rectangle screenRect = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
BufferedImage screenFullImage = robot.createScreenCapture(screenRect);
ImageIO.write(screenFullImage, format, new File("d:\\"+imgFileName+".jpg"));

System.out.println("Screenshot Saved in today's date format in d:\\");
catch (  IOException ex)
{
System.err.println(ex);
}
}
}

Output:




0 comments: