Showing posts with label Selenium WebDriver. Show all posts
Showing posts with label Selenium WebDriver. Show all posts

Selenium Java Cucumber BDD Framework from Scratch

Selenium Java Cucumber BDD Framework from Scratch,Cucumber supports Behavior Driven Development (BDD) ,Cucumber reads executable plain text specifications which is written in Gherkin language in the form of Given, Then, And, But etc keywords.

Step Definitions connects Gherkin steps to programming the code and try to execute the step definitions as mentioned in Feature Files.

Cucumber Selenium Framework from Scratch helps to create Selenium framework using Maven project ,user able to create Feature files based on scenarios. Able to run selenium test scripts with test runner class.

Selenium Cucumber project gives you flavors of 

1.Set Up maven dependency

2.Write User acceptance test cases.

3.Able to create Junit reports

4.Able to map Step definitions to Cucumber glue

5.User can run multiple feature files from runner class.



How to Make a POST Request with Rest Assured?

In previous post you've learned Rest API Testing using Rest Assured and in this below post you will learn How to Make a POST Request with Rest Assured library.In this below code uses requestSpecBuilder to make a post request. Parameter descriptions are listed below.

restAPIURL – URL of the Rest API
APIBody – Body of the Rest API. Example: {"key1":"value1","key2":"value2"}
setContentType() – Pass the "application/json", "application/xml" or "text/html" etc. headers to setContenType() method.
Authentication credentials – Pass the username and password to the basic() method or if there is no authentication leave them blank basic("","")

How to Make a POST Request with Rest Assured


public class RestAssured {


 @Test
 public void httpPostMethodTest() throws JSONException, InterruptedException {

  //Rest API's URL
  String restAPIUrl = "http://{RestAPIURL}";

  //API Body
  String apiBody = "{\"key1\":\"value1\",\"key2\":\"value2\",\"key3\":\"value3\"}";

  // Building request by using requestSpecBuilder
  RequestSpecBuilder builder = new RequestSpecBuilder();

  //Set API's Body
  builder.setBody(apiBody);

  //Setting content type as application/json
  builder.setContentType("application/json; charset=UTF-8");

  RequestSpecification requestSpec = builder.build();

  //Making post request with authentication or leave blank if you don't have credentials like: basic("","")
  Response response = given().authentication().preemptive().basic({
    username
   }, {
    password
   })
   .spec(requestSpec).when().post(restAPIUrl);

  JSONObject JSONResponseBody = new JSONObject(response.body().asString());

  //Get the desired value of a parameter
  String result = JSONResponseBody.getString({
   key
  });

  //Check the Result
  Assert.assertEquals(result, "{expectedValue}");

 }
}

REST API testing using Rest Assured

In this REST API testing using Rest Assured post, You will learn what is API and API testing, what is the little difference between SOAP and REST services, and how to test REST APIs using Rest Assured Library.


Rest API Testing using Rest Assured with Examples


What is API?


API full form is Application Programming Interface. It comprises of a set of functions that can be accessed and executed by another software systems. It is an interface between different systems and establishes interaction with systems and data exchange process.

What is API Testing?


In the modern development world, many web applications are designed based on three-tier architecture model. Those are:

1) Presentation Tier – Occupies the top level and displays information related to services available on a website ,User Interface (UI)
2) Application Tier – Also called Middle Tier or Logic Tier ,Business logic is written in this tier which is pulled from Presentation tier. It is also called Business Tier. (API)
3) Data Tier – Here information about database and data is stored and retrieved from a Database. (DB)

REST vs SOAP

REST (Representational State Transfer)


REST is an architectural style that uses simple HTTP calls for inter-machine communication. REST does not contain an additional messaging layer and focuses on design rules for creating stateless services. A client can access the resource using the unique URI and a representation of the resource is returned. With each new resource representation, the client is said to transfer state. While accessing RESTful resources with HTTP protocol, the URL of the resource serves as the resource identifier and GET, PUT, DELETE, POST and HEAD are the standard HTTP operations to be performed on that resource.

SOAP (Simple Object Access Protocol)


SOAP relies heavily on XML, and together with schema, defines a very strongly typed messaging framework. Every operation the service provides is explicitly defined, along with the XML structure of the request and response for that operation. Each input parameter is similarly defined and bound to a type: for example, an integer, a string, or some other complex object. All of this is codified in the WSDL – Web Service Description (or Definition, in later versions) Language. The WSDL is often explained as a contract between the provider and the consumer of the service. SOAP uses different transport protocols, such as HTTP and SMTP. The standard protocol HTTP makes it easier for SOAP model to tunnel across firewalls and proxies without any modifications to the SOAP protocol.

Trending Posts:



REST API Testing Using Rest Assured

What is Rest Assured?

