Selenium – Core Java Interview Questions – Part1

Q1. What are static Blocks in Java?

–> Static block in java is simply the initialize block, used for initialization when particular class is loaded in to JVM memory. Static blocks or static initializes are used to initialize static fields in java. we declare static blocks when we want to initialize static fields in our class. Static blocks gets executed exactly once when the class is loaded
Note that,  Static blocks are executed even before the constructors are executed.

Example –

package com.java2novice.staticexmp;
 
import java.util.ArrayList;
import java.util.List;
 
public class MyStaticBlock {
 
    private static List<String> list;
     
    static{
        //created required instances
        //create ur in-memory objects here
        list = new ArrayList<String>();
        list.add("one");
        list.add("two");
        list.add("three");
        list.add("four");
    }
     
    public void testList(){
        System.out.println(list);
    }
     
    public static void main(String a[]){
        MyStaticBlock msb = new MyStaticBlock();
        msb.testList();
    }
}

Below Output shows that, static block got executed even before constructor executes.

[one, two, three, four]

Q2. What is super keyword in java ?

–>To differentiate between instance variable and local variable, we use this keyword. On the similar line, to differentiate between members of super class and subclass (In case of inheritance), super keyword is used.  super is used to refer access method / variable / constructors from immediate parent class (While using Inheritance).

In care of overriding, a subclass object call its own variables and methods. Subclass can not access the variables and methods of superclass because the overriden variables / methods hides the methods and variables of super-class. So to overcome this issue, super keyword is used.

  • super is used to refer immediate parent class instance variable.
  • super() is used to invoke immediate parent class constructor.
  • super is used to invoke immediate parent class method.

Say you are writing a class CHILD extending a class PARENT .

While writing the constructor, if you use super() the constructor of PARENT will be called.

Or if you want to access a public/protected variable of PARENT in CHILD class, then super.variable will fetch you the PARENT variable

Example:

Parent class –
package DummyPackage;

public class parentClass {
  
  //parent class instance variable
  String name = "Parent Class Name";
  
  //parent class constructor
  public parentClass() {
    System.out.println("Parent class constructor is called");
  }
  
  //method in parent class
  public void calculate() {
    System.out.println("Area calculated in ParentClass");
  }

}
Child / subclass:
package DummyPackage;

public class superKeywordInJava extends parentClass {
  
  //child class instance variable
  String name = "Sub class name";
  
  //child class constructor, super() is used here to call parent class constructor
  public superKeywordInJava() {
    super();
  }
  
  //super os used to call methods and variables from parent class
  public void methodTOCallParentClass() {
    System.out.println("Name from parent class:: "+super.name);
    super.calculate();
  }
  
  public void calculate() {
    System.out.println("Area calculated in subclass");
  }

  public static void main(String[] args) {
    
    superKeywordInJava s = new superKeywordInJava();
    System.out.println( "******************************************");
    System.out.println("Name is:: "+s.name);
    s.calculate();	
    System.out.println( "******************************************");
    s.methodTOCallParentClass();
    }

}
Output:
Parent class constructor is called
******************************************
Name is:: Sub class name
Area calculated in subclass
******************************************
Name from parent class:: Parent Class Name
Area calculated in ParentClass

 

 

TestNG Annotations in Selenium WebDriver

TestNG Annotations in Selenium WebDriver –

TestNG Annotations are the repeated word used by developers; They are a piece of code that is inserted into the program or business logic used to control the flow of methods in java. Annotations play a major role in TestNG – The abbreviation for TestNG is Test Next Generation most of us know it is an automation framework widely used by Selenium. As I said before annotation plays an important role in TestNG, Testers need to understand the working and uses of each annotation while they are working on TestNG.

In this tutorial, I will focus on different types of TestNG annotations for Selenium Webdriver and their uses with the example. Before getting into this topic, we will know a few points about Selenium Webdriver.

What is Selenium Webdriver?

It is a group of open source API’s used for automating web application testing. The new feature of selenium is the inclusion of the WebDriver API. Selenium Webdriver was developed for the better support on the dynamic web pages.

