SlideShare a Scribd company logo
1 of 11
http://testingtoolstecniques.blogspot.com/
http://testingtoolstecniques.blogspot.com/
Writing your first MYSQL DB functional Test Case in J unit
In junit you can write test cases for any SQL Queries here I am using MYSQL however if you want to
perform this on some other D.B you will just have to change connection configurations according to that
D.B.
You need to download MY SQL Connector for java and import that in your project.
Steps:
Creating Connection Class
First Step is to create a connection class with data base here I am following singleton pattern for
creating connection with D.B
Example Code is :
import com.mysql.*;
import com.mysql.jdbc.Connection;
public class dbConnectionInstance {
public static Connection conn;
static String url= "jdbc:mysql://localhost:3306/";
static String dbName = "test_data_eoffice";
static String driver = "com.mysql.jdbc.Driver";
static String userName = "root";
static String password = "";
dbConnectionInstance()
{}
public static Connection MysqlConnect() {
if ( conn == null ) {
try {
Class.forName(driver).newInstance();
conn =
(Connection)DriverManager.getConnection(url+dbName,userName,password);
}
catch (Exception sqle) {
sqle.printStackTrace();
}
return conn;
}
else
return conn;
}
}
http://testingtoolstecniques.blogspot.com/
http://testingtoolstecniques.blogspot.com/
Benefit of using singleton pattern is that you won’t need to created create a
connection object ever time you will simply call this instance by
dbConnectionInstance. MysqlConnect(); and this method will return you connection.
Creating Functionalities Class
This class will contain execution of all queries which we want to test
First step is to create this class and identify a query here I am writing a test case for query “insert into
testdatacreatefile”
I created a function public void createFileTestDataGenarator()
Then I executed this query with in this function
Now my test functionality is ready to be called in a J-Unit Test case
Example code is :
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
public class TestDataGenerator {
private Connection connect = dbConnectionInstance.MysqlConnect();
private Statement statement = null;
public void createFileTestDataGenarator()
{
try {
statement=connect.createStatement();
for(int i=1000; i<=2000; i++)
{ String fileRefNum="Test FIle Reference Number"+i;
String Subject="Test FIle Subject Number"+i;
String Keywords ="keyword"+i+"A,keyword"+i+"B";
String Decscription="Test FIle Description Number"+i;
int status=0;
statement.executeUpdate("insert into
testdatacreatefile(fileSubject,fileReferenceNumber,fileKeyword,fileDescription,testDa
taStatus) values
('"+Subject+"','"+fileRefNum+"','"+Keywords+"','"+Decscription+"',"+status+")");
}} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}}
public void Log(String log)
{
http://testingtoolstecniques.blogspot.com/
http://testingtoolstecniques.blogspot.com/
try {
statement=connect.createStatement();
statement.executeUpdate("insert into logger(step)
values ('"+log+"')");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void createDocumentTestDataGenarator()
{
try {
statement=connect.createStatement();
for(int i=1000; i<=2000; i++)
{
String DocumentRefNum="Test Document Reference Number"+i;
String Subject="Test Doucument subject "+i;
String Decscription="Test Document Description"+i;
String FromMinsitry="Some Test Mionistry"+i;
String FromDesigntation="Some Test Mionistry Designation
ABC"+i;
String FromName="Some Test Misnitry Named ABC:GM"+i;
String FromMedium="Some Test Courior Service"+i;
int status=0;
statement.executeUpdate("insert into
testdatacreatedocument(
DocumentRef,DocumentDesc,FromMinistry,FromDesignation,FromName,FromMedium,Stat
us) values
('"+DocumentRefNum+"','"+Decscription+"','"+FromMinsitry+"','"+FromDesigntation+"','"
+FromName+"','"+FromMedium+"',"+status+")");
}} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}}
}
http://testingtoolstecniques.blogspot.com/
http://testingtoolstecniques.blogspot.com/
Creating J unit Class
Left Click your project and add a J Unit Test Case
There are three basic attenuation is Junit
@Before: this attenuation is used for initialization
@ Test: with this attenuation you call your actual test or execute with in this
attenuation
@ After: this attenuation is used at the end of test e.g for closing all DB
connections
Next step is now to call you created functionality in @ test Attenuation
Create Object of that class and then call its instance like example below
@Test
public void testCreateFIle() throws Exception {
TestDataGenerator TDG= new TestDataGenarator();
TDG.createDocumentTestDataGenarator();
//FM.addNtoing("fazal.karim", baseUrl, driver, "Abdul Hafeez", "KPO",
"abdul.hafeeez");
// Thread.sleep(5000L);
http://testingtoolstecniques.blogspot.com/
http://testingtoolstecniques.blogspot.com/
}
At Last execute your Junit Class as a Junit project not as a Java Application
For knowing more about MY SQL and java refer following links
http://www.tutorialspoint.com/jdbc/
Writing your first Selenium Web Driver functional Test Case in J unit
First of all I scripts all functionalities in a web app in a separate class and I create a separate function for
every functionality like signin(string username, string password). Then I call these functions in sequence
in my Junit Test case
e.g you class contain 3 function sign in (), Register() , View Category(), clickProduct(), addToCart
Now in your junit test case if you need add to cart you need following steps
1. Sign in User by calling signin()
2. Open a category by calling View Category()
3. Click some product by calling clickProduct(),
4. Add product to cart by calling addToCart()
I this approach e.g you need a test case view product or just sign in you don’t need to rewrite test script
you will simply rearrange test steps
Example code is mentioned below: In this code I created a separate function for every functionality and
we can call this functionality a test step benefit of this approach is reusability but in this approach you
have to keep it in mind that every possible parameter must be kept dynamic
import java.awt.AWTException;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.*;
import org.openqa.selenium.support.ui.Select;
public class FileManagment {
loginManager LM= new loginManager();
TestDataGenerator TDG=new TestDataGenerator();
testDataProvider TP=new testDataProvider();
String subject;
String FileRefNumber;
String Description;
String Keywords;
String fileName;
// private StringBuffer verificationErrors = new StringBuffer();
public void createDocument(WebDriver wd, String uID, String baseUrl) throws
ClassNotFoundException, InterruptedException
http://testingtoolstecniques.blogspot.com/
http://testingtoolstecniques.blogspot.com/
{ LM.loginAsAppUser(uID, baseUrl, wd);
List<String> list= new ArrayList<String>();
testDataProvider TDP=new testDataProvider();
list=TDP.getCreateDocumentData();
String DocRef=list.get(0);
String DocumentDesc=list.get(1);
wd.get(baseUrl+"faces/ic/AddDocument.jsp?init=true");
wd.findElement(By.id("form1:referenceNo")).sendKeys(DocRef);
wd.findElement(By.id("form1:subject")).click();
wd.findElement(By.id("form1:subject")).clear();
wd.findElement(By.id("form1:subject")).sendKeys(DocRef);
wd.findElement(By.xpath("//html/body")).click();
wd.switchTo().frame("content_ifr");
wd.findElement(By.id("mce_editor_0")).sendKeys(DocumentDesc);
wd.switchTo().defaultContent();
new Select(wd.findElement(By.id("fform1:template"))).selectByIndex(2);
wd.findElement(By.id("form1:button")).click();
//wd.findElement(By.id("form1:hiddenBtn")).click();
}
public void CreateFile(String uID,String baseUrl,WebDriver browser) throws
AWTException
{
try{
List<String> list= new ArrayList<String>();
list=TP.getCreateFileData();
subject=list.get(0);
FileRefNumber=list.get(1);
Description=list.get(3);
Keywords=list.get(2);
WebDriver driver;
driver=browser;
//Step 1 login
LM.loginAsAppUser(uID, baseUrl, driver);
//Step 2 Create File
driver.get(baseUrl+"faces/ic/CreateFile.jsp?isNewFile=true");
// ERROR: Caught exception [ERROR: Unsupported command [selectWindow | null | ]]
new
Select(driver.findElement(By.id("form1:cboFileHeading"))).selectByIndex(1);;
new Select(driver.findElement(By.id("form1:cboFileTypes"))).selectByIndex(1);;
driver.findElement(By.id("form1:txtSubject")).clear();
driver.findElement(By.id("form1:txtSubject")).sendKeys(subject);
driver.findElement(By.id("form1:txtParaNumber")).clear();
driver.findElement(By.id("form1:txtParaNumber")).sendKeys("1");
driver.findElement(By.id("form1:Description")).clear();
driver.findElement(By.id("form1:Description")).sendKeys(Description);
driver.findElement(By.id("form1:Keywords")).clear();
driver.findElement(By.id("form1:Keywords")).sendKeys(Keywords);
driver.findElement(By.id("form1:btnSave")).click();
//driver.findElement(By.id("form1:hiddenBtn")).click();
http://testingtoolstecniques.blogspot.com/
http://testingtoolstecniques.blogspot.com/
//driver.findElement(By.xpath("/html/body/form/table/tbody/tr[2]/td/table/tbody/tr/td
[2]/table/tbody/tr/td/table/tbody/tr/td/span"));
System.out.print("n"+uID+": Sucessfully Created File");
Thread.sleep(10000L);
}
catch (NoSuchElementException e) {
e.printStackTrace();
}
catch (InterruptedException e) {
}
catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void openTopMostFileOnDesk(String uID,String baseUrl,WebDriver browser)
{
try {
LM.loginAsAppUser(uID, baseUrl, browser);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
fileName=browser.findElement(By.xpath("/html/body/form/table/tbody/tr[2]/td/table/tbo
dy/tr[2]/td/table/tbody/tr/td[2]/table/tbody/tr/td/table/tbody/tr[2]/td/table/tbody/t
r[2]/td/a")).getText();
System.out.print("n"+fileName);
buttonController.clickButtonByXPath(browser,
"/html/body/form/table/tbody/tr[2]/td/table/tbody/tr[2]/td/table/tbody/tr/td[2]/table
/tbody/tr/td/table/tbody/tr[2]/td/table/tbody/tr[2]/td/a");
System.out.print("n"+uID+": Sucessfully Opened File");
((JavascriptExecutor)browser).executeScript("document.location.reload()");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void openNotingTabtopMostFile(String uID,String baseUrl,WebDriver
browser)
{
openTopMostFileOnDesk(uID, baseUrl, browser);
browser.findElement(By.id("form1:text13")).click();
System.out.print("n"+uID+": Sucessfully Opened Noting Tab");
http://testingtoolstecniques.blogspot.com/
http://testingtoolstecniques.blogspot.com/
((JavascriptExecutor)browser).executeScript("document.location.reload()");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void verifyNoting(String uID,String baseUrl,WebDriver browser, String
FileName)
{
try {
LM.loginAsAppUser(uID, baseUrl, browser);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
browser.getPageSource().contains(FileName);
System.out.print("n"+uID+": recived file Sucessfully ");
}
public void addNtoing(String uID,String baseUrl,WebDriver browser, String
reciverName, String reciverDesignation, String reciverID) throws InterruptedException
{
openNotingTabtopMostFile(uID, baseUrl, browser);
JavascriptExecutor jsx = (JavascriptExecutor)browser;
jsx.executeScript("window.scrollBy(0,600)", "");
browser.switchTo().frame("mce_editor_0");
browser.findElement(By.cssSelector("body")).sendKeys("heloo Fahad
Testing here");
browser.switchTo().window(browser.getWindowHandle());
Thread.sleep(100L);
browser.findElement(By.xpath("/html/body/form[2]/table/tbody/tr[2]/td/table/tb
ody/tr/td[2]/table/tbody/tr/td/table/tbody/tr[3]/td/table/tbody/tr[20]/td/a"));
Thread.sleep(500L);
Select select=new Select(browser.findElement(By.id("form1:markTo")));
select.selectByVisibleText(reciverName+", "+reciverDesignation);
browser.findElement(By.xpath("//*[@id="form1:fwdButton"]")).click();
Alert alert = browser.switchTo().alert();
alert.accept();
try {
Thread.sleep(10000L);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
assertEquals("Internal Communication", browser.getTitle());
System.out.print("n"+uID+": sucessfully added noting and marked File to
"+reciverName+" Whose designation is "+reciverDesignation);
http://testingtoolstecniques.blogspot.com/
http://testingtoolstecniques.blogspot.com/
verifyNoting(reciverID,baseUrl, browser,fileName);
}
}
Now Add a Junit Test Case
Left Click your project and add a J Unit Test Case
There are three basic attenuation is Junit
@Before: this attenuation is used for initialization
@ Test: with this attenuation you call your actual test or execute with in this
attenuation
@ After: this attenuation is used at the end of test e.g for closing all DB
connections
Next step is now to call you created functionality in @ test Attenuation
Now call your web driver script with in @test
http://testingtoolstecniques.blogspot.com/
http://testingtoolstecniques.blogspot.com/
import static org.junit.Assert.fail;
import java.util.concurrent.TimeUnit;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.NoAlertPresentException;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
public class mainTestClass {
private WebDriver driver;
private String baseUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
FileManagment FM= new FileManagment();
@Before
public void setUp() throws Exception {
System.setProperty("webdriver.chrome.driver","chromedriver.exe");
// System.setProperty("webdriver.ie.driver", "IEDriverServer.exe");
// driver = new InternetExplorerDriver();
Thread.sleep(2000L);
driver = new FirefoxDriver();
Thread.sleep(2000L);
baseUrl = "http://10.11.11.80:8080/EOffice/";
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
}
@Test
public void testCreateFIle() throws Exception {
FM.createDocument();
FM.addNtoing("fazal.karim", baseUrl, driver, "Abdul Hafeez", "KPO",
"abdul.hafeeez");
}
@After
public void tearDown() throws Exception {
driver.quit();
System.out.print("Driver Closed Sucessfull");
http://testingtoolstecniques.blogspot.com/
http://testingtoolstecniques.blogspot.com/
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
private boolean isElementPresent(By by) {
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
private boolean isAlertPresent() {
try {
driver.switchTo().alert();
return true;
} catch (NoAlertPresentException e) {
return false;
}
}
private String closeAlertAndGetItsText() {
try {
Alert alert = driver.switchTo().alert();
String alertText = alert.getText();
if (acceptNextAlert) {
alert.accept();
} else {
alert.dismiss();
}
return alertText;
} finally {
acceptNextAlert = true;
}
}
}
In @before I created all objects which were required by script to execute
In @ after I teared down Web driver and MY SQL connection
For knowing more about JUNIT refer following links
http://www.tutorialspoint.com/junit/junit_using_assertion.html
http://www.vogella.com/tutorials/JUnit/article.html

More Related Content

What's hot

Net Beans Codes for Student Portal
Net Beans Codes for Student PortalNet Beans Codes for Student Portal
Net Beans Codes for Student PortalPeeyush Ranjan
 
JSRs 303 and 330 in Action
JSRs 303 and 330 in ActionJSRs 303 and 330 in Action
JSRs 303 and 330 in Actionsimonetripodi
 
Testing for Pragmatic People
Testing for Pragmatic PeopleTesting for Pragmatic People
Testing for Pragmatic Peopledavismr
 
Mastering Mock Objects - Advanced Unit Testing for Java
Mastering Mock Objects - Advanced Unit Testing for JavaMastering Mock Objects - Advanced Unit Testing for Java
Mastering Mock Objects - Advanced Unit Testing for JavaDenilson Nastacio
 
Unit testing with Easymock
Unit testing with EasymockUnit testing with Easymock
Unit testing with EasymockÜrgo Ringo
 
Unit Testing on Android - Droidcon Berlin 2015
Unit Testing on Android - Droidcon Berlin 2015Unit Testing on Android - Droidcon Berlin 2015
Unit Testing on Android - Droidcon Berlin 2015Buşra Deniz, CSM
 
Padroes Projeto
Padroes ProjetoPadroes Projeto
Padroes Projetolcbj
 
Advanced java practical semester 6_computer science
Advanced java practical semester 6_computer scienceAdvanced java practical semester 6_computer science
Advanced java practical semester 6_computer scienceNiraj Bharambe
 
Pragmatic unittestingwithj unit
Pragmatic unittestingwithj unitPragmatic unittestingwithj unit
Pragmatic unittestingwithj unitliminescence
 
Android ui layouts ,cntls,webservices examples codes
Android ui layouts ,cntls,webservices examples codesAndroid ui layouts ,cntls,webservices examples codes
Android ui layouts ,cntls,webservices examples codesAravindharamanan S
 
Diving into VS 2015 Day5
Diving into VS 2015 Day5Diving into VS 2015 Day5
Diving into VS 2015 Day5Akhil Mittal
 
Introduction to Active Record at MySQL Conference 2007
Introduction to Active Record at MySQL Conference 2007Introduction to Active Record at MySQL Conference 2007
Introduction to Active Record at MySQL Conference 2007Rabble .
 
Selenium Webdriver with data driven framework
Selenium Webdriver with data driven frameworkSelenium Webdriver with data driven framework
Selenium Webdriver with data driven frameworkDavid Rajah Selvaraj
 
Дмитрий Контрерас «Back to the future: the evolution of the Java Type System»
Дмитрий Контрерас «Back to the future: the evolution of the Java Type System»Дмитрий Контрерас «Back to the future: the evolution of the Java Type System»
Дмитрий Контрерас «Back to the future: the evolution of the Java Type System»Anna Shymchenko
 
Understanding JavaScript Testing
Understanding JavaScript TestingUnderstanding JavaScript Testing
Understanding JavaScript Testingjeresig
 

What's hot (20)

Net Beans Codes for Student Portal
Net Beans Codes for Student PortalNet Beans Codes for Student Portal
Net Beans Codes for Student Portal
 
JSRs 303 and 330 in Action
JSRs 303 and 330 in ActionJSRs 303 and 330 in Action
JSRs 303 and 330 in Action
 
Testing for Pragmatic People
Testing for Pragmatic PeopleTesting for Pragmatic People
Testing for Pragmatic People
 
Mastering Mock Objects - Advanced Unit Testing for Java
Mastering Mock Objects - Advanced Unit Testing for JavaMastering Mock Objects - Advanced Unit Testing for Java
Mastering Mock Objects - Advanced Unit Testing for Java
 
Unit testing with Easymock
Unit testing with EasymockUnit testing with Easymock
Unit testing with Easymock
 
Unit Testing on Android - Droidcon Berlin 2015
Unit Testing on Android - Droidcon Berlin 2015Unit Testing on Android - Droidcon Berlin 2015
Unit Testing on Android - Droidcon Berlin 2015
 
Jsr 303
Jsr 303Jsr 303
Jsr 303
 
Devoxx 2012 (v2)
Devoxx 2012 (v2)Devoxx 2012 (v2)
Devoxx 2012 (v2)
 
Clean Test Code
Clean Test CodeClean Test Code
Clean Test Code
 
Padroes Projeto
Padroes ProjetoPadroes Projeto
Padroes Projeto
 
Auto testing!
Auto testing!Auto testing!
Auto testing!
 
Advanced java practical semester 6_computer science
Advanced java practical semester 6_computer scienceAdvanced java practical semester 6_computer science
Advanced java practical semester 6_computer science
 
Pragmatic unittestingwithj unit
Pragmatic unittestingwithj unitPragmatic unittestingwithj unit
Pragmatic unittestingwithj unit
 
Android ui layouts ,cntls,webservices examples codes
Android ui layouts ,cntls,webservices examples codesAndroid ui layouts ,cntls,webservices examples codes
Android ui layouts ,cntls,webservices examples codes
 
Diving into VS 2015 Day5
Diving into VS 2015 Day5Diving into VS 2015 Day5
Diving into VS 2015 Day5
 
Introduction to Active Record at MySQL Conference 2007
Introduction to Active Record at MySQL Conference 2007Introduction to Active Record at MySQL Conference 2007
Introduction to Active Record at MySQL Conference 2007
 
Qtp test
Qtp testQtp test
Qtp test
 
Selenium Webdriver with data driven framework
Selenium Webdriver with data driven frameworkSelenium Webdriver with data driven framework
Selenium Webdriver with data driven framework
 
Дмитрий Контрерас «Back to the future: the evolution of the Java Type System»
Дмитрий Контрерас «Back to the future: the evolution of the Java Type System»Дмитрий Контрерас «Back to the future: the evolution of the Java Type System»
Дмитрий Контрерас «Back to the future: the evolution of the Java Type System»
 
Understanding JavaScript Testing
Understanding JavaScript TestingUnderstanding JavaScript Testing
Understanding JavaScript Testing
 

Viewers also liked

Automation testing & Unit testing
Automation testing & Unit testingAutomation testing & Unit testing
Automation testing & Unit testingKapil Rajpurohit
 
Advanced junit and mockito
Advanced junit and mockitoAdvanced junit and mockito
Advanced junit and mockitoMathieu Carbou
 
Spock Testing Framework - The Next Generation
Spock Testing Framework - The Next GenerationSpock Testing Framework - The Next Generation
Spock Testing Framework - The Next GenerationBTI360
 
Build, logging, and unit test tools
Build, logging, and unit test toolsBuild, logging, and unit test tools
Build, logging, and unit test toolsAllan Huang
 
Performance Testing Java Applications
Performance Testing Java ApplicationsPerformance Testing Java Applications
Performance Testing Java ApplicationsC4Media
 
Mocking in Java with Mockito
Mocking in Java with MockitoMocking in Java with Mockito
Mocking in Java with MockitoRichard Paul
 

Viewers also liked (11)

TestNG vs. JUnit4
TestNG vs. JUnit4TestNG vs. JUnit4
TestNG vs. JUnit4
 
Automation testing & Unit testing
Automation testing & Unit testingAutomation testing & Unit testing
Automation testing & Unit testing
 
TestNGvsJUnit
TestNGvsJUnitTestNGvsJUnit
TestNGvsJUnit
 
Advanced junit and mockito
Advanced junit and mockitoAdvanced junit and mockito
Advanced junit and mockito
 
Spock Testing Framework - The Next Generation
Spock Testing Framework - The Next GenerationSpock Testing Framework - The Next Generation
Spock Testing Framework - The Next Generation
 
Build, logging, and unit test tools
Build, logging, and unit test toolsBuild, logging, and unit test tools
Build, logging, and unit test tools
 
Java 8 Features
Java 8 FeaturesJava 8 Features
Java 8 Features
 
Performance Testing Java Applications
Performance Testing Java ApplicationsPerformance Testing Java Applications
Performance Testing Java Applications
 
Mocking in Java with Mockito
Mocking in Java with MockitoMocking in Java with Mockito
Mocking in Java with Mockito
 
JUnit Presentation
JUnit PresentationJUnit Presentation
JUnit Presentation
 
Testing In Java
Testing In JavaTesting In Java
Testing In Java
 

Similar to Selenium my sql and junit user guide

比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotationjavatwo2011
 
Apex Testing and Best Practices
Apex Testing and Best PracticesApex Testing and Best Practices
Apex Testing and Best PracticesJitendra Zaa
 
Qtp 92 Tutorial769
Qtp 92 Tutorial769Qtp 92 Tutorial769
Qtp 92 Tutorial769subhasis100
 
qtp 9.2 features
qtp 9.2 featuresqtp 9.2 features
qtp 9.2 featureskrishna3032
 
Qtp 92 Tutorial
Qtp 92 TutorialQtp 92 Tutorial
Qtp 92 Tutorialsasidhar
 
Qtp 92 Tutorial769
Qtp 92 Tutorial769Qtp 92 Tutorial769
Qtp 92 Tutorial769subhasis100
 
Qtp 92 Tutorial Anil
Qtp 92 Tutorial AnilQtp 92 Tutorial Anil
Qtp 92 Tutorial Anilguest3373d3
 
Qtp 9.2 Tutorial
Qtp 9.2 TutorialQtp 9.2 Tutorial
Qtp 9.2 Tutorialguest37ae7f
 
Pruebas unitarias con django
Pruebas unitarias con djangoPruebas unitarias con django
Pruebas unitarias con djangoTomás Henríquez
 
Code Kata: String Calculator in Flex
Code Kata: String Calculator in FlexCode Kata: String Calculator in Flex
Code Kata: String Calculator in FlexChris Farrell
 
Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014
Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014
Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014First Tuesday Bergen
 
Java database connecticity steps
Java database connecticity stepsJava database connecticity steps
Java database connecticity stepsSKMohamedKasim
 
.NET Portfolio
.NET Portfolio.NET Portfolio
.NET Portfoliomwillmer
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to javaciklum_ods
 
stateDatabuild.xml Builds, tests, and runs the project.docx
stateDatabuild.xml      Builds, tests, and runs the project.docxstateDatabuild.xml      Builds, tests, and runs the project.docx
stateDatabuild.xml Builds, tests, and runs the project.docxwhitneyleman54422
 

Similar to Selenium my sql and junit user guide (20)

Android sql examples
Android sql examplesAndroid sql examples
Android sql examples
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotation
 
Apex Testing and Best Practices
Apex Testing and Best PracticesApex Testing and Best Practices
Apex Testing and Best Practices
 
Qtp 92 Tutorial769
Qtp 92 Tutorial769Qtp 92 Tutorial769
Qtp 92 Tutorial769
 
qtp 9.2 features
qtp 9.2 featuresqtp 9.2 features
qtp 9.2 features
 
Qtp 92 Tutorial
Qtp 92 TutorialQtp 92 Tutorial
Qtp 92 Tutorial
 
Ppt Qtp
Ppt QtpPpt Qtp
Ppt Qtp
 
Qtp 92 Tutorial769
Qtp 92 Tutorial769Qtp 92 Tutorial769
Qtp 92 Tutorial769
 
Qtp 92 Tutorial Anil
Qtp 92 Tutorial AnilQtp 92 Tutorial Anil
Qtp 92 Tutorial Anil
 
Qtp 9.2 Tutorial
Qtp 9.2 TutorialQtp 9.2 Tutorial
Qtp 9.2 Tutorial
 
Qtp 92 Tutorial769
Qtp 92 Tutorial769Qtp 92 Tutorial769
Qtp 92 Tutorial769
 
J Unit
J UnitJ Unit
J Unit
 
Pruebas unitarias con django
Pruebas unitarias con djangoPruebas unitarias con django
Pruebas unitarias con django
 
Code Kata: String Calculator in Flex
Code Kata: String Calculator in FlexCode Kata: String Calculator in Flex
Code Kata: String Calculator in Flex
 
Dependency Injection for Android
Dependency Injection for AndroidDependency Injection for Android
Dependency Injection for Android
 
Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014
Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014
Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014
 
Java database connecticity steps
Java database connecticity stepsJava database connecticity steps
Java database connecticity steps
 
.NET Portfolio
.NET Portfolio.NET Portfolio
.NET Portfolio
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to java
 
stateDatabuild.xml Builds, tests, and runs the project.docx
stateDatabuild.xml      Builds, tests, and runs the project.docxstateDatabuild.xml      Builds, tests, and runs the project.docx
stateDatabuild.xml Builds, tests, and runs the project.docx
 

Recently uploaded

The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
XpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsXpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsMehedi Hasan Shohan
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfPower Karaoke
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 

Recently uploaded (20)

The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
XpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsXpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software Solutions
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdf
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 

Selenium my sql and junit user guide

  • 1. http://testingtoolstecniques.blogspot.com/ http://testingtoolstecniques.blogspot.com/ Writing your first MYSQL DB functional Test Case in J unit In junit you can write test cases for any SQL Queries here I am using MYSQL however if you want to perform this on some other D.B you will just have to change connection configurations according to that D.B. You need to download MY SQL Connector for java and import that in your project. Steps: Creating Connection Class First Step is to create a connection class with data base here I am following singleton pattern for creating connection with D.B Example Code is : import com.mysql.*; import com.mysql.jdbc.Connection; public class dbConnectionInstance { public static Connection conn; static String url= "jdbc:mysql://localhost:3306/"; static String dbName = "test_data_eoffice"; static String driver = "com.mysql.jdbc.Driver"; static String userName = "root"; static String password = ""; dbConnectionInstance() {} public static Connection MysqlConnect() { if ( conn == null ) { try { Class.forName(driver).newInstance(); conn = (Connection)DriverManager.getConnection(url+dbName,userName,password); } catch (Exception sqle) { sqle.printStackTrace(); } return conn; } else return conn; } }
  • 2. http://testingtoolstecniques.blogspot.com/ http://testingtoolstecniques.blogspot.com/ Benefit of using singleton pattern is that you won’t need to created create a connection object ever time you will simply call this instance by dbConnectionInstance. MysqlConnect(); and this method will return you connection. Creating Functionalities Class This class will contain execution of all queries which we want to test First step is to create this class and identify a query here I am writing a test case for query “insert into testdatacreatefile” I created a function public void createFileTestDataGenarator() Then I executed this query with in this function Now my test functionality is ready to be called in a J-Unit Test case Example code is : import java.sql.Connection; import java.sql.SQLException; import java.sql.Statement; public class TestDataGenerator { private Connection connect = dbConnectionInstance.MysqlConnect(); private Statement statement = null; public void createFileTestDataGenarator() { try { statement=connect.createStatement(); for(int i=1000; i<=2000; i++) { String fileRefNum="Test FIle Reference Number"+i; String Subject="Test FIle Subject Number"+i; String Keywords ="keyword"+i+"A,keyword"+i+"B"; String Decscription="Test FIle Description Number"+i; int status=0; statement.executeUpdate("insert into testdatacreatefile(fileSubject,fileReferenceNumber,fileKeyword,fileDescription,testDa taStatus) values ('"+Subject+"','"+fileRefNum+"','"+Keywords+"','"+Decscription+"',"+status+")"); }} catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }} public void Log(String log) {
  • 3. http://testingtoolstecniques.blogspot.com/ http://testingtoolstecniques.blogspot.com/ try { statement=connect.createStatement(); statement.executeUpdate("insert into logger(step) values ('"+log+"')"); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void createDocumentTestDataGenarator() { try { statement=connect.createStatement(); for(int i=1000; i<=2000; i++) { String DocumentRefNum="Test Document Reference Number"+i; String Subject="Test Doucument subject "+i; String Decscription="Test Document Description"+i; String FromMinsitry="Some Test Mionistry"+i; String FromDesigntation="Some Test Mionistry Designation ABC"+i; String FromName="Some Test Misnitry Named ABC:GM"+i; String FromMedium="Some Test Courior Service"+i; int status=0; statement.executeUpdate("insert into testdatacreatedocument( DocumentRef,DocumentDesc,FromMinistry,FromDesignation,FromName,FromMedium,Stat us) values ('"+DocumentRefNum+"','"+Decscription+"','"+FromMinsitry+"','"+FromDesigntation+"','" +FromName+"','"+FromMedium+"',"+status+")"); }} catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }} }
  • 4. http://testingtoolstecniques.blogspot.com/ http://testingtoolstecniques.blogspot.com/ Creating J unit Class Left Click your project and add a J Unit Test Case There are three basic attenuation is Junit @Before: this attenuation is used for initialization @ Test: with this attenuation you call your actual test or execute with in this attenuation @ After: this attenuation is used at the end of test e.g for closing all DB connections Next step is now to call you created functionality in @ test Attenuation Create Object of that class and then call its instance like example below @Test public void testCreateFIle() throws Exception { TestDataGenerator TDG= new TestDataGenarator(); TDG.createDocumentTestDataGenarator(); //FM.addNtoing("fazal.karim", baseUrl, driver, "Abdul Hafeez", "KPO", "abdul.hafeeez"); // Thread.sleep(5000L);
  • 5. http://testingtoolstecniques.blogspot.com/ http://testingtoolstecniques.blogspot.com/ } At Last execute your Junit Class as a Junit project not as a Java Application For knowing more about MY SQL and java refer following links http://www.tutorialspoint.com/jdbc/ Writing your first Selenium Web Driver functional Test Case in J unit First of all I scripts all functionalities in a web app in a separate class and I create a separate function for every functionality like signin(string username, string password). Then I call these functions in sequence in my Junit Test case e.g you class contain 3 function sign in (), Register() , View Category(), clickProduct(), addToCart Now in your junit test case if you need add to cart you need following steps 1. Sign in User by calling signin() 2. Open a category by calling View Category() 3. Click some product by calling clickProduct(), 4. Add product to cart by calling addToCart() I this approach e.g you need a test case view product or just sign in you don’t need to rewrite test script you will simply rearrange test steps Example code is mentioned below: In this code I created a separate function for every functionality and we can call this functionality a test step benefit of this approach is reusability but in this approach you have to keep it in mind that every possible parameter must be kept dynamic import java.awt.AWTException; import java.util.ArrayList; import java.util.List; import static org.junit.Assert.*; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.*; import org.openqa.selenium.support.ui.Select; public class FileManagment { loginManager LM= new loginManager(); TestDataGenerator TDG=new TestDataGenerator(); testDataProvider TP=new testDataProvider(); String subject; String FileRefNumber; String Description; String Keywords; String fileName; // private StringBuffer verificationErrors = new StringBuffer(); public void createDocument(WebDriver wd, String uID, String baseUrl) throws ClassNotFoundException, InterruptedException
  • 6. http://testingtoolstecniques.blogspot.com/ http://testingtoolstecniques.blogspot.com/ { LM.loginAsAppUser(uID, baseUrl, wd); List<String> list= new ArrayList<String>(); testDataProvider TDP=new testDataProvider(); list=TDP.getCreateDocumentData(); String DocRef=list.get(0); String DocumentDesc=list.get(1); wd.get(baseUrl+"faces/ic/AddDocument.jsp?init=true"); wd.findElement(By.id("form1:referenceNo")).sendKeys(DocRef); wd.findElement(By.id("form1:subject")).click(); wd.findElement(By.id("form1:subject")).clear(); wd.findElement(By.id("form1:subject")).sendKeys(DocRef); wd.findElement(By.xpath("//html/body")).click(); wd.switchTo().frame("content_ifr"); wd.findElement(By.id("mce_editor_0")).sendKeys(DocumentDesc); wd.switchTo().defaultContent(); new Select(wd.findElement(By.id("fform1:template"))).selectByIndex(2); wd.findElement(By.id("form1:button")).click(); //wd.findElement(By.id("form1:hiddenBtn")).click(); } public void CreateFile(String uID,String baseUrl,WebDriver browser) throws AWTException { try{ List<String> list= new ArrayList<String>(); list=TP.getCreateFileData(); subject=list.get(0); FileRefNumber=list.get(1); Description=list.get(3); Keywords=list.get(2); WebDriver driver; driver=browser; //Step 1 login LM.loginAsAppUser(uID, baseUrl, driver); //Step 2 Create File driver.get(baseUrl+"faces/ic/CreateFile.jsp?isNewFile=true"); // ERROR: Caught exception [ERROR: Unsupported command [selectWindow | null | ]] new Select(driver.findElement(By.id("form1:cboFileHeading"))).selectByIndex(1);; new Select(driver.findElement(By.id("form1:cboFileTypes"))).selectByIndex(1);; driver.findElement(By.id("form1:txtSubject")).clear(); driver.findElement(By.id("form1:txtSubject")).sendKeys(subject); driver.findElement(By.id("form1:txtParaNumber")).clear(); driver.findElement(By.id("form1:txtParaNumber")).sendKeys("1"); driver.findElement(By.id("form1:Description")).clear(); driver.findElement(By.id("form1:Description")).sendKeys(Description); driver.findElement(By.id("form1:Keywords")).clear(); driver.findElement(By.id("form1:Keywords")).sendKeys(Keywords); driver.findElement(By.id("form1:btnSave")).click(); //driver.findElement(By.id("form1:hiddenBtn")).click();
  • 7. http://testingtoolstecniques.blogspot.com/ http://testingtoolstecniques.blogspot.com/ //driver.findElement(By.xpath("/html/body/form/table/tbody/tr[2]/td/table/tbody/tr/td [2]/table/tbody/tr/td/table/tbody/tr/td/span")); System.out.print("n"+uID+": Sucessfully Created File"); Thread.sleep(10000L); } catch (NoSuchElementException e) { e.printStackTrace(); } catch (InterruptedException e) { } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void openTopMostFileOnDesk(String uID,String baseUrl,WebDriver browser) { try { LM.loginAsAppUser(uID, baseUrl, browser); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } fileName=browser.findElement(By.xpath("/html/body/form/table/tbody/tr[2]/td/table/tbo dy/tr[2]/td/table/tbody/tr/td[2]/table/tbody/tr/td/table/tbody/tr[2]/td/table/tbody/t r[2]/td/a")).getText(); System.out.print("n"+fileName); buttonController.clickButtonByXPath(browser, "/html/body/form/table/tbody/tr[2]/td/table/tbody/tr[2]/td/table/tbody/tr/td[2]/table /tbody/tr/td/table/tbody/tr[2]/td/table/tbody/tr[2]/td/a"); System.out.print("n"+uID+": Sucessfully Opened File"); ((JavascriptExecutor)browser).executeScript("document.location.reload()"); try { Thread.sleep(2000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void openNotingTabtopMostFile(String uID,String baseUrl,WebDriver browser) { openTopMostFileOnDesk(uID, baseUrl, browser); browser.findElement(By.id("form1:text13")).click(); System.out.print("n"+uID+": Sucessfully Opened Noting Tab");
  • 8. http://testingtoolstecniques.blogspot.com/ http://testingtoolstecniques.blogspot.com/ ((JavascriptExecutor)browser).executeScript("document.location.reload()"); try { Thread.sleep(2000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void verifyNoting(String uID,String baseUrl,WebDriver browser, String FileName) { try { LM.loginAsAppUser(uID, baseUrl, browser); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } browser.getPageSource().contains(FileName); System.out.print("n"+uID+": recived file Sucessfully "); } public void addNtoing(String uID,String baseUrl,WebDriver browser, String reciverName, String reciverDesignation, String reciverID) throws InterruptedException { openNotingTabtopMostFile(uID, baseUrl, browser); JavascriptExecutor jsx = (JavascriptExecutor)browser; jsx.executeScript("window.scrollBy(0,600)", ""); browser.switchTo().frame("mce_editor_0"); browser.findElement(By.cssSelector("body")).sendKeys("heloo Fahad Testing here"); browser.switchTo().window(browser.getWindowHandle()); Thread.sleep(100L); browser.findElement(By.xpath("/html/body/form[2]/table/tbody/tr[2]/td/table/tb ody/tr/td[2]/table/tbody/tr/td/table/tbody/tr[3]/td/table/tbody/tr[20]/td/a")); Thread.sleep(500L); Select select=new Select(browser.findElement(By.id("form1:markTo"))); select.selectByVisibleText(reciverName+", "+reciverDesignation); browser.findElement(By.xpath("//*[@id="form1:fwdButton"]")).click(); Alert alert = browser.switchTo().alert(); alert.accept(); try { Thread.sleep(10000L); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } assertEquals("Internal Communication", browser.getTitle()); System.out.print("n"+uID+": sucessfully added noting and marked File to "+reciverName+" Whose designation is "+reciverDesignation);
  • 9. http://testingtoolstecniques.blogspot.com/ http://testingtoolstecniques.blogspot.com/ verifyNoting(reciverID,baseUrl, browser,fileName); } } Now Add a Junit Test Case Left Click your project and add a J Unit Test Case There are three basic attenuation is Junit @Before: this attenuation is used for initialization @ Test: with this attenuation you call your actual test or execute with in this attenuation @ After: this attenuation is used at the end of test e.g for closing all DB connections Next step is now to call you created functionality in @ test Attenuation Now call your web driver script with in @test
  • 10. http://testingtoolstecniques.blogspot.com/ http://testingtoolstecniques.blogspot.com/ import static org.junit.Assert.fail; import java.util.concurrent.TimeUnit; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.openqa.selenium.Alert; import org.openqa.selenium.By; import org.openqa.selenium.NoAlertPresentException; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.ie.InternetExplorerDriver; public class mainTestClass { private WebDriver driver; private String baseUrl; private boolean acceptNextAlert = true; private StringBuffer verificationErrors = new StringBuffer(); FileManagment FM= new FileManagment(); @Before public void setUp() throws Exception { System.setProperty("webdriver.chrome.driver","chromedriver.exe"); // System.setProperty("webdriver.ie.driver", "IEDriverServer.exe"); // driver = new InternetExplorerDriver(); Thread.sleep(2000L); driver = new FirefoxDriver(); Thread.sleep(2000L); baseUrl = "http://10.11.11.80:8080/EOffice/"; driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS); } @Test public void testCreateFIle() throws Exception { FM.createDocument(); FM.addNtoing("fazal.karim", baseUrl, driver, "Abdul Hafeez", "KPO", "abdul.hafeeez"); } @After public void tearDown() throws Exception { driver.quit(); System.out.print("Driver Closed Sucessfull");
  • 11. http://testingtoolstecniques.blogspot.com/ http://testingtoolstecniques.blogspot.com/ String verificationErrorString = verificationErrors.toString(); if (!"".equals(verificationErrorString)) { fail(verificationErrorString); } } private boolean isElementPresent(By by) { try { driver.findElement(by); return true; } catch (NoSuchElementException e) { return false; } } private boolean isAlertPresent() { try { driver.switchTo().alert(); return true; } catch (NoAlertPresentException e) { return false; } } private String closeAlertAndGetItsText() { try { Alert alert = driver.switchTo().alert(); String alertText = alert.getText(); if (acceptNextAlert) { alert.accept(); } else { alert.dismiss(); } return alertText; } finally { acceptNextAlert = true; } } } In @before I created all objects which were required by script to execute In @ after I teared down Web driver and MY SQL connection For knowing more about JUNIT refer following links http://www.tutorialspoint.com/junit/junit_using_assertion.html http://www.vogella.com/tutorials/JUnit/article.html