In order to test REST APIs, I found REST Assured library so useful. It is developed by JayWay Company and it is a really powerful catalyzer for automated testing of REST-services. REST-assured provides a lot of nice features, such as DSL-like syntax, XPath-Validation, Specification Reuse, easy file uploads and with those features we will handle automated API testing much easier.

Rest Assured has a gherkin type syntax which is shown in below code. If you are a fan of BDD (Behavior Driven Development).

Rest Assured Example:

public class RestAssured{

@Test
public void appRestTest() {
given()
.contentType(ContentType.JSON)
.pathParam("name", "suresh")
.when()
.get("/restapipath/{name}")
.then()
.statusCode(200)
.body("firstName", equalTo("Suresh"))
.body("Lastname", equalTo("Narayana"));
}
}

Also, we can get JSON response as a string and send it to the JsonPath class and we can use its methods to write flexible structured tests.

public class RestAssured{

@Test
public void appJsonPathTest() {
Response res = get("/RestAPiservice/customer");
assertEquals(200, res.getStatusCode());
String json = res.asString();
JsonPath jp = new JsonPath(json);
assertEquals("rajesh@gmail.com, jp.get("email"));
assertEquals("suresh", jp.get("firstName"));
assertEquals("Narayana", jp.get("LastName"));
}
}


What is the default port number used by hub in Selenium?

What is the default port number used by hub in Selenium,While working with Selenium Grid,we require to configure Selenium Hub to connect to different machines and it will have default port number.

What is the default port number used by hub in Selenium?

What is the default port number used by hub in Selenium?

a. 4444
b. 2222
c. 3434
d. 2290

ANSWER : 4444

How to Select a Dropdown in Selenium WebDriver using Java

In order to select a dropdown value using Selenium WebDriver we have to create a Select an element and will not use the default WebElements provided by Selenium Webdriver.

Let's consider below drop-down example to select a value using Selenium WebDriver.




1.HTML Dropdown Code:

<select id="citySelect">
<option value="option1">Ahmedabad</option>
<option value="option2">Hyderabad</option>
<option value="option3">Mumbai</option>
<option value="option4">Pune</option>
</select>


1.1 Identify the HTML Element to Select value

Selenium WebDriver providing WebElement class to  identify the or store web element as below

WebElement CitySelection = driver.findElement(By.id("citySelect"));
Select dropdown= new Select(CitySelection);

Another method is directly you can pass in WebElement as below

Select dropdown = new Select(driver.findElement(By.id("citySelect")));


1.2 Select an Option

You can select drodown options by three ways

1.selectByVisibleText(String)
2.selectByIndex(int)
3.selectByValue(String)


2.1 selectByVisibleText:

You can select dropdown value by matching visible text as below

dropdown.selectByVisibleText("Hyderabad")


2.2 selectByIndex:

You can select the dropDown value by index attribute of an element as below

dropdown.selectByIndex(2)

index =1 means Ahmedabad
index=2 means Hyderabad


2.3 selectByValue:

You can select dropDown value by Optioon Value in above HTML code we've used multiple options 1,2,3,4 and code will be

drodown.selectByValue("option2")
dropdown.selectByValue("option1")


3.Complete Selenium Webdriver Code as follows:

WebElement CitySelection = driver.findElement(By.id("citySelect"));
Select dropdown= new Select(CitySelection);
dropdown.selectByIndex(2);
dropdown.selectByValue("option1");
dropdown.selectByVisibleText("Hyderabad");

Selenium WebDriver Page Object Model Framework Introduction

Page Object Model Framework in Selenium WebDriver has come to be very popular Selenium WebDriver test automation framework in the software industry and many IT companies are following this framework because of its easy to write test scripts, Test script maintenance and reduces the duplication of code.

The main merit of Page Object Model in Selenium WebDriver is that if the Web UI changes for any module pages, it don’t require to change any Selenium WebDriver Test Scripts, we just need to change only the Test Page code within the page objects. 


Page Object Model in Selenium WebDriver


Example:


public class LoginPage{

public static WebDriver driver;
private By pageTile = By.xpath("//input[@title='Selenium WebDriver']");
private By homePage=By.id("home");
private By singInPage=By.id("login");
private By uname=By.id("userName");
private By password = By.id("password");

}




In the above code, we've identified the Element locators and defined in the after the class. In this way we can achieve readability of test scripts and we can easily identify Web Element locators and change the Element Locators as per required only in page object classes.
Page Object model in Selenium WebDriver is useful in preparing the AUT functionalities or Reusable components of a Webpage which we want to automate in a separate Test class. Let’s consider as Login Page.

As per Selenium WebDriver ORG Page Object Model is


"Within your web app’s UI there are areas that your tests interact 
with. A Page Object simply models these as
objects within the test code.This reduces the amount of duplicated code
 and means that if the UI changes,the fix need only be applied in one place."

For the above page I’m creating simile class as LoginPage.class. In this class we’ll write reusable methods to call in another class to implement the Test cases.

Let’s consider entry page as Bing Search Page which will have many options like Search, Sign In, Images, Videos, Maps, News Languages, MSN, Outlook.com links. Here as per user action it will navigates to respective web pages to achieve this all functionalities that we want to automate should have reusable methods/components for each web-page.

Now as our main Entry Page is Bing Home page user can navigate to respective pages by clicking on any link from the Bing Search page. Whenever users are navigating to respective pages, we have to return particular page objects. Otherwise Return the current page object as this action doesn't navigate to another page signified by another Page Object.

The Page Object model advantages.

1. Clean Code between test code and page specific code such as locators and layout.
2. Single Object Repository for all functionalities, No Duplication of codes.

In above situation this allows you to perform modifications only in UI because of CR in current requirements or changes in UI Designs.

As per Selenium WebDriver WIKI Page

There is a PageFactory in the support package that provides support for this pattern, and helps to remove some boiler-plate code from your Page Objects at the same time.

Page Object Model in Selenium WebDriver Step by Step Guide

Page Object Model in Selenium WebDriver Projects has become crucial Automation Framework in different organization and many software Testers are implementing Selenium Page Object Model in their project why because it is easy to maintain Test Scripts, easy to understand the Test Execution, easy to maintain Page Object Repository and last but not least reduces the duplication of code.

Recommended Articles

