Friday, August 28, 2015

Jmeter : Running Selenium Scripts in Jmeter

Running Selenium Scripts in Jmeter

Pre -Req :
  1. Use latest Jmeter
  2. Goto link "http://jmeter-plugins.org/" and copy paste all the jars in "your_jmeter/lib" folder.
  3. Go to lib folder and delete files which has copies of older versions 
    1. httpclient-4.2.6.jar (delect this jar)
    2. httpclient-4.3.1.jar
    3. httpcore-4.2.5.jar (delect this jar)
    4. httpcore-4.3.jar
  4.  

Steps
  1. Open Eclipse
  2. Create new project
  3.  Add Selenium libraries to your project
  4. Add a class file in project> src  (ex: Jtest)
  5. Add the below code. 
public class Jtest {
    WebDriver driver;
   
    @Before
    public void setUp(){
        driver=new FirefoxDriver();
        System.out.println("before");
    }
    @Test
    public void test_meel(){
        driver.get("http://google.com");
    }   
    @After
    public void tearDown(){
        driver.close();
        System.out.println("after");
    }
}


Note : 
Junit Annotations are very important .
setUp() , tearDown() - method names should be exact. 

6. Save and Run (To Add Junit library ie., project>rt ck properties>Libraries>Add Library>Junit>select junit4>Finish).

7. Once It has Run successfully , project>rt ck>export>Select JAR file>Do as below
(Export Destination = "your_Jmeter/lib")



 
 8. Click Finish

 9.Open Jmeter
10.Add Thread groups
11. Thread groups>Junit Sampler
12.Thread groups> View Results Tree
13. goto Junit Request> Class name 







Output :
Result is same as if you Run seleniume script ie., Browser will open and close ,simultaneously performance is captured .


Tips :
Keep a watch on compiler version in eclipse .As currently Jmeter can recognize only 1.6 so your code needs to be compiled with 1.6 as well otherwise the class name and method will not show up in Jmeter.



Ref:
http://artoftesting.com/performanceTesting/jmeterJunit.html
http://stackoverflow.com/questions/29200736/jmeter-and-webdriver-set-do-not-work
http://jmetertips.blogspot.in/
http://pro-programmers.blogspot.in/2009/06/testing-junit-cases-in-jmeter-basic.html
http://jmetertips.blogspot.in/2009/07/running-junit-cases-with-jmeterbasic.html
http://www.javacodegeeks.com/2014/11/jmeter-tutorial-load-testing.html

Thursday, August 27, 2015

Java : Generics

Generics



If you declare a method to take ArrayList<Animal> it can take ONLY an ArrayList<Animal>, not ArrayList<Dog> .To avoid this we use generics :

 ie.,Use ArrayList<? extends Animal> instead of ArrayList<Animal> 

(Animal is parent class)

Note : But this is not required if user is sending arrays[],


Example :

public class generics {

    public static void main(String[] args) {
       
        ArrayList<Animal> A=new ArrayList<Animal>();
        A.add(new Animal());

        ArrayList<dog> B=new ArrayList<dog>();
        B.add(new dog());
        B.add(new dog());

        System.out.println(new generics().cal(B));
        System.out.println(new generics().cal(A));
    }
       
//    try ArrayList<Animal>-------instead of-------- ArrayList<? extends Animal>
    public int cal( ArrayList<? extends Animal> A ){       
        return A.size();
    }
}

class Animal{
    private boolean wild;

    public void set_wild(boolean wild){
        this.wild=wild;
    }
   
    public boolean get_wild(){
        return this.wild;
    }   
}

class dog extends Animal{
   
    private StringBuffer dog_name=new StringBuffer();
   
    public void set_dogname(String dog_name){
        this.dog_name.append(dog_name);
    }
}


Output (ArrayList<? extends Animal>) :
1
2

Output (ArrayList<Animal>)
Error

Monday, August 24, 2015

Selenium : Writing Test Results in Excel - Part 2

Writing Test Results in Excel - Part 2









Example

Test 1 (launchSiteAndLogin)
    1. Go to http://www.seleniummaster.com/seleniummastertestapp/index.php
    2. Enter "test" in the Username field
    3. Enter "XXXX" in the Password filed
    4. Click on the Login button
    5. Verify that the text "Selenium Test" is present.

Test 2 (ChangeUserSettings)
    1. Click on the radio button near friends need my authorization to add me
    2. Click on the save button
    3. Verify that the text "preference saved" displayed.

Test3 (Logout)
    1. Click on the Logout button
    2. Verify that Login button displayed.