Selenium 1.0 + Webdriver = Selenium 2.0

The main advantage of selenium web driver is they are simple to use, and programming interface is easy to understand with basic knowledge of programming languages and improved support on web-app testing problems.

Prerequisites to Write Test with TestNG?

  • Install the TestNG in Eclipse.
  • Java Development Kit(JDK)
  • Need To Add TestNG Maven dependency for your pom.xml
  • Start Writing test scenario with the help of TestNG Annotations (Note: Annotations can be used from java version 1.5 or higher versions)
  • Convert your test code into the testng.xml file
  • Compile and run your test.

List TestNG Annotations

Annotations differ from project to project depending on their requirement. Though the requirement changes the flow of execution will be the same for every single project. Here, I will list out you the TestNG Annotations and will explain one by one with examples.

  1. @BeforeSuite
  2. @BeforeTest
  3. @BeforeClass
  4. @BeforeMethod
  5. @Test
  6. @AfterMethod
  7. @AfterClass
  8. @AfterTest
  9. @AfterSuite

Workflow of TestNG is shown below:

The below workflow will be in this process, Here @Test is the base annotation in this TestNG workflow. Continuous with @Method which executes before and after execution of @Test. Now, @Class will executes before and after the execution of @Method and so on.

<BeforeSuite>
     <BeforeTest>
           <BeforeClasses>
                 <BeforeMethod>
                            <Test>
                </AfterMethod>
          </AfterClasses>
      </AfterTest>
</AfterSuite>

Now, Let see one by one from the list of Annotations:

1) @Test

In any automation script Test annotation is the important part, where we write code/business logic. If you need to automate something we need to insert that particular code into the test method, Where this test method executes Test by passing attributes. Here are some attributes which are used to pass in the test methods.

# dependsOnGroups: In this attribute, we can get a group of the list to a particular method depends on.

Example: @Test (groups = { “Organization” ,”Employee” })

# alwaysRun: This attribute can be used whenever we get a situation to run method continuously, even if the parameters of the process fails.

Example: @Test(alwaysRun = true)

# dataProviderClass: dataProviderClass is class used to provide the data to the dataProvider, So let’s give the class name as “Computer.”

# dataProvider: It is used for providing any data to the parameterization.

Example: @Test (dataProvider = “Computer”)

# dependsOnMethods: methods are used to execute it’s dependent method, In the same way, dependsOnMethods works.

Example: @Test (dependsOnMethods = { “start”, “init” })

2) @BeforeMethod and @AfterMethod

In @BeforeMethod allows the method to execute before the execution of each @test methods, Whereas @afterMethod is executed after the execution of each @test methods. In this

Code:

@BeforeMethod

public void accountLogin()
{

System.out.println(“Account has been logged in”)
}

@AfterMethod

public void accountLogout ()
{

System.out.println(“Account has been logged out”)
}

@test(priority=0)
public void updateProfile()
{

System.out.println(“Profile has been updated using the updateProfile method”)

}

@test(priority=1)
public void bankBlance()
{

System.out.println(“Bank balance will be shown using the bankBlance method” )
}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Output:

As, I as said before @BeforeMethod executes each time for the @Test method, the output for the above code will be as follow. Now, accountLogin() method will be executed before execution of updateProfile() and then accountLogout () method will be the last step. Again accountLogin() method will be executed before execution of bankBalance() and then stops with accountLogout() method.

For First @Test Method:

“Account has been logged in.”
“Profile has been updated using the updateProfile method.”
“Account has been logged out.”

For Second @Test Method

“Account has been logged in.”
“Bank balance will be shown using the bank balance method.”
“Account has been logged out.”

3) @BeforeClass and @AfterClass

The method annotated with @BeforeClass will execute only once before the first test method in that particular class is invoked. In this, you can initialization or configuration setup for all the conventional test methods. IN @AfterClass annotation will be executed only once after all the test methods of that particular class have been invoked. In the below output you can see that @BeforeClass & @AfterClass are executed at the very beginning and very end, So we can conclude that they both implement only once.

