Friday, December 25, 2020

How to get the number of objects created in JAVA

Program to get the number of objects created in JAVA

public class Main

{

    static int i=0;

    public Main()

    {

        i++;

    }

    public Main(String name)

    {

        i++;

    }

public static void main(String[] args)

{

    Main m=new Main();

    Main m1=new Main("Balaji");

    System.out.println(i);

}

}

Output:

2

Wednesday, February 14, 2018

How to click the 'Second' element out of '8' matching element using Selenium Webdriver (Two elements in a page with same ID's)

Option 1:

You can use XPath indexing.

Example:
driver.findElement(By.xpath("(//*[@id="notificationStatusSwitch"])[2]"));

Option 2:

You can use findElements(): Using the given “locating mechanism” find all the elements on the current page.It returns a list of web elements, Then access the second one found

Example:

List<WebElement> elementList = driver.findElements(By.xpath("//*[@id="notificationStatusSwitch"]"));

elementList.get(1).click;

Thursday, February 1, 2018

Generate Extent Reports (Java) in Selenium WebDriver

In this article, we see one of the most popular and widely used Selenium Reporting Tools (Extent Reports).
What is Extent Reports?
Extent Report is an HTML reporting library for Selenium WebDriver for Java.
Features of Extent Report:
  • Allow is to generate logs inside HTML.
  • Generate PIE Chart based on test case status.
  • Generate Step summary.
  • We can filter reports depends on status.
  • It provides execution history.
  • It fetches system details like OS, Java Version, and Memory and so on.
  • Allow us the attached screenshot in the report that is a most important feature.

Pre-requisites to Generate Extent Reports:
1.    Java should be installed (Link to Install and setup Java )
2.    TestNG should be installed
3.    Extent Report Jars (Version 2.41.2)
4.    extent-config.xml – It allows to configure HTML Report

Steps To Generate Extent Reports:
1.    First, Create a TestNG project in eclipse
2.    Now download extent library files from the following link (http://extentreports.com/) and add the downloaded library files to your project.

Please refer the below sample code:

package com.Tests;
import java.io.IOException;
import org.testng.ITestResult;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
import com.BaseFixture.BaseFixture;
import com.CommonMethods.WebUtils;
import com.relevantcodes.extentreports.ExtentReports;
import com.relevantcodes.extentreports.ExtentTest;
import com.relevantcodes.extentreports.LogStatus;

public class HomePage extends BaseFixture
{            
              String Login_Button_Obj=null;String Enter_Username_Obj=null;String Enter_Password_Obj=null;String Click_Login_Obj=null;
              String Username_Data=null;String Password_Data=null;String Search_Box_Obj=null;String Search_Text_Data=null;
              String Click_POTUS_Obj=null;String Follow_Link_Obj=null;String Click_Follow_Obj=null;
             
              ExtentReports reports;
              ExtentTest logger;
             
              @BeforeSuite
              public void beforeSuite()
              {
                             reports=new ExtentReports("D:\\Interview\\balaji-interview-framework\\AdvanceTestRun.html",true);                                                    
                             reports.addSystemInfo("Application URL","https://twitter.com/");
                             reports.addSystemInfo("Environment", "Live Environment");
                             reports.addSystemInfo("Author","Balaji G");                   
              }
             
              @BeforeTest
              public void launchApplication() throws IOException
              {                                                                                                                                                                                         
                            Login_Button_Obj=WebUtils.readDataFromPropertiesFile("D:/Interview/balaji-interview-framework/src/test/resources/com/ObjectRepository/HomePage/HomePageObject.properties","Login_Button");                                                         
                            Enter_Username_Obj=WebUtils.readDataFromPropertiesFile("D:/Interview/balaji-interview-framework/src/test/resources/com/ObjectRepository/HomePage/HomePageObject.properties","Enter_Username");
                            Enter_Password_Obj=WebUtils.readDataFromPropertiesFile("D:/Interview/balaji-interview-framework/src/test/resources/com/ObjectRepository/HomePage/HomePageObject.properties","Enter_Password");
                            Click_Login_Obj=WebUtils.readDataFromPropertiesFile("D:/Interview/balaji-interview-framework/src/test/resources/com/ObjectRepository/HomePage/HomePageObject.properties","Click_Login");
                            Search_Box_Obj=WebUtils.readDataFromPropertiesFile("D:/Interview/balaji-interview-framework/src/test/resources/com/ObjectRepository/HomePage/HomePageObject.properties","Search_Box");
                            Click_POTUS_Obj=WebUtils.readDataFromPropertiesFile("D:/Interview/balaji-interview-framework/src/test/resources/com/ObjectRepository/HomePage/HomePageObject.properties","Click_POTUS");
                            Follow_Link_Obj=WebUtils.readDataFromPropertiesFile("D:/Interview/balaji-interview-framework/src/test/resources/com/ObjectRepository/HomePage/HomePageObject.properties","Follow_Link");
                            Click_Follow_Obj=WebUtils.readDataFromPropertiesFile("D:/Interview/balaji-interview-framework/src/test/resources/com/ObjectRepository/HomePage/HomePageObject.properties","Click_Follow");
                            
                            Username_Data=WebUtils.readDataFromPropertiesFile("D:/Interview/balaji-interview-framework/src/test/resources/com/DataRepository/HomePage/HomePageData.properties","Username");
                            Password_Data=WebUtils.readDataFromPropertiesFile("D:/Interview/balaji-interview-framework/src/test/resources/com/DataRepository/HomePage/HomePageData.properties","Password");
                            Search_Text_Data=WebUtils.readDataFromPropertiesFile("D:/Interview/balaji-interview-framework/src/test/resources/com/DataRepository/HomePage/HomePageData.properties","Search_Text");
              }
             
              @Test(priority=0)
              @Parameters({"browser"})
              public void verifyHomePage(String bro)
              {            
                             logger=reports.startTest("Verify Home Page - Twitter");
                             boolean isElementFound=WebUtils.IsElementDisplayed(getDriver(bro),Login_Button_Obj);
                  if(isElementFound)
                  {                                                        
                            System.out.println("Twitter Home page is loaded successfully");
                            logger.log(LogStatus.PASS, "Twitter Home Page is loaded Successfully");
                  }
                  else
                  {
                            System.out.println("Twitter Home page is not loaded successfully");
                            logger.log(LogStatus.FAIL, "Twitter Home Page is not loaded Successfully");
                  }
                  reports.endTest(logger);
               }
             
              @Test(priority=1)
              @Parameters({"browser"})
              public void loginwithValidCredentials(String bro) throws InterruptedException
              {            
                             logger=reports.startTest("Verify Login with Valid Credentials - Twitter");
                             boolean isElementFound=WebUtils.IsElementDisplayed(getDriver(bro),Enter_Username_Obj);                            
                  if(isElementFound)
                  {                                                        
                                WebUtils.ClickElementByXpath(getDriver(bro),Login_Button_Obj);
                           
                            WebUtils.ClearInputByXpath(getDriver(bro), Enter_Username_Obj);
                                           WebUtils.EnterInputByXpath(getDriver(bro), Enter_Username_Obj, Username_Data);
                                          
                                           WebUtils.ClearInputByXpath(getDriver(bro), Enter_Password_Obj);
                                           WebUtils.EnterInputByXpath(getDriver(bro), Enter_Password_Obj, Password_Data);
                                           Thread.sleep(2500);
                                          
                                           WebUtils.ClickElementByXpath(getDriver(bro),Click_Login_Obj);
                                           System.out.println("Login Successful - Twitter");
                                           Thread.sleep(2500);
                            logger.log(LogStatus.PASS, "Login Successful - Twitter");
                  }
                  else
                  {
                            System.out.println("Login button is not available");
                            logger.log(LogStatus.FAIL, "Login button is not available. So Unable to login - Twitter");
                  }
                  reports.endTest(logger);
               }
             
              @Test(priority=2)
              @Parameters({"browser"})
              public void followPOTUS(String bro) throws InterruptedException
              {            
                             String expectedText="Follow";
                             logger=reports.startTest("Verify whether POTUS is following or not - Twitter");
                             boolean isElementFound=WebUtils.IsElementDisplayed(getDriver(bro),Search_Box_Obj);                            
                  if(isElementFound)
                  {                                                                               
                            WebUtils.ClearInputByXpath(getDriver(bro), Search_Box_Obj);
                                           WebUtils.EnterInputByXpath(getDriver(bro), Search_Box_Obj, Search_Text_Data);
                                           Thread.sleep(2500);                                  
                                           WebUtils.ClickElementByXpath(getDriver(bro),Click_POTUS_Obj);
                                           Thread.sleep(5000);
                                           String text=WebUtils.GetElementText(getDriver(bro), Follow_Link_Obj);
                                           if(text.equals(expectedText))
                                           {
                                                         WebUtils.ClickElementByXpath(getDriver(bro),Click_Follow_Obj);
                                                          Thread.sleep(5000);
                                                          System.out.println("Successfully Started Following - POTUS(Twitter)");
                                           logger.log(LogStatus.PASS, "Successfully Started Following - POTUS(Twitter)");
                                           }
                                           else
                                           {
                                                          System.out.println("Already Logged-in is Following - POTUS(Twitter)");
                                           logger.log(LogStatus.PASS, "Already Logged-in User is Following - POTUS(Twitter)");                  
                                           }
                  }
                  else
                  {
                            System.out.println("Search Textbox is not available");
                            logger.log(LogStatus.FAIL, "Search Textbox is not available");
                  }
                  reports.endTest(logger);
               }
             
              @AfterMethod
              @Parameters({"browser"})
              public void closeApplication(String bro,ITestResult result) throws Exception
              {
                             if(result.getStatus()==ITestResult.FAILURE)
                             {
                                           String screenShot_Path=WebUtils.captureScreenshot(getDriver(bro), result.getName());
                                           String image=logger.addScreenCapture(screenShot_Path);                                                                
                                           logger.log(LogStatus.FAIL, "FailedScreenshot", image);
                             }            
              }
             
              @AfterTest
              @Parameters({"browser"})
              public void endReport(String bro)
              {
                             getDriver(bro).quit();                  
    }
             
              @AfterSuite
              public void afterSuite()
              {
                             reports.flush();
                             SendMailSSLWithAttachment.mailTrigger();
              }

}

Sample Report:


Wednesday, January 17, 2018

Interview Question - How to run same test case multiple times

In this blog, We will see how to run same test case multiple times. We can run same test case multiple times with help of @Test attribute 'invocationCount'.

@Test(invocationCount=?):

This invocationCount determined how many times TestNG should run this particular test method.

Example:

@Test(invocationCount = 2)
public void repeatTest()
{
     System.out.println("Execute Test 2 times");
}

Output:

The repeatTest() method will run 2 times.

Execute Test 2 times
Execute Test 2 times

PASSED: repeatTest
PASSED: repeatTest

Now let's see how to use invocationCount in Selenium script with the example.

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
import org.testng.annotations.Test;

public class RunSameTestMultipleTimes 
{
@Test(invocationCount = 2)
public void loadApplication()
{
WebDriver driver = new FirefoxDriver();
driver.get("http://www.google.com");
System.out.println("Page Title is " +driver.getTitle());
Assert.assertEquals("Google",driver.getTitle());
driver.close();
driver.quit();
}
}

Output:

You will notice that Firefox browser will prompt out and close 2 times.

Page Title is Google
Page Title is Google

PASSED: loadApplication
PASSED: loadApplication

Thursday, January 11, 2018

Javascript in Selenium Web-driver

Hello All,

Welcome to Software Testing Made Life Easy blog. In this post, we will see how we can introduce Javascript in Selenium Webdriver.

What is Javascript?

Javascript is one of the programming languages of the Web and It is a lightweight programming language and most commonly used as a part of web pages.

All modern HTML pages are using JavaScript.

Use of Javascript in Selenium Webdriver:

We have used Java in our script and we have implemented almost all features but some features can’t be handled by Java. So we need scripting language which can control server side & client side scripting. That's why JavaScript comes into the picture.

Implement Javascript in Selenium Webdriver:

To implement Javascript in our selenium script, We don't need to write the separate code because we have a predefined interface available in package org.openqa.selenium.JavascriptExecutor.

Inside this, We have some predefined method called executeScript() - Whatever script you will pass as a 'String', those will be executed by JavascriptExecutor.

Example:

import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class JavaScriptTestCase
{
public static void main(String[] args) throws InterruptedException
{
WebDriver driver=new FirefoxDriver();
System.out.println("Launching Browser");
driver.manage().window().maximize();
driver.get("https://software-testing-made-lifeeasy.blogspot.in");
((JavascriptExecutor)driver).executeScript("document.getElementById('s').value='Balaji'");
}
}

Tuesday, January 9, 2018

Interview Question - What are the difference between web app and mobile app?

Mobile App:

A Mobile App is an application developed essentially for a particular handset and it will be installed directly onto the device.


Web App:

Basically, Internet-enabled apps that are accessible via the mobile device’s Web browser.



Accessibility:

A mobile app is totally compatible with the device’s hardware and native features, such as the GPS, the accelerometer, the compass, the list of contacts, and so on.

On the other hand, Web app can access only a limited amount of the device’s native features.

Upgradability:

A web app is much more dynamic than a mobile app in terms of updating the content.

Efficiency:

Mobile apps are more expensive to develop. However, they are faster and more efficient. Users can access the app only via the app store.



Web apps may result in higher costs of maintenance across multiple platforms. Also, there is no specific authority to control the quality of these apps.

Reach:

A web app is accessible across platforms and can be easily shared among users, as well as search engines, it has considerably greater reach than a mobile app.

User Interface:

Both the mobile apps and the web apps look and work the same way with a very little difference (The choice and decision is up to you ðŸ˜Š) 

Feel free to share your valuable feedback.Thanks.

Wednesday, January 3, 2018

Challenges we faced in Selenium Automation Testing

I work on Selenium Automation Testing and one of the major challenging tasks which I faced was, After invoking the application URL on any browser, it was required to authenticate the window based pop-up as below. The first challenge was selenium doesn't handle windows based pop-ups.

The solution is AutoIt tool (Click here!)
I wrote code using AutoIt which can easily handle the window based pop-up to enter credentials.
About AutoIt tool:
AutoIt is a tool where we can capture window based objects and write a simple AutoIt script. Once we compile & Run the AutoIt script file, It will generate the .exe file and which can be invoked within our selenium automation scripts.
Now, all we need to do is call the .exe soon after invoking the application URL. Please refer the sample code below
driver.get("application URL");
Runtime.getRuntime().exec("path where the .exe file exists");
Now the actual problem was AutoIt code was not getting triggered after invoking the application URL - driver.get("application URL").
Please find the solution to the above problem:
Subsequent lines of code will not execute unless execution of driver.get("application URL") method is complete. We found out that driver.get("application URL") was not getting completed unless we complete the window based pop-up operation.
The only solution is to run both driver.get("application URL") method and AutoIT code in parallel. This can be achieved with help of Java multi-threading.
After invoking the application URL, We will be giving control to window based pop-up and due to parallel execution, AutoIt.exe code will trigger and enter the credentials in a window based pop-up and completes the operation. Due to this, driver.get("application URL") method will also gets completed.
Code:
driver.get("application URL");
AUTOIT startExe=new AUTOIT ();
Thread t1 =new Thread(startExe);
t1.start();
Finally, I solved the issue.
Feel free to share your valuable feedback.Thanks.