• No results found

Technical Challenges With Selenium

N/A
N/A
Protected

Academic year: 2021

Share "Technical Challenges With Selenium"

Copied!
232
0
0

Loading.... (view fulltext now)

Full text

(1)

Technical Challenges with Selenium

WHAT ARE THE TECHNICAL CHALLENGES WITH SELENIUM?

As you know Selenium is a free ware open source testing tool. There are many challenges with Selenium.

1. Selenium supports only web based applications.

2. It doesn't support any non web based (Like Win 32, Java Applet, Java Swing, .Net Client Server etc) applications.

3. When you compare selenium with QTP, Silk Test, Test Partner and RFT, there are many challenges in terms of maintainability

of the test cases.

4. Since Selenium is a freeware tool, there is no direct support if one is in trouble with the support of applications.

5. There is no object repository concept in Selenium, so maintainability of the objects is very high

6. There are many challenges if one have to interact with Win 32 windows even when you are working with Web based applicati

ons.

7. Bitmap comparison is not supported by Selenium.

8. Any reporting related capabilities, you need to depend on third party tools.

9. You need to learn any one of the native language like (.Net, Java, Perl, Python, PHP, Ruby) to work efficiently with the scriptin

g side of selenium.

JUnit 4 Vs TestNG

BELOW ARE SOME OF THE DIFFERENCES LISTED BETWEEN JUNIT 4 AND TESTNG

1. ANNOTATION @TEST IS USED IN BOTH JUNIT4 AND TESTNG BUT FROM DIFFERENT CLASS:

import org.junit.Test; // JUnit 4

or

import org.testng.annotations.Test; // TestNG

public class MyTestClass {

@Test public void aTestMethod() throws ...

{ ...

}

}

2. ACCORDING TO ANNOTATION SUPPORT:

Feature

JUnit 4

TestNG

Test annotation

@Test

@Test

Run before all tests in this suite have run

@BeforeSuite

Run after all tests in this suite have run

@AfterSuite

Run before the test

@BeforeTest

Run after the test

@AfterTest

Run before the first test method that belongs

(2)

Run after the last test method that belongs to

any of these groups is invoked

@AfterGroups

Run before the first test method in the current

class is invoked

@BeforeClass

@BeforeClass

Run after all the test methods in the current

class have been run

@AfterClass

@AfterClass

Run before each test method

@Before

@BeforeMethod

Run after each test method

@After

@AfterMethod

Ignore test

@ignore

@Test(enbale=false)

Expected exception

@Test(expected =

ArithmeticException.class)

@Test(expectedExceptions =

ArithmeticException.class)

Timeout

@Test(timeout = 1000)

@Test(timeout = 1000)

3. EXCEPTION TEST

It explains what exception will throw from the unit test.

//JUnit4

@Test(expected = ArithmeticException.class)

public void divisionByZeroException() {

int i = 1/0;

}

//TestNG

@Test(expectedExceptions = ArithmeticException.class)

public void divisionByZeroException() {

int i = 1/0;

}

4. Ignore Test

It explains how to ignore the unit test.

//JUnit

@Ignore("Not Ready to Run")

@Test

public void IgnoreTest() {

System.out.println("Method is not ready yet");

}

//TestNG

@Test(enabled=false)

public void IgnoreTest() {

System.out.println("Method is not ready yet");

}

(3)

5. SUITE TEST

5. Suite Test

It explains how to bundle a few unit test and run together.

//JUnit4

The "@RunWith" and "@Suite" are use to run the suite test. The below class means both unit test "JunitTest1" and "JunitTest2"

run together after "JunitTest3" executed. All the declaration is define inside the class.

@RunWith(Suite.class)

@Suite.SuiteClasses({

JunitTest1.class,

JunitTest2.class

})

public class JunitTest3 {

}

//TestNG

XML file is use to run the suite test. The below XML file means both unit test “TestNGTest1” and “TestNGTest2” will run it

together.

<suite name="My test suite">

<test name="My test">

<classes>

<class name="example.test.TestNGTest1" />

<class name="example.test.TestNGTest2" />

</classes>

</test>

</suite>

6. DEPENDENCY TEST

It explains which test will execute after what test. If the dependent method fails, then all subsequent tests will be skipped, not

marked as failed.

//JUnit4

JUnit framework is focus on test isolation; it did not support this feature at the moment.

//TestNG

It use "dependOnMethods" to implement the dependency testing as following

@Test

(4)

System.out.println("This is method 1");

}

@Test(dependsOnMethods={"testMethod1"})

public void testMethod2() {

System.out.println("This is method 2");

}

7. PARAMETERIZED TEST

It says how to pass parameters to an unit test dynamically.

//JUnit4

The "@RunWith" and "@Parameter" is use to provide parameter value for unit test, @Parameters have to return List[], and the

parameter will pass into class constructor as argument.

@RunWith(value = Parameterized.class)

public class JunitTest {

private int number;

public JunitTest(int number) {

this.number = number;

}

@Parameters

public static Collection<Object[]> data() {

Object[][] data = new Object[][] { { 1 }, { 2 }, { 3 }, { 4 } };

return Arrays.asList(data);

}

@Test

public void pushTest() {

System.out.println("Parameterized Number is : " + number);

}

}

It has many limitations here; we have to follow the “JUnit” way to declare the parameter, and the parameter has to pass into

constructor in order to initialize the class member as parameter value for testing. The return type of parameter class is “List *+”,

data has been limited to String or a primitive value for testing.

//TestNG

XML file or “@DataProvider” is used to provide vary parameter for testing.

ADVANTAGES OF WEB DRIVER

1) Support for iPhone and Android testing

2) Implementation of listeners - a much awaited feature

3) Better features for Ajax testing.

4) You can easily simulate clicking on front and back button of browser.

5) You can extract objects in bulk like QTP. For ex - extract all links of page. With RC this was a big hastle

6) Unlike RC you don’t have to start a server in webdriver.