Code:

@BeforeClass

public void accountLogin()
{

System.out.println(“Account has been logged in”)
}

@AfterClass

public void accountLogout()
{

System.out.println(“Account has been logged out”)
}

@Test(priority=0)
public void updateProfile()
{

System.out.println(“Profile has been updated using updateProfile method”)

}

@Test(priority=1)
public void bankBlance()
{

System.out.println(“Bank balance will be shown using the bankBlance method” )
}

Output:

When we run the above code the output will be accountLogin() method is executed before executing updateProfile() & void bankBlance() method at last accountLogout () method is executed.

“Account has been logged in.”
“Profile has been updated using the updateProfile method”
“Bank balance will be shown using the bankBlance method”
“Account has been logged out.”

4) @BeforeTest and @AfterTest

TestNG method that is annotated with @BeforeTest will run before any test methods to that particular classes inside the test tags is run, @BeforeTest methods run after @beforeSuite. For frameworks like smoke testing @BeforeTest is used for creating an initial set-up for the set of data. Whereas @AfterTest annotation will run once after the tests are run, it helps to clean all the data.

Code:

public class Testngfile {
public String basePath = “https://mindmajix.com/selenium-training”;
String path = “D:\\svcdriver.exe”;
public WebDriver automation;@BeforeTest
public void openBrowser() {
System.out.println(“opening chrome browser”);
System.setProperty(“webdriver.firefox.nicole”, path);
automation = new FirefoxDriver();
automation.get(basePath);
}
@Test
public void welcomePage() {
String welcomeMessage = “Hello Connections”;
String requiredMessage =automation.getTitle();
Assert.assertEquals(requiredMessage, welcomeMessage);
}
@AfterTest
public void discontinueBrowser(){
automation.close();
}
}

5) @BeforeSuite and @AfterSuite

With the help of @BeforeSuite annotation, we can set up and start the selenium webdrivers. The @AfterSuite annotation is used to stop the selenium drivers.

Code:

public class SuiteInitialization() {

@BeforeSuite(alwaysRun = true)
public void initializationSuite() {
WebDriver automation = new FirefoxDriver();
}

@AfterSuite(alwaysRun = true)
public void discontinue() {
automation().close();
}
}

When you are working with annotation, it’s essential to check whether your system is installed with Java 1.5 version or higher version, Because annotation works only with Java 1.5 version or the above. In case, You are working with annotation on older versions of Eclipse it through an error saying that annotations are not supported on your system.

Final Words:

In this tutorial, We have discussed some of the important testng annotations and few attributes which are frequently used by testers. Here are some more annotations which are used but not regularly such annotation are @AfterGroups and @BeforeGroups. However, they are significant when you are working with groups in you are the project. From the above annotations pick the right one for your project and use them according to your requirement.

 

–> This is a Guest Article shared by – Gnanasekar (GnanaSekar is working as a Technical Content Contributor & SEO Analyst for Mindmajix. He holds a Bachelor’s degree in Electrical & Electronics Engineering from Anna University. He can be contacted at gnanasekar.6914@gmail.com. Connect with Gnanasekar on LinkedIn.)

backed-up home page

AutomationTalks.com is a platform to learn and practice software automation testing. This is a technological blog and on this blog you will find Various Automation tool tutorials and videos, explained in very simple language which will be helpful for new learner as well as experienced professionals.

Software testing is a process of executing a program or application with the intent of finding the software bugs.

In other words, it is the process of validating and verifying that a software program or application or product:

  • Meets the business and technical requirements that guided its design and development
  • Works as expected
  • Can be implemented with the same characteristic.

Trends in Software testing keep changing, Here is the list of Latest Trends in software testing in year 2017.

Latest Trends in Software Testing – 2017

Testing is important because software bugs could be expensive or even dangerous.

Basically, testing is classified as –

 

 

      Well, let’s talk about, how software testing is in terms of career?

 