  1. Write Test Cases PASS OR FAIL in Excel with SELENIUM
  2. Create Object Repository in Selenium Project.
  3. Page Factory Framework Implementation Examples.
  4. Start APPIUM server programmatically.


Page Object Model in Selenium WebDriver

The main advantage of Page Object Model in Selenium WebDriver is easy to maintain Page Objects, easy to avoid duplicate of Code. Duplicate code in Selenium cause duplicate of different Functionalities with this duplicate code which results in multiple time repetition of duplicate element locators. You will learn How to implement Page Object Model in Selenium using Simple Examples as explained below. In this examples I’m using simple Login.java class, so that you can implement for other classes in your Selenium Projects.

In this Page Object Model, you need to create two packages

One for Page Objects Second one for Page Test Cases Implementation as below example.

How to IMPLEMENT?

STEP 1: First Create JAVA Project
STEP 2: Configure required JAR files in Build Path
STEP 3: Create two packages under src folder
STEP 4: One Package for Page Object (Object Repository)
STEP 5: Second Package for Page Test Classes.


Login.java

Above class created under page Objects package and code will be as follows
package com.selenium.pageObjects; 
import org.openqa.selenium.*; 
import org.openqa.selenium.WebDriver; 
import org.openqa.selenium.WebElement;
 
public class LoginPage {
 
        private static WebElement element;
 
    public WebElement setUserName(WebDriver driver){
 
         element = driver.findElement(By.id("uName"));
 
         return element;
 
         }
 
     public WebElement setPassword(WebDriver driver){
 
         element = driver.findElement(By.id("password"));
 
         return element;
 
         }
 
     public WebElement clickOnSignin(WebDriver driver){
 
         element = driver.findElement(By.id("submit"));
 
         return element;
 
         }
 
}

WebDriver is being passed as a Method Arguments for each methods, so that Selenium is able to locate the Web Page elements on the specified browser using driver object. In above code element is returned, because method is not a void that is the reason we should return the values inside the method to use in another class or somewhere.so that an Action can be performed on elements. Method is declared as Public WebElement, so that method can be used in any other methods without instantiate the class.Now let’s create Page Test Case class under page Actions package as below for Login Page.

LoginTest.java
package com.selenium.Actions;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import com.selenium.pageObjects.LoginPage ;

public class LoginTest {

     private static WebDriver driver = null;
 LoginPage login=new LoginPage();

//Main Method
   public static void main(String[] args) {

 System.setProperty("webdriver.gecko.driver","E:\\geckodriver\\geckodriver.exe");
     driver = new FirefoxDriver();
     driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
     driver.get("http://www.yourloginurl.com");

     // Use page Object library now

     login.setUserName(driver).sendKeys("rajesh_3434");
     login.setPassword(driver).sendKeys("makeindia");
     login.clickOnSignin(driver).click();

     System.out.println(" User Login Successfully,My Account screen is open");

      driver.quit();

     }

}





Now create testng.xml file to run your Test Actions classes as specified in your testng.xml file,Just right click on it and Run As – TestNG Tests. 

 You will see Test script Execution on Firefox Browser as provided login credentials. 

 Thank you for reading my blog ,Please share this post in case you feel informative and provide your valuable comments on this post.