7) You can simulate movement of a mouse using selenium.

8) Tabs and pops are more or less the same. RC can also handle and Webdriver can also handle.

9) You can find coordinates of any object using Webdriver.

10) You have classes in Webdriver which help you to simulate key press events of keyboard.

10) Keyword driven framework is very easy to build in webdriver.

TestNG Basic Concepts and Annotations

(5)

3)

4) TestNG engine supports a series of annotations, with these annotations it even has stronger flexibility and extensibility

than Junit, we will seethese annotations one by one in detail, first of all, let us have a quick look at the life cycle of a

typical TestNG case.

5)

6)

7)

8) From the given illustration, we know that the life-cycle of a TestNG case starts with @BeforeClass and ends

with@AfterClass. @BeforeClass/@AfterClass methods will be run before/after any method in a given is run, they are

designed for those expensive resource initialization/cleanup and recovery, we didn’t put @BeforeSuite,

@BeforeGroups, @AfterGroups and @AfterSuite to this illustration, but if they were, they will be ran even

before @BeforeClass or after @AfterClass. @Configuration is deprecated so we don’t recommend use it.

9)

10) TESTNG BASIC ANNOTATIONS FOR CONFIGURATION METHODS

Pri Annotation name

Documentation

1

@BeforeSuite

Annotates methods that will be run before any method in a given is run.

2

@BeforeGroups

Annotates methods that will be run before the first method in any of the specified groups is

run.

(6)

4

@BeforeTest

Annotates methods that will be run before any method in a given is run.

5

@BeforeMethod

Annotates methods that will be run before each test method.

6

@AfterMethod

Annotates methods that will be run after every test method.

7

@AfterTest

Annotates methods that will be run after all the test methods in a given have been run.

8

@AfterClass

Annotates methods that will be run after the last test method on the current class is run.

9

@AfterGroups

Annotates methods that will be run after the last test method belonging to the groups

specified in its value attribute has been run. The annotated method is automatically put into

these specified groups.

10 @AfterSuite

Annotates methods that will be run after all the test methods in a given have been run.

11) The annotations @Test annotates a method as test case in TestNG pattern.

12)

13)

Simple Example with TestNG Annotations

package com.My_Project;

import org.testng.annotations.*;