So, it’s that simple, anywhere, you need to offer something special & unique. you will rock there. Check below link where i tried to explain How is Software Testing as a career. So, Finally, decision is up to you, how & where you want to start your career.

 

How is Software Testing as a Career ?

 

API Testing Automation

API testing automation consist of 5 major steps. Also make sure that API test cases should be executed with any order ,they should be independent of each other.

  1. Setup –> It involves calling common methods, or functions to perform tasks such as Initialize data, create objects, start services or setting machine states.Basically setup is about putting the system in to a known machine state required for test execution.
  2. Execution –> These are the statements  to exercise API or sequence of API’s. It should include logging as well. If a test fails and you can not determine the failure from the log files, then probably you aren’t logging required information.
  3. Verification –> Evaluate execution outcomes. Compare actual results with expected one. Example – verify for error codes, verify output parameters, and many other.
  4. Reporting –> It records the outcome of the test. An automated test should be designed to log Pass / Fail / Blocked results
  5. Cleanup –> It basically means  to return the system to its pre-test state by releasing memory, shutting down services and deleting files used by that test if required.

How to upload file in selenium using AutoIT

In earlier articles, we saw that, we can upload the file using sendKeys() method or by using robot class.
Refer below articles for this.

Upload file in selenium using sendkeys() method.

Upload file in selenium using robot class