Pre-req :

1. TestNg
2. ApachePOI libaray

   

Step 1: write the UserSettingTest.java code as follows

public class UserSettingTest
{
private WebDriver browser;
private String baseUrl;
HSSFWorkbook workbook;
HSSFSheet sheet;
Map<String, Object[]> testresultdata;//define a test result data object
@BeforeClass(alwaysRun = true)
public void setupBeforeSuite(ITestContext context) {
baseUrl = "http://www.seleniummaster.com";
workbook = new HSSFWorkbook();
sheet = workbook.createSheet("Test Result");
testresultdata = new LinkedHashMap<String, Object[]>();
testresultdata.put("1", new Object[] {"Test Step Id", "Action", "Expected Result","Actual Result"});
try {
browser=new FirefoxDriver();
browser.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
} catch (Exception e) {
throw new IllegalStateException("Can't start Web Driver", e);
}
}
@Test(description="Launches the Selenium Master Test Application and Login")
public void launchSiteAndLogin() throws InterruptedException{
browser.get(baseUrl+"/seleniummastertestapp/index.php");
browser.findElement(By.id("login_login_username")).sendKeys("test");
browser.findElement(By.id("login_login_password")).sendKeys("XXXXX"); //password is omitted
browser.findElement(By.id("login_submit")).click();
try{
assertEquals(browser.findElement(By.id("id1")).getText(),"Test Selenium");
//add pass entry to the excel sheet
testresultdata.put("2", new Object[] {1d, "navigate to site and login", "site opens and login success","Pass"});
}
catch(Exception e)
{
//add fail entry to the excel sheet
testresultdata.put("2", new Object[] {1d, "navigate to site and login", "site opens and login success","Fail"});
}
}
@Test(description="Change a User settings to add as a friends after authorization")
public void ChangeUserSettings() {
browser.findElement(By.xpath("//input[@value='auth']")).click();
browser.findElement(By.id("accountprefs_submit")).click();
try{
assertEquals(browser.findElement(By.cssSelector("div.ok")).getText(), "Preferences saved");
//add pass entry to the excel sheet
testresultdata.put("3", new Object[] {2d, "User can change settings", "Settings changed","Pass"});
}
catch(Exception e)
{
//add fail entry to the excel sheet
testresultdata.put("3", new Object[] {2d, "User can change settings", "Settings NOT changed","Fail"});
}
}
@Test(description="Log out the system")
public void Logout() throws InterruptedException {
browser.findElement(By.linkText("Logout")).click();
try{
assertTrue(isElementPresent(By.id("login_login_username")));
//add pass entry to the excel sheet
testresultdata.put("4", new Object[] {3d, "User can logout", "Logout successfull","Pass"});
}
catch(Exception e)
{
//add fail entry to the excel sheet
testresultdata.put("4", new Object[] {3d, "User can logout", "Logout successfull","Fail"});
}
}
@AfterClass
public void setupAfterSuite() {
//write excel file and file name is TestResult.xls
Set<String> keyset = testresultdata.keySet();
int rownum = 0;
for (String key : keyset) {
Row row = sheet.createRow(rownum++);
Object [] objArr = testresultdata.get(key);
int cellnum = 0;
for (Object obj : objArr) {
Cell cell = row.createCell(cellnum++);
if(obj instanceof Date)
cell.setCellValue((Date)obj);
else if(obj instanceof Boolean)
cell.setCellValue((Boolean)obj);
else if(obj instanceof String)
cell.setCellValue((String)obj);
else if(obj instanceof Double)
cell.setCellValue((Double)obj);
}
}
try {
FileOutputStream out =new FileOutputStream(new File("TestResult.xls"));
workbook.write(out);
out.close();
System.out.println("Excel written successfully..");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//close the browser
browser.close();
browser.quit();
}
private boolean isElementPresent(By by) {
try {
browser.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
}


Step 3: Create a testng.xml file to run the test suite as TestNG Suite.
Step 4: Right click on the testng.xml file and select run as TestNG Suite.
Step 5: Check the test result on the console or in the test-output folder. Generally, open the index.html under the test-output folder to view the result.

The result file indicated that all the tests passed. With this pattern, you can expand the test suite with many test modules.You can also see the TestResult.xls file to view the test result. When you open the excel file, you will see the test result as shown below.

TestStepId    Action                                   Expected Result                      Actual Result
1                   navigate to site and login     site opens and login success     Pass
2                   User can change settings     Settings changed                      Pass
3                   User can logout                    Logout successfull                   Pass