public class TestNGTest {

@BeforeGroups

public void BeforeGroups() {

System.out.println("@BeforeGroups");

}

@BeforeClass

public void BeforeClass() {

System.out.println("@BeforeClass");

}

@Test(groups = {"My group"})

public void test1() {

System.out.println("test1");

}

@Test

public void test2() {

System.out.println("test2");

}

@AfterClass

public void AfterClass() {

System.out.println("@AfterClass");

}

AfterMethod

public void AfterMethod() {

System.out.println("@AfterMethod");

}

(7)

Here is the output of this Above code

[Parser] Running:

C:\Users\Administrator\.IntelliJIdea70\system\temp-testng-customsuite.xml

@BeforeClass

test1

@AfterMethod

test2

@AfterMethod

@AfterClass

===============================================

Custom suite

Total tests run: 2, Failures: 0, Skips: 0

===============================================

Selenium Basics

WHAT IS SELENIUM ?

Selenium is a Testing framework for web applications, having 3 variants:

Selenium IDE

- Firefox add-on

- Record and playback user actions on a web site

- Not recommend for stable, long staying test suites

Selenium RC (Remote Control, Selenium 1)

- Java Server that controls various browsers

- Executes scripted user actions from a typically JUnit programming environment,

- Has a “string-based” programming API

- Supports variety of browsers (Internet Explorer , Firefox, safari, chrome, opera etc )

Selenium WebDriver (Selenium 2)

- Java Library, which controls the browser

- Has a object-oriented programming API

- Supports Internet Explorer, Firefox, Chrome and HtmlUnit as drivers

I recommend using the WebDriver API!

WebDriver with TestNG - Gmail Login Functionality

Below is the code for GMAIL Login functionality using WebDriver with TestNG

package com.test.webdriver;

import static org.testng.AssertJUnit.assertEquals;

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.firefox.FirefoxDriver;

import org.testng.annotations.AfterClass;

(8)

import org.testng.annotations.BeforeClass;

import org.testng.annotations.Test;

public class Driver {

private WebDriver driver;

@BeforeClass

public void Startup(){

driver = new FirefoxDriver();

}

@Test (description="Google Login")

public void GoogleLogin() throws Exception{

driver.get("http://www.gmail.com");

assertEquals("Sign in", driver.findElement(By.id("signIn")).getAttribute("value"));

driver.findElement(By.id("Email")).sendKeys("*********");

driver.findElement(By.id("Passwd")).sendKeys("**********");

driver.findElement(By.id("signIn")).click();

Thread.sleep(10000);

driver.switchTo().frame("canvas_frame");

driver.findElement(By.id("gbgs4dn")).click();

driver.findElement(By.id("gb_71")).click();

driver.switchTo().defaultContent();

assertEquals("Sign in to Gmail", driver.findElement(By.id("button")).getText());

}

@AfterClass

public void teardown(){

driver.quit();

}

}

Selenium Web Driver Command List

Command Description

driver.get("http://www.google.com"); To open an application

driver.findElement(By.id("passwd-id")); Finding Element using Id

driver.findElement(By.name("passwd")); Finding Element using Name

driver.findElement(By.xpath("//input*@id=’passwd-id’+")); Finding Element using Xpath

element.sendKeys("some text"); To type some data

element.clear(); clear thecontents of a text field or textarea

driver.findElement(By.xpath("//select")); Selecting the value

select.findElements(By.tagName("option")); Selecting the value

select.deselectAll(); This will deselect all OPTIONs from the first SELECT on the page

select.selectByVisibleText("Edam"); select the OPTION withthe displayed text of “Edam”

findElement(By.id("submit")).click(); To click on Any button/Link

driver.switchTo().window("windowName"); Moving from one window to another window

driver.switchTo().frame("frameName"); swing from frame to frame (or into iframes)

driver.switchTo().frame("frameName.0.child"); to access subframes by separating the path with a dot, and you can specify the

frame by itsindex too.

driver.switchTo().alert(); Handling Alerts

driver.navigate().to("http://www.example.com"); To Navigate Paeticular URL

driver.navigate().forward(); To Navigate Forward

driver.navigate().back(); To Navigate Backword

driver.close() Closes the current window

driver.quit() Quits the driver and closes every associated window.

driver.switch_to_alert() Switches focus to an alert on the page.

driver.refresh() Refreshes the current page.

driver.implicitly_wait(30) Amount of time to wait

driver.set_script_timeout(30) The amount of time to wait

(9)

driver.get_screenshot_as_base64() Gets the screenshot of the current window as a base64 encoded string which is useful in

embedded images in HTML

using functions in xpath in selenium

How to use functions in xpath in selenium

Automation using selenium is a great experience. It provides many way to identify an object or element on the web page.

But sometime we face the problems of identifying the objects on a page which have same attributes. When we get more than

one element which are same in attribute and name like multiple check boxes with same name and same id. More than one

button having

same name and ids. There are no way to distinguishes those element. In this case we have problem to instruct selenium to

identify a particular object on a web page.

I am giving you a simple example . In the below html source there are 6 check boxes are there having same type and same

name.

It is really tough to select third or fifth.

input type='checkbox' name='chk' first

input type='checkbox' name='chk' second

input type='checkbox' name='chk' third

input type='checkbox' name='chk' forth

input type='checkbox' name='chk' fifth

input type='checkbox' name='chk' sixth

(10)

There are some functions we can use in Xpath to identify the object in above cases. An XPath expression can return one of four

basic XPath data types:

* String

* Number

* Boolean

* Node-set

XPath Type : Functions

Node set : last(), position(), count(), id(), local-name(), namespace-uri(), name()

String : string(), concat(), starts-with(), contains(), substring-before(), substring-after(), substring(), string-length(),

normalize-space(), translate()

Boolean : boolean(), not(), true(), false(), lang()

Number : number(), sum(), floor(), ceiling(), round()

I will show you how we can use some of these above functions in xpath to identify the objects.

Node Set : last()

In the above html file there are six check boxes and all are having same attributes (same type and name)

1. How we can select the last checkbox based on the position. We can use last() function to identify the last object among all

similar objects.

Below code will check or uncheck the last checkbox.

selenium.click("xpath=(//input[@type='checkbox'])[last()]");

2. How we can select the second last check box and third last check box. We can use last()- function to identify the last object

among all similar objects.

Below code will check or uncheck the second last checkbox and thrid last checkbox respectively.

selenium.click("xpath=(//input[@type='submit'])[last()-1]");

selenium.click("xpath=(//input[@type='submit'])[last()-2]");

Node Set : position()

If you want to select any object based on their position using xpath then you can use position() function in xpath.

You want to select second checkbox and forth checkbox then use below command

selenium.click("xpath=(//input[@type='checkbox'])[position()=2]");

selenium.click("xpath=(//input[@type='checkbox'])[position()=4]");

above code will select second and forth checkbox respectively.

String : starts-with()

Many web sites create dynamic element on their web pages where Ids of the elements gets generated dynamically.

Each time id gets generated differently. So to handle this situation we use some JavaScript functions.

XPath: //button[starts-with(@id, 'continue-')]

Sometimes an element gets identified by a value that could be surrounded by other text, then contains function can be used.

To demonstrate, the element can be located based on the ‘suggest’ class without having

to couple it with the ‘top’ and ‘business’ classes using the following

XPath: //input[contains(@class, 'suggest')].

(11)

TestNG– Dependency Test

The “Dependency Test” means methods are test base on dependency. If the dependent method fails, all the subsequent test

methods will be skipped, not marked as failed.

TestNG uses “dependOnMethods“ to implement the dependency testing as following

import org.testng.annotations.*;

/**

* TestNG Dependency Test

*

*

*/

public class TestNGTest7 {

@Test

public void method1() {

System.out.println("This is method 1");

}

@Test(dependsOnMethods={"method1"})

public void method2() {

System.out.println("This is method 2");

}

(12)

Result

PASSED: method1

PASSED: method2

The “method2()” will execute only if “method1()” is run successfully, else “method2()” will skip.

TestNG – Ignore Test

This “Ignored” means the method is not ready to test, the TestNG engine will just bypass this method.

import org.testng.annotations.*;

/**

* TestNG Ignore Test

*

*

*/

public class TestNGTest3 {

@Test(enabled=false)

public void divisionWithException() {

System.out.println("Method is not ready yet");

}

}

In above example, TestNG will not test the divisionWithException() method.

estNG – Suite Test

TESTNG – SUITE TEST

The “Suite Test” means bundle a few unit test cases and run it together.

In TestNG, XML file is use to define the suite test. The below XML file means both unit test “TestNGTest1” and “TestNGTest2”

will execute together.

<!DOCTYPE suite SYSTEM "http://beust.com/testng/testng-1.0.dtd" >

<suite name="My test suite">

<test name="testing">

<classes>

<class name="TestNGTest1" />

<class name="TestNGTest2" />

</classes>

</test>

(13)

</suite>

Beside classes bundle testing, TestNG provides a “Grouping” feature to bundle few methods as a single unit for testing, where

every method is tie to a group.

For example, Here’s a class with four methods, three groups (method1, method2 and method3)

import org.testng.annotations.*;

/*

*

* TestNG Grouping *

*

*/

public class TestNGTest5_2_0 {

@Test(groups="method1")

public void testingMethod1() {

System.out.println("Method - testingMethod1()");

}

@Test(groups="method2")

public void testingMethod2() {

System.out.println("Method - testingMethod2()");

}

@Test(groups="method1")

public void testingMethod1_1() {

System.out.println("Method - testingMethod1_1()");

}

@Test(groups="method4")

public void testingMethod4() {

System.out.println("Method - testingMethod4()");

}

}

You can execute the unit test with group “method1” only.

<!DOCTYPE suite SYSTEM "http://beust.com/testng/testng-1.0.dtd" >

<suite name="My test suite">

<test name="testing">

<groups>

<run>

<include name="method1"/>

</run>

</groups>

<classes>

<class name="TestNGTest5_2_0" />

</classes>

</test>

</suite>

(14)

Result:

Method - testingMethod1_1()

Method - testingMethod1()

TestNG Grouping is highly flexible and useful, especially when you implement it in your project integration testing.

Interview Questions

FEW INTERVIEW QUESTIONS FOR SELENIUM WEBDRIVER WITH JAVA

-What class should be extended to use Serialization?

-What is list and set?

-what is hash table?

-what is iterator?

-Tell me about binary search?

-Tell me about buble sort?

-What is Selenium IDE

-How can we do Iphone and Android app testing in selenium

-What technical issues did you face in selenium

-What is Selenium RC and WebDriver. What is the difference in them (2)

-How many ways can can start the selenium server (1)

-How will you convert integer to String and String to integer in Java (1)

-What do you mean by Object oriented programming. How is it used in selenium? (1)

-how do you download and install selenium? (1)

-Where do you write selenium code if you implement in java (1)

-What all languages are supported by selenium (1)

-What is Murex testing? Do we use Selenium to test Murex? (3)

-How to Integrate Jenkins Hudson integration with selenium for running the scripts in schdule time? (6)

-How to compare Text (not Html strings ) (2)

-How to open csv file (1)

-How to run webdriver scripts with different browsers

-How to do web service testing using selenium webdriver.

-How to identify webElement on web Page

-How to draw an annotation(s) on map using selenium webdriver?

-how to handle list(selecting more than one item) in Rc and Webdriver

-how to handle filedownload in ie and chrome

-How to handle silver light objects

-How to handles Popups!

-Interview Ques: How to extract data from webtable or weblist, store it in a file and sort the file

-Is there Assert.assertNotEquals() in webdriver ?

-Can we schedule the execution of test cases

-Do you any automation tool for desktop application testing?

-How to verify if the webElement is present or not on the webpage..??

-what are reflection api and how are they used in selenium ?

-How to schedule selenium suite using RC and WebDriver

-How to create a new file using Java

-How do you run your automated tests on Mutliple browsers

-How to handle certification error

(15)

-What is most difficult challenge you have faced in automating a web application

-How to execute selenium webdriver tests after completion and deployment of build thru Jenkins?

-Give two examples of functionality that cannot be properly tested with automated testing software?

--List the advantage/disadvantages: Selenium WebDriver Vs QTP

-What is inheritance in Java? How is it applied in Selenium?

-What are the drawbacks of Webdriver?

-Give me 5 points about what is the use of Framework (jUnit or TestNg)

-What is the difference between verify and Assert?

-How to run the test script in selenium on specific time?

-What to do at very first if you want to start a Selenium automation tool in your project?

-How do we keep expected result in the Seleniumj automation script?

-What is the use of Class HtmlUnitDriver and when we have to use the Class HtmlUnitDriver

-can we handle windows popup using selenium?

-There are 3 fields like House Number, Mobile Number and email address. How will you validate fields

-What is the difference between client-server application and web application?

-How can you test application in multiple browsers in selenium when making the framework

-How will you run 1000 test cases and generate reports

-What are user extensions

-What is difference between QTP and selenium

-What is the architecture of selenium WebDriver

Write results to excel sheet

Write results to excel sheet

After successfully executing scripts, every one want to write results to excel sheet..here is the way to write results to excel

sheet....

Below is the sample script to write results to excel sheet...

package test;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import jxl.Sheet;

import jxl.Workbook;

import jxl.write.Label;

import jxl.write.WritableSheet;

import jxl.write.WritableWorkbook;

import com.thoughtworks.selenium.*;

import org.openqa.selenium.server.*;

import org.testng.annotations.*;

public class Importexport1 {

public Selenium selenium;

public SeleniumServer seleniumserver;

@BeforeClass

public void setUp() throws Exception {

RemoteControlConfiguration rc = new RemoteControlConfiguration();

seleniumserver = new SeleniumServer(rc);

selenium = new DefaultSelenium("localhost", 4444, "*firefox", "http://");

seleniumserver.start();

selenium.start();

}

@Test

public void testImportexport1() throws Exception {

// Read data from excel sheet

FileInputStream fi = new FileInputStream(

"F:\\Framework\\testdata\\Login1_Credentials.xls");

Workbook w = Workbook.getWorkbook(fi);

(16)

String a[][] = new String[s.getRows()][s.getColumns()];

// Write the input data into another excel file

FileOutputStream fo = new FileOutputStream(

"F:\\Framework\\Results\\LoginResult1.xls");

WritableWorkbook wwb = Workbook.createWorkbook(fo);

WritableSheet ws = wwb.createSheet("loginresult1", 0);

selenium.open("http://www.gmail.com");

selenium.windowMaximize();

System.out.println("s.getRows() = " + s.getRows());

for (int i = 0; i < s.getRows(); i++) {

System.out.println("s.getColumns = " + s.getColumns());

for (int j = 0; j < s.getColumns(); j++) {

a[i][j] = s.getCell(j, i).getContents();

Label l = new Label(j, i, a[i][j]);

Label l1 = new Label(2, 0, "Result");

ws.addCell(l);

ws.addCell(l1);

}

}

for (int i = 1; i < s.getRows(); i++) {

selenium.type("Email", s.getCell(0, i).getContents());

selenium.type("Passwd", s.getCell(1, i).getContents());

selenium.click("signIn");

selenium.waitForPageToLoad("30000");

boolean aa = selenium.isTextPresent("The username or password you entered is incorrect. [?]");

System.out.println("the value of aa is::" + aa);

if (aa)

{

Label l3 = new Label(2, i, "fail");

ws.addCell(l3);

System.out.println("Login Failure");

Thread.sleep(10000);

} else {

Label l2 = new Label(2, i, "pass");

ws.addCell(l2);

selenium.click("link=Sign out");

Thread.sleep(10000);

}

}

wwb.write();

wwb.close();

}

@AfterClass

public void tearDown() throws Exception {

selenium.stop();

seleniumserver.stop();

}

}

(17)

Your out put excel should be like this

Write results to excel sheet

Write results to excel sheet

After successfully executing scripts, every one want to write results to excel sheet..here is the way to write results to excel

sheet....

Below is the sample script to write results to excel sheet...

package test;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import jxl.Sheet;

import jxl.Workbook;

import jxl.write.Label;

import jxl.write.WritableSheet;

import jxl.write.WritableWorkbook;

import com.thoughtworks.selenium.*;

import org.openqa.selenium.server.*;

import org.testng.annotations.*;

(18)

public class Importexport1 {

public Selenium selenium;

public SeleniumServer seleniumserver;

@BeforeClass

public void setUp() throws Exception {

RemoteControlConfiguration rc = new RemoteControlConfiguration();

seleniumserver = new SeleniumServer(rc);

selenium = new DefaultSelenium("localhost", 4444, "*firefox", "http://");

seleniumserver.start();

selenium.start();

}

@Test

public void testImportexport1() throws Exception {

// Read data from excel sheet

FileInputStream fi = new FileInputStream(

"F:\\Framework\\testdata\\Login1_Credentials.xls");

Workbook w = Workbook.getWorkbook(fi);

Sheet s = w.getSheet(0);

String a[][] = new String[s.getRows()][s.getColumns()];

// Write the input data into another excel file

FileOutputStream fo = new FileOutputStream(

"F:\\Framework\\Results\\LoginResult1.xls");

WritableWorkbook wwb = Workbook.createWorkbook(fo);

WritableSheet ws = wwb.createSheet("loginresult1", 0);

selenium.open("http://www.gmail.com");

selenium.windowMaximize();

System.out.println("s.getRows() = " + s.getRows());

for (int i = 0; i < s.getRows(); i++) {

System.out.println("s.getColumns = " + s.getColumns());

for (int j = 0; j < s.getColumns(); j++) {

a[i][j] = s.getCell(j, i).getContents();

Label l = new Label(j, i, a[i][j]);

Label l1 = new Label(2, 0, "Result");

ws.addCell(l);

ws.addCell(l1);

}

}

for (int i = 1; i < s.getRows(); i++) {

selenium.type("Email", s.getCell(0, i).getContents());

selenium.type("Passwd", s.getCell(1, i).getContents());

selenium.click("signIn");

selenium.waitForPageToLoad("30000");

boolean aa = selenium.isTextPresent("The username or password you entered is incorrect. [?]");

System.out.println("the value of aa is::" + aa);

if (aa)

{

Label l3 = new Label(2, i, "fail");

ws.addCell(l3);

System.out.println("Login Failure");

Thread.sleep(10000);

} else {

Label l2 = new Label(2, i, "pass");

ws.addCell(l2);

selenium.click("link=Sign out");

Thread.sleep(10000);

}

}

wwb.write();

(19)

wwb.close();

}

@AfterClass

public void tearDown() throws Exception {

selenium.stop();

seleniumserver.stop();

}

}

Your input data should be like this....

Your out put excel should be like this

Collection Java Programming Interview Questions 1

Collection API ?

Java Collections framework API is a unified architecture for representing and manipulating collections. All collections

frameworks contains interface, implementations and algorithms. Following are the benefits of collection framework.

• Reduces programming efforts. - Increases program speed and quality.

• Allows interoperability among unrelated APIs.

• Reduces effort to learn and to use new APIs.

• Reduces effort to design new APIs.

(20)

• Encourages & Fosters software reuse.

Collection contains six interfaces.

Set, List and SortedSet: extends collection interface

Map and SortedMap : don’t extend collection interface.a

What is HashMap and Map?

Maps stores key Value pair, and Hashmap is class that implements that using hashing technique.

Diff HashTable Vs HashMap Vs HashSet

Hashtable

Hashtable is basically a datastructure to retain values of key-value pair. Doesnot allow null for key and values

It is synchronized. So it comes with its cost. Only one thread can access in one time

Synchronized means only one thread can modify a hash table at one point of time. Any thread before performing an update on

a hashtable will have to acquire a lock on the object while others will wait for lock to be released.

Hashtable<Integer,String> rank= new Hashtable<Integer,String>();

rank.put(1,"A");

rank.put(1,"B");

rank.put(1,"C");

rank.put(null,"E"); NullPointerException at runtime

System.out.println(rank.get(1));

System.out.println(rank.get(2));

HashMap

Like Hashtable it also accepts key value pair.Allows null values

It is unsynchronized. So come up with better performance

By using following command Hashmap can be synchronized.

Map m = Collections.synchronizedMap(hashMap);

HashMap<Integer,String> Lang= new HashMap<Integer,String>();

Lang.put(1, "java");

Lang.put(2, null);

HashSet

HashSet does not allow duplicate values.

It can be used where you want to maintain a unique list. You also use its contain method to check whether the object is already

available in HashSet.

It provides add method rather put method.

HashSet<String> str= new HashSet<String>();

str.add ("Apple");

str.add ("Boy");

str.add ("Cat");

if (str.contains("Apple"))

Iterator and implementation

An iterator is an object that enables a programmer to traverse a collection.

Iterator iter = list.iterator();

while (iter.hasNext()) {

System.out.print(iter.next());

(21)

if (iter.hasNext())

System.out.print(", ");

}

Diff Iterator Vs ListIterator

Iterator : Enables you to traverse through a collection in the forward direction only, for obtaining or removing elements

ListIterator : extends Iterator, and allows bidirectional traversal of list and also allows the modification of elements.

Interface Implementation:

Implementations

Interface

Array

Balanced Tree Linked List Hash table

List

ArrayList

LinkedList

Map

TreeMap

HashMap

Set

TreeSet

HashSet

Deque

ArrayDeque

LinkedList

Collection interview Questions in Java 2

ArrayList vs LinkedList

Adding new elements is pretty fast for either type of list. For the ArrayList, doing random lookup using "get" is fast, but for

LinkedList, it's slow. It's slow because there's no efficient way to index into the middle of a linked list. When removing elements,

using ArrayList is slow. This is because all remaining elements in the underlying array of Object instances must be shifted down

for each remove operation. But here LinkedList is fast, because deletion can be done simply by changing a couple of links. So an

ArrayList works best for cases where you're doing random access on the list, and a LinkedList works better if you're doing a lot

of editing in the middle of the list.

Array vs ArrayList vs LinkedList vs Vector in java

Array vs ArrayList:

ArrayList is much better than Array, when the size need to be increased dynamically. Efficiency is possible with arrays. ArrayList

permits null elements.

ArrayList has group of objects. Array it treated as an object.

LinkedList vs Vector:

A vector is a growable array which can store many objects of different classes.

A linked list is a linear list where each item has a link to the next item in the list. It can be used to implement queue or stack

operations.

ArrayList vs LinkedList

Array list is better than linked list for accessing elements.Linked list is better than array list to perform insertion and deletion

operations at arbitrary locations.

Vector Vs ArrayList

Vector is synchronized whereas ArrayList is not. Even though Vector class is synchronized, still when you want programs to run

in multithreading environment using ArrayList with Collections.synchronizedList() is recommended over Vector.

ArrayList has no default size while vector has a default size of 10.

What is an enumeration?

An enumeration is an interface containing methods for accessing the underlying data structure from which the enumeration is

obtained. It is a construct which collection classes return when you request a collection of all the objects stored in the

collection. It allows sequential access to all the elements stored in the collection.

(22)

equals vs toString vs hashcod are methods in Object

Sort Diff b/w Arrays and Collections

Both use the same algorithm the only difference is type of input to them. Collections.sort() has a input as List so it does a

translation of List to array. So this should be used when you are trying to sort a list. Arrays.sort is for arrays so the sorting is

done directly on the array.

Printing the Fibonacci Series using Java

public class FibonaciN {

public static void main(String args[])

{

int prev, next, sum, n;

prev=next=1;

for(n=1;n<=9;n++)

{

System.out.println(prev);

sum=prev+next;

prev=next;

next=sum;

}

}

}

Basic String Operations in Java

public class StringOperations {

public static void main(String args[]){

String str1="Hello";

String str2="Ja va";

String str3="Hello";

// String Operations

System.out.println("String1 == String3"+ str1.equals(str3));

System.out.println("String2 at Index 2:"+str2.charAt(2));

System.out.println("Compare Str2 and Str3"+str2.compareTo(str3));

System.out.println("Compare str1 and str3"+str1.compareTo(str3));

System.out.println("String2 contains Ja: "+str2.contains("Ja"));

System.out.println("String is empty ?"+str1.isEmpty());

System.out.println("Sting HashCode"+ str1.hashCode());

System.out.println("Substring of String1"+str1.substring(2, 3));

System.out.println("Remove whitespaces in String2"+str2.trim());

System.out.println("Convert to LowerCase"+str2.toLowerCase());

System.out.println("Replace a with A"+str3.replace('a','A'));

}

}

OutPut:

========

String1 == String3true

String2 at Index 2:

Compare Str2 and Str32

Compare str1 and str30

String2 contains Ja: true

String is empty ?false

Sting HashCode69609650

(23)

Substring of String1l

Remove whitespaces in String2Ja va

Convert to LowerCaseja va

Replace a with AHello

Palindrome in Java for Integers and Strings

public class JavaPalindrome {

public static void main(String arg[]){

int num=121;

String str="teet teet";

System.out.println("Given Number"+num+"is Palindrome:"+intPalindrome(num));

System.out.println("Given String"+str+"is Palindrome:"+stringPalindrome(str));

System.out.println("String reverse using toChar Array");

System.out.println("Given String"+str+"is Palindrome:"+stringCharArrayPalindrome(str));

}

private static boolean stringCharArrayPalindrome(String str) {

String rev="";

char arr[]=str.toCharArray();

for(int i=arr.length-1;i>=0;i--)

rev=rev+arr[i];

if(str.equalsIgnoreCase(rev))

return true;

else

return false;

}

private static boolean stringPalindrome(String st) {

String str1[]=st.split("");

String revstr="";

for(int i=str1.length-1;i>=0;i--){

revstr+=str1[i];

}

if(st.equalsIgnoreCase(revstr))

return true;

else

return false;

}

// Checking Number Palindrome or not

private static boolean intPalindrome(int num) {

int n = num;

int rev = 0;

for (int i = 0; i <= num; i++)

{

int r = num % 10;

num = num / 10;

rev = rev * 10 + r;

i = 0;

}

if (n == rev) {

return true;

} else {

return false;

}

(24)

}/** Number palindrome */

}

Polymorphism in Java Using Overloading and Overridden methods

Polymorphism

One form and many implementations.

It can be acheived by using inheritence,overloading and Overriding.

Compile time Polymorphism: Over loading

Runtitme Polymorphism: Over riding

Runtime Polymorphism /Dynamic method dispatch:

Its a process in which a call to an overridden methodis resolved at runtime rather than compile itme.

Dynamic Binding: Refers to linking of a procedure call to the code to be executed in response to the call

Also known as late binding :Code associated to procedure call is not known untile the time of the call at runtime.

Overloading.

Two or more methods with same name in the same class with different arguments.

Overloaded methods Must change the argument list

May change the return type

May change the access modifiers.

May change the checded exceptions.

Example:

package com.oops;

public class OverLoadingExample {

public int sum(int a,int b){

System.out.println("Int Int");

return a+b;

}

public double sum(double a,double b){

System.out.println("Double Double");

return a+b;

}

public int sum(int a,double b){

System.out.println("Int Double");

return (int) (a+b);

}

public static void main(String args[]){

OverLoadingExample oe=new OverLoadingExample();

System.out.println("Overloading method"+oe.sum(3, 7));

System.out.println("Overloading method"+oe.sum(2.5, 5.7));

System.out.println("Overloading method"+oe.sum(2, 5.5));

}

}

Output:

=======

Int Int

Overloading method10

Double Double

Overloading method8.2

(25)

Int Double

Overloading method7

Overriding:

Occurs in the subclass and declares method that has same type arguments as a method and declared by one of its super class.

It can be used for defining the behaviour of child class.

Argument list same as overriden method.

Constructors canot be overridden.

final methods canot be overridden.

Static method cannot be overridden but can be re-declared.

super() can be used for invoking parent class(Super class) methods.

Example

package com.oops;

class OverExample{

public void fun1(){

System.out.println("Super Function1");

}

public void fun2(){

System.out.println("Super Using super() Function2");

}

}

public class OverRiddingExample extends OverExample{

public void fun1(){

System.out.println("Subclass Function1");

}

public void fun2(){

super.fun2();

System.out.println("Subclass Function2");

}

public static void main(String[] args) {

OverExample or=new OverRiddingExample();

OverExample oe=new OverExample();

or.fun1();

oe.fun1();

or.fun2();

}

}

Output:

========

Subclass Function1

Super Function1

(26)

Super Using super() Function2

Subclass Function2

Inheritance in Object Orient Programming and Java

Inheritance

Its a process where one object acquire properites another.

Inheritence reduces the code re-usablity.

Inheritence can be achieved by using extends or implemnts keyword

Single Inheritance:

Class A extends B{

statements

}

Example:

=============

Pulsar is subclass of Bike

TVS is subclass of Bike.

package com.oops;

class TwoWheeler{

int count=1;

public void setProp(){

System.out.println("Color: Red & Brand:Own");

}

}

public class SingleInheritence extends TwoWheeler {

public static void main(String args[]){

TwoWheeler two=new TwoWheeler();

SingleInheritence si=new SingleInheritence();

System.out.println(si instanceof TwoWheeler);

System.out.println("Calling method in SuperClass");

si.setProp();

}

}

Output

=======

true

Calling method in SuperClass

Color: Red & Brand:Own

Multiple Inheritance can be acheived by using interface.

Interface in Java Language (Click on link to know about interfaces)

Below example contains Single Inheritance and Multiple Inheritance Using Interfaces.

package com.oops;

(27)

int count=1;

public void setProp(){

System.out.println("Color: Red & Brand:Own");

}

}

interface Car

{

public void setBrandname(String name);

}

interface HeaveyVechile{

public void setProperites(String prop);

}

public class Wheeler extends TwoWheeler implements Car, HeaveyVechile{

public static void main(String args[]){

TwoWheeler two=new TwoWheeler();

Wheeler si=new Wheeler();

System.out.println(si instanceof TwoWheeler);

System.out.println("Calling method in SuperClass");

si.setProp();

si.setBrandname("First");

si.setProperites("HeavyLoadVechile");

}

@Override

public void setBrandname(String name) {

System.out.println("Brand name is"+name);

}

@Override

public void setProperites(String prop) {

System.out.println("Heavy Vechile with 4 or 8 Wheels "+prop);

}

}

Output

=========

true

Calling method in SuperClass

Color: Red & Brand:Own

Brand name isFirst

Heavy Vechile with 4 or 8 Wheels HeavyLoadVechile

interfaces in Object Oriented Programming Language

(28)

interface

==========

Descriptive set of methods. Implements class needs to be implemented methods in interface.

Properties of interface:

=========================

Canot mark interface as final

Cannot instiate interface.

Default: Methods in interface are abstract

fields in interface are static and final.

interface can implement class.

interface can extend multiple interfaces.

Class Implementing Interface

============================

package com.oops;

interface Bike{

//final static fields as default

int Capacity=150;

//abstract methods as default

public void speed();

public void price();

}

public class InterfaceExample implements Bike {

@Override

public void speed() {

System.out.println("Speed of Bike is 100 KMPH");

}

@Override

public void price() {

System.out.println("Price of Bike is 75K");

}

public static void main(String args[]){

InterfaceExample it=new InterfaceExample();

it.speed();

it.price();

}

}

Interface extends Multiple Interfaces

public interface Computer

{

public void setBrandname(String name);

}

(29)

{

public void setProperty(String prop);

public void viewProperty(String id);

}

public interface Laptop extends Computer

{

public void setProcess(double process);

public void setScreen(int size);

}

public interface Laptop extends Computer,Device{

statements

}

Encapsulation in Java Programming

Encapsulation: is like information Hiding.

Hiding the properites and behaviors of object and allowing outside access via public methods.

Example for Encapsulation:

============================

EmpDetails.java:

package com.oops;

public class EmpDetails {

private int empid;

private String empname;

public void setEmpid(int id){

empid=id;

}

public int getEmpid(){

return empid;

}

public void setEmpName(String name){

empname=name;

}

public String getEmpName(){

return empname;

}

}

EncapsulationExample.java

package com.oops;

public class EncapsulationExample {

/**

* @param args

*/

(30)

EmpDetails emp1=new EmpDetails();

emp1.setEmpid(1);

emp1.setEmpName("First");

System.out.println("Employee details id: "+emp1.getEmpid()+" and name:"+emp1.getEmpName());

}

}