Now, in case both of the above methods won’t work, then we have to use AutoIT tool (which a third-party tool used to handle window popups). Let’s talk how this can be done.
AutoIt v3 is a freeware BASIC-like scripting language designed for automating Windows GUI and general scripting. It uses a combination of simulated keystrokes, mouse movement and window/control manipulation in order to automate tasks.
This method is for handling the Windows File Upload dialog, which cannot be handled using Selenium. Please follow below steps:
         
           1.       Download AutoIT setup file from here (https://www.autoitscript.com/site/autoit/downloads/)
      
           2.       Open Au3Info.exe for which helps to find window information details.
           
          3.       Open SciTE Script Editor.
            Script used to upload the file is as below. Write the script below in script editor.
               ControlFocus(“File Upload”,””,”Edit1″)

               ControlSetText(“File Upload”,””,”Edit1″,”C:UsersPrakashDesktopTOSCA tutorial.pptx”)

               ControlClick(“File Upload”,””,”Button1″)
              We can get Title and control id from application Au3Info.exe. Just Drag and drop the finder tool at required position. 

              In this script Control Focus is used to focus on the field where we enter the file to be uploaded path details. Note that Control id is the combination of Class and Instance.
     
        Syntax –  ControlFocus(“title”,”text”,”Control id”)
                                                       
                          ControlSetText is used to write the text (file path of the file to be uploaded)
                          Syntax – ControlSetText(“title”,”text”,”Control id”,”file path”)
 
                          ControlClick is used to click on the button.
                           Syntax – ControlClick(“title”,”text”,”Control id”)
 
              2.       Save the Script with some name with .au3 extension. 
 
              3.       Then right click on it, click on Compile.
               4.       Then Double click on the same file.
              5.       Now you will see the .exe file with same name is generated.
                   We are going to use this .exe file in our java – selenium program (to upload the file using AutoIT).
        
             6.       Use below piece of code for executing the .exe file created above
                 
               Runtime.getRuntime().exec(“C:UsersPrakashDesktopTestScript.exe”);
          
          Refer below example –

package basicsOfSelenium;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

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

public class AutoIT {

public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub

WebDriver driver = new FirefoxDriver();
driver.navigate().to("http://www.tinyupload.com/");
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.manage().window().maximize();

// Click on Browse Button
driver.findElement(By.xpath("html/body/table/tbody/tr[4]/td/table/tbody/tr/td[2]/form/table/tbody/tr[2]/td[1]/input[2]")).click();

//After pop-up open, below script is used to upload the file
Runtime.getRuntime().exec("C:UsersPrakashDesktopTestScript.exe");

}
  
Hope this helps !!!!

How to upload file in Selenium WebDriver using sendKeys() method

Let us talk about how to upload file in Selenium WebDriver. We can upload the file in selenium WebDriver using various methods. By using sendKeys() method is one of the simplest one.
Upload file in Selenium WebDriver using sendKeys
This is the simplest way to upload the file in selenium Webdriver. Here we will use sendKeys() method to send the absolute file path to be uploaded. But this can be achieved only when the type attribute for filepath textbox / browse button is “file”. Observe below screenshot for this.
As in above screenshot, since type = file, we can use sendKeys() method to send the file path & then click on upload / submit file button to complete upload process.
First make sure that the input element is visible
Don’t click on the browse button, it will trigger an OS level dialogue box and effectively stop your test dead.
Instead you can use:
driver.findElement(By.xpath(“//*[@id=’uploadfile_0′]”)).sendKeys(“C:UsersPrakashDesktopDesktopTOSCA tutorial.pptx”);
//*[@id=’uploadfile_0′] is the xpath of that element (button in this case) and in sendKeys you have to specify the absolute path of the content you want to upload (Image,video etc). Selenium will do the rest for you.
Keep in mind that the upload file will work only If the element you send a file should be in the form    <input type=”file”>
Below is the sample example of how to upload file –

package basicsOfSelenium;

import java.util.concurrent.TimeUnit;

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

public class FileUploadInSelenium1 {

 public static void main(String[] args) {

  WebDriver driver = new FirefoxDriver();
  driver.navigate().to("http://demo.guru99.com/selenium/upload/");
  driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
  driver.manage().window().maximize();
  
  //send the file path to be uploaded to the element, note - this will work only if attribute type = file
  driver.findElement(By.xpath("//*[@id='uploadfile_0']")).sendKeys("C:UsersPrakashDesktopDesktopTOSCA tutorial.pptx");
  
  //click on accept term checkbox
  driver.findElement(By.xpath("//*[@id='terms']")).click();
  //click on submit button - to complete file upload
  driver.findElement(By.xpath("//*[@id='submitbutton']")).click();

  
 }

}
Well, this was all about upload file in Selenium webdriver by using sendKeys() method. There is another way to do it is by using AutoIT. Refer below link to know more about AutoIT

AutoIT Tutorials – Upload and download files in Selenium WebDriver

Hope this helps !!!

Extracting all links from web page / Bulk extraction of objects

In this article, we will talk about finding total number of objects (Links / Checkboxes / dropdown etc) present on the Web Page. We may need these things while counting total number of links present on web page, checking if all links are working properly etc.
Let us see how this can be done.
         a.       First Navigate to the webpage.
         b.       Get the list of all web-elements (which you need, could be either links, or checkboxes or dropdowns) using proper attribute type.
        c.       Get the count (total number of links) from the list.
        d.       Finally iterate over the list & get all desired objects.
Look at the below example.
Let us suppose, I want to find total number of links present on particular web page.

package basicsOfSelenium;

import java.util.List;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class ExtractAllLInks {

public static void main(String[] args) {

WebDriver driver = new FirefoxDriver();
driver.navigate().to("http://demowebshop.tricentis.com/");
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.manage().window().maximize();

List<WebElement> allElements = driver.findElements(By.tagName("a"));
System.out.println("Total Number of Links present on this page is: "+allElements.size());

for (WebElement ele : allElements){
System.out.println("Link is: "+ ele.getText());
}

}

}

Now in case, if you want to find Number of checkboxes present on the web page, then use below –
List<WebElement> listOfCheckBoxes = driver.findElements(By.xpath("//input[@type='checkbox']")); 
Now in case, if you want to find Number of dropdowns present on the web page, then use below –

  List<WebElement> allDropdowns = driver.findElements(By.tagName("select"));
If you want to find total number of text boxes present on web page, then –
List<WebElement> allTextBoxes = driver.findElements(By.xpath("//input[@type='text'[@class='inputtext']"));
Hope this helps !!!!