Output

==========

Employee details id: 1 and name:First

Java Exception Handling Programming Questions

Q) What are the two types of Exceptions?

A)Checked Exceptions and Unchecked Exceptions.

Q) What is the base class of all exceptions?

A) java.lang.Throwable

Q)If the overridden method in super class A throws FileNotFoundException, then the overriding method present in class B

which is a subclass of class A can throw IOException. If the above statement true?

A) The overriding method can not throw any checked exception other than the exception classes or sub-classes of those

classes which are thrown by the overridden method.

In the scenario described in question, the method in class B can not throw IOException but can throw FileNotFoundException

exception.

Q)Can we have a try block without a catch block?

public class JExample {

public static void main(String args[]){

int i=0;

int j=4;

try

{

int k=j/i;

}

finally{

System.out.println("finally");

}

}

}

Output:

=======

finally

Exception in thread "main" java.lang.ArithmeticException: / by zero

at com.test.JExample.main(JExample.java:11)

Q) What is the difference between checked and unchecked exception handling in Java? What are the disadvantages of

checked exception handling?

A) Checked exceptions are the one for which there is a check by the compiler that these exceptions have to be caught or

specified with throws keyword. These kind of exceptions occur because of conditions which are out of control of the

application like Network error, File Access Denied etc.

(31)

element which doesn’t exist.

Q)Explain try,catch and finally statements in Java ?

The try/catch statement encloses some code and is used to handle errors and exceptions that might occur in that code.

try {

} catch (Exception e) {

}finally{

}

Example

======

public class JExample {

public static void main(String args[]){

int i=0;

int j=4;

try

{

int k=j/i;

}catch(Exception e)

{

System.out.println("Exception caught");

e.printStackTrace();

}

finally{

System.out.println("finally");

}

}

}

Output:

======

Exception caught

java.lang.ArithmeticException: / by zero

at com.test.JExample.main(JExample.java:11)

finally

Q) If there is common code to be executed in the catch block of 10 exceptions which are thrown from a single try block, then

how that common code can be written with minimum effort?

A) In pre JDK 7, a method can be written and all catch blocks can invoke this method containing the common code.

In JDK 7, the | operator can be used in catch block in order to execute common code for multiple exceptions. e.g.

catch(SQLException sqle | IOException ioe){}

4) Have you every created custom exceptions? Explain the scenario?

Ans: Custom exceptions are useful when the JDK exception classes don’t capture the essence of erroneous situation which

has come up in the application. A custom exception can be created by extending any subclass of Exception class or by

implementing Throwable interface.

Q) What is the difference between Validation, Exception and Error?

A)Validation is the process of making user enter data in a format which the application can handle.

Exception handling is the process when the application logic didn’t work as expected by the Java compiler.

Error occurs in a situation where the normal application execution can not continue. For e.g. out of memory.

(32)

Q) What is the purpose of finally block? In which scenario, the code in finally block will not be executed?

A) finally block is used to execute code which should be executed irrespective of whether an exception occurs or not. The

kind of code written in a finally block consists of clean up code such as closing of database/file connection.

But JDK 7 has come up with try with resources block which automatically handles the closing of resources.

Q) Can a finally block exist with a try block but without a catch?

A)Yes. The following are the combinations try/catch or try/catch/finally or try/finally.

Q) What is the difference between throw and throws?

Throw is used to explicitly raise a exception within the program, the statement would be throw new Exception(); throws

clause is used to indicate the exceptions that are not handled by the method. It must specify this behavior so the callers of

the method can guard against the exceptions.

Throws is specified in the method signature. If multiple exceptions are not handled, then they are separated by a comma.

the statement would be as follows: public void doSomething() throws IOException,MyException{}

Q) How to create Custom Exception in Java?

package com.test;

//NullException is the user exception defined

class NullException extends Exception{

int a;

public NullException(int i) {

i=a;

}

public String toString(){

return "Created NullException:"+a;

}

}

public class CustomException

{

public static void Divide(int a,int b) throws NullException{

int k=a/b;

throw new NullException(k);

}

public static void main(String args[]){

try{

CustomException c=new CustomException();

c.Divide(5, 2);

}catch(Exception e){

System.out.println("Main CustomExceptionm:" +e);

}finally{

System.out.println("Finally Exceuting");

}

}

}

Output

=========

(33)

Finally Exceuting

Q) What are the differences between NoClassDefFoundError and ClassNotFoundException?

A) NoClassDefFoundError occurs when a class was found during compilation but could not be located in the classpath while

executing the program.

For example: class A invokes method from class B and both compile fine but before executing the program, an ANT script

deleted B.class by mistake. Now on executing the program NoClassDefFoundError is thrown.

ClassNotFoundException occurs when a class is not found while dynamically loading a class using the class loaders.

For example: The database driver is not found when trying to load the driver using Class.forName() method.

Q) Can a catch block exist without a try block?

A)No. A catch block should always go with a try block.

Q) What will happen to the Exception object after exception handling?

A)Exception object will be garbage collected.

Q)How does finally block differ from finalize() metho

Finally block will be executed whether or not an exception is thrown. So it is used to free resoources. finalize() is a protected

method in the Object class which is called by the JVM just before an object is garbage collected.

Q) What is the purpose of throw keyword? What happens if we write “throw null;” statement in a Java program?

A) ”throw” keyword is used to re-throw an exception which has been caught in a catch block. The syntax is “throw e;” where

e is the reference to the exception being caught. The exception is re-thrown to the client.

This keyword is useful when some part of the exception is to be handled by the caller of the method in which throw keyword

is used.

The use of “throw null;” statement causes NullPointerException to be thrown.

Q) return statement in try,catch and finally ?

public

class ExceptionDemo {

public int chkException(int arr[]){

int k=0;

int t=1,c=2,f=3;

try

{

for(k=0;k<5;k++)

System.out.println("arr Element"+arr[k]);

System.out.println("Try Catch");

return t;

}catch(Exception e){

System.out.println("Failed on exception"+e.getMessage());

System.out.println("Catch Retrun");

return c;

}finally{

System.out.println("Finally Return");

return f;

}

}

public static void main(String args[]){

int arr[]={1,4,5};

ExceptionDemo e=new ExceptionDemo();

e.chkException(arr);

References

Related documents