How to disable tests in JUnit5 – @Disabled

HOME

JUnit5 also provides the support to exclude/disable the tests. The @Disabled annotation in JUnit5 is used to exclude the test methods from the test suite. This annotation can be applied over a test class as well as over individual test methods. This annotation accepts only one optional parameter where we can mention the reason to skip the tests. @Disabled annotation can be used without providing any reason but its always good to provide a reason why this particular test case has been disabled, or issue tracker id for better understanding.

1.Disable Test Methods

In the below example, I have annotated 2 test methods out of 5 test methods as @Disabled with a parameter which specify the reason for disabling the test that means these 2 test methods should not be executed.

import io.github.bonigarcia.wdm.WebDriverManager;
import org.junit.jupiter.api.*;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import static org.junit.jupiter.api.Assertions.*;

class DisabledTestsDemo {

    WebDriver driver;

    @BeforeEach
    public void setUp() {
        
        WebDriverManager.chromedriver().setup();
        ChromeOptions chromeOptions = new ChromeOptions();
        driver = new ChromeDriver(chromeOptions);
        driver.manage().window().fullscreen();
        driver.get("http://automationpractice.com/index.php");

    }

    @Disabled("This test is not applicable for Sprint 14")
    @Test
    void verifyPopularLink() {

        boolean displayed = driver.findElement(By.xpath("//*[@id='home-page-tabs']/li[1]/a")).isDisplayed();
        assertTrue(displayed);

    }

    @Test
    void verifyContactNumber() {

        String contactDetail = driver.findElement(By.xpath("//span[@class='shop-phone']/strong")).getText();
        assertEquals("0123-456-789", contactDetail);

    }

    @Disabled("This test is blocked till bug 1290 is fixed")
    @Test
    void verifyWomenLink() {

        boolean enabled = driver.findElement(By.xpath("//*[@id='block_top_menu']/ul/li[1]/a")).isEnabled();
        assertTrue(enabled);
    }

    @Test
    void contactUSPageTest() {

        driver.findElement(By.xpath("//*[@id='contact-link']/a")).click();
        String contactPage = driver.getTitle();
        assertEquals("Contact us - My Store", contactPage);
    }

    @Test
    void signInPageTest() {

        driver.findElement(By.className("login")).click();
        String signInPage = driver.getTitle();
        assertEquals("Login - My Store", signInPage);
    }

    @AfterEach
    public void tearDown() {
        driver.close();
    }
}

The output of the above test shows, the 2 tests that are annotated with @Disabled are not executed.

2. Disable Test Class

When we annotate a class as @Disabled, then all the test methods present within that test class will not be executed.

In the below example, there are 2 test classes – Demo and DisabledTestsDemo. Demo class contains 1 test method whereas DisabledTestsDemo contains 5 test methods. I have annotated DisabledTestsDemo class as @Disabled which means all 5 tests present within it will not be executed.

In the below example, there is a base class that contains the initialization of webDriver as well as closing of the same.

import io.github.bonigarcia.wdm.WebDriverManager;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;

public class Base {

    static WebDriver driver=null;

    @BeforeEach
    public void setUp() {

        WebDriverManager.chromedriver().setup();
        ChromeOptions chromeOptions = new ChromeOptions();
        driver = new ChromeDriver(chromeOptions);
        driver.manage().window().fullscreen();
        driver.get("http://automationpractice.com/index.php");

    }

    @AfterEach
    public void tearDown() {
        driver.close();
    }
}

Class 1 – Demo

import org.junit.jupiter.api.*;

public class Demo extends Base{

    @Test
    public void homePage() {
        Assertions.assertEquals("My Store",driver.getTitle());

    }
}

Class 2 – DisabledTestsDemo

import org.junit.jupiter.api.*;
import org.openqa.selenium.By;
import static org.junit.jupiter.api.Assertions.*;

@Disabled
class DisabledTestsDemo extends Base {

    @Test
    void verifyPopularLink() {

        boolean displayed = driver.findElement(By.xpath("//*[@id='home-page-tabs']/li[1]/a")).isDisplayed();
        assertTrue(displayed);

    }

    @Test
    void verifyContactNumber() {

        String contactDetail = driver.findElement(By.xpath("//span[@class='shop-phone']/strong")).getText();
        assertEquals("0123-456-789", contactDetail);

    }

    @Test
    void verifyWomenLink() {

        boolean enabled = driver.findElement(By.xpath("//*[@id='block_top_menu']/ul/li[1]/a")).isEnabled();
        assertTrue(enabled);
    }

    @Test
    void contactUSPageTest() {

        driver.findElement(By.xpath("//*[@id='contact-link']/a")).click();
        String contactPage = driver.getTitle();
        assertEquals("Contact us - My Store", contactPage);
    }

    @Test
    void signInPageTest() {

        driver.findElement(By.className("login")).click();
        String signInPage = driver.getTitle();
        assertEquals("Login - My Store", signInPage);
    }
}

The output of the above test shows, all the test methods present in the class that is annotated with @Disabled are not executed.

Congratulations. We are able to understand the usage of @Disabled annotation in JUnit5. Happy Learning!!

Advertisement

What is Allure Report?

HOME

Allure Framework is a flexible lightweight multi-language test report tool that not only shows a very concise representation of what has been tested in a neat web report form but allows everyone participating in the development process to extract the maximum useful information from the everyday execution of tests.

How Allure Report is generated?

Allure is based on standard xUnit results output but adds some supplementary data. Any report is generated in two steps. During test execution (first step), a small library called adapter attached to the testing framework saves information about executed tests to XML files. We already provide adapters for popular Java, PHP, Ruby, Python, Scala, and C# test frameworks. During report generation (second step), the XML files are transformed into an HTML report. This can be done with a command line tool, a plugin for CI, or a build tool.

Similarly, when we run our tests, every popular test framework generates junit-style XML report or testng style which will be used by Allure to generate HTML report.

In the below example, we use the maven surefire plugin which automatically generates xml test reports and stores them in target/surefire-reports. And these XML files are transformed into an HTML report by Allure.

Allure reports have provided adapters for Java, PHP, Ruby, Python, Scala, and C# test frameworks.

Allure report has the below-mentioned annotation.

@Epic
@Features
@Stories/@Story

We can add Epic, Feature, and Stories annotations to the test to describe the behaviour of the test.

@Severity(SeverityLevel.BLOCKER)@Severity annotation is used in order to prioritize test methods by severity.

@Description(“Regression Testing”) – We can add a detailed description for each test method. To add such a description, use the @Description annotation.

@Step – In order to define steps in Java code, you need to annotate the respective methods with @Step annotation. When not specified, the step name is equal to the annotated method name.

@Attachment – An attachment in Java code is simply a method annotated with @Attachment that returns either a String or byte[], which should be added to the report.

@Link – We can link the tests to Defect Tracker or JIRA Ticket.

Below is an example that shows how to use various Allure Annotations in the Test.

@Epic("Web Application Regression Testing")
@Feature("Login Page Tests")
@Listeners(TestExecutionListener.class)
public class LoginTests extends BaseTest {

	LoginPage objLogin;
	DashboardPage objDashboardPage;

	@Severity(SeverityLevel.NORMAL)
	@Test(priority = 0, description = "Verify Login Page")
	@Description("Test Description : Verify the title of Login Page")
	@Story("Title of Login Page")
	public void verifyLoginPage() {

		// Create Login Page object
		objLogin = new LoginPage(driver);

		// Verify login page text
		objLogin.verifyPageTitle();
	}
}

Install Allure

For Windows, Allure is available from the Scoop commandline installer.

Set-ExecutionPolicy RemoteSigned -scope CurrentUser

Invoke-Expression (New-Object System.Net.WebClient).DownloadString('https://get.scoop.sh')

To install Allure, download and install Scoop, and then execute in the Powershell:

scoop install allure

I have Allure installed, so I’m getting a message – ‘allure’ (2.14.0) is already installed.

To check if you have Allure installed or not, please use the below command in the command line or PowerShell.

allure --version

Sample Allure Report

You can find more information on Allure documentation.

Additional Tutorials on Allure Reports

Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!! 

How to automate Radio Button in Selenium WebDriver

HOME

 

In this tutorial, will find out how the Radio Buttons can automated in Selenium WebDriver. Radio Button is also a Web Element like Checkbox. 
Below image shows the Radio Buttons before they selected

Here, In below image Male option is selected and clicked on Get Checked value, then a message will be displayed.

Here,
Check if Option 1 is already selected or not
If Option 1 is already selected, then select Option 2, else select Option 1.

Let’s go through the scenario below:-

1) Launch Chrome Browser
2) Maximize the current window
3) Implicitly wait for 30 sec
4) Open browser – https://www.seleniumeasy.com/test/basic-radiobutton-demo.html.
5) Find locator of all Radio Buttons
6) Find no of Radio Buttons available and print their values
7) Verify that first Radio button is selected or not and print
8) Find the value of Get Checked Value button and print the value
9) Identify if Radio Button 1 selected or not. If Button 1 already selected, then select Button 2
10) Click on “Get Checked Value” button
11) Find the value of “Get Checked Value” button after selecting the option and print the value
12) Close the browser

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.chrome.ChromeDriver;
 
public class RadioButtonDemo {
            public static void main(String[] args) throws InterruptedException {
 
                        System.setProperty("webdriver.chrome.driver", "src\\test\\resources\\webdrivers\\window\\chromedriver.exe");
 
                        // Initiate Chrome browser
                        WebDriver driver = new ChromeDriver();
 
                        // Maximize the browser
                        driver.manage().window().maximize();
 
                        // Put an Implicit wait and launch URL
                        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
                        driver.get("https://www.seleniumeasy.com/test/basic-radiobutton-demo.html");
 
                        // Find locator of all Radio Buttons
                        List Radio_Options = driver.findElements(By.xpath("//*[@name='optradio']"));
 
                        // Find no of Radio Buttons available and print their values
                        int radioSize = Radio_Options.size();
                        System.out.println("No Of Radio Button Options :" + radioSize);
 
                        for (int i= 0; i< radioSize; i++) {
                                    System.out.println("Name of Radio Button :"+ Radio_Options.get(i).getAttribute("value"));
                        }
 
                        // Create a boolean variable which will hold the value (True/False)
                        boolean radio_value = false;
 
                        // This statement will return True, in case of first Radio button is selected
                        radio_value = Radio_Options.get(0).isSelected();
                        System.out.println("First Radio Option is Checked :" + radio_value);
 
                        // Find the value of "Get Checked Value" button and print the value
                        String preButtonSelected = driver.findElement(By.xpath("//*[@id='easycont']/div/div[2]/div[1]/div[2]/p[3]"))
                                                .getText();
 
                        if (preButtonSelected.isEmpty() == true) {
                                    System.out.println("Get Checked Value before selection is Empty");
                        } else {
                                    System.out.println("Get Checked Value before selection is :" + preButtonSelected);
                        }
                        Thread.sleep(1000);
 
                        // Identify if Radio Button 1 is selected or not. If Button 1 is already
                        // selected, then select Button 2
                        if (radio_value == true) {
                                    Radio_Options.get(1).click();
                                    System.out.println("Button Selected is :"+ Radio_Options.get(1).getAttribute("value"));
                        } else {
                                    Radio_Options.get(0).click();
                                    System.out.println("Button Selected is :"+ Radio_Options.get(0).getAttribute("value"));
                        }
 
                        // Click on "Get Checked Value" button
                        driver.findElement(By.id("buttoncheck")).click();
 
                        // Find the value of "Get Checked Value" button after selecting 
                        // the option and print the value
                        String postButtonSelected = driver.findElement(By.xpath("//*[@id='easycont']/div/div[2]/div[1]/div[2]/p[3]"))
                                                .getText();
                        System.out.println("Get Checked Value is :"+ postButtonSelected);
                        Thread.sleep(1000);
 
                        // Close the browser
                        driver.close();
            }
}

Output
No Of Radio Button Options :2
Name of Radio Button :Male
Name of Radio Button :Female
First Radio Option is Checked :false
Get Checked Value before selection is Empty
Button Selected is :Male
Get Checked Value is :Radio button 'Male' is checked

How to automate BootStrap DropDown using Selenium WebDriver

 
In the previous post, we have already seen How to Handle Dropdowns in Selenium WebDriver . In this post, we will see how to handle Bootstrap Dropdown using Selenium WebDriver.
 
What is Bootstrap?
 
  • Bootstrap is a free front-end framework for faster and easier web development
  • Bootstrap includes HTML and CSS based design templates for typography, forms, buttons, tables, navigation, modals, image carousels and many other, as well as optional JavaScript plugins
  • Bootstrap also gives you the ability to easily create responsive designs
  • Bootstrap is compatible with all modern browsers (Chrome, Firefox, Internet Explorer, Edge, Safari, and Opera)

What is Responsive Web Design?

Responsive web design is about creating web sites, which automatically adjust themselves to look good on all devices, from small phones to large desktops.
Bootstrap dropdowns and interactive dropdowns that are dynamically position and formed using list of ul and li html tags. To know more about Bootstrap, please click here

How to get all the options of a Bootstrap dropdown


Below is an example which will explain how to get all the options of a Bootstrap dropdown.

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.chrome.ChromeDriver;
public class BootStrapDemo {
        public static void main(String[] args) {
 System.setProperty("webdriver.chrome.driver","C:\\Users\\Desktop\\Drivers\\chromedriver_win32\\chromedriver.exe");

          WebDriver driver= new ChromeDriver();
          driver.manage().window().maximize();
          driver.get("https://www.seleniumeasy.com/test/");
          driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);

                // Clicking on Bootstrap Dropdown
               driver.findElement(By.xpath("//*[@id='navbar-brand-centered']/ul[1]/li[1]/a")).click(); 

                // Get the all WebElements inside the dropdown in List  
               List dropdown_list =  driver.findElements(By.xpath("//ul[contains(@class,'dropdown-menu')]//li//a"));

              // Printing the amount of WebElements inside the list
               System.out.println("The Options in the Dropdown are: " + dropdown_list.size());

              // Condition to get the WebElement for list
              for(int i=0; i<dropdown_list.size(); i++)
              {
                   // Printing All the options from the dropdown
                   System.out.println(dropdown_list.get(i).getText());
            }                                                                                       
      }
}

Output
The Options in the Dropdown are: 29
Simple Form Demo
Checkbox Demo
Radio Buttons Demo
Select Dropdown List
Input Form Submit
Ajax Form Submit
JQuery Select dropdown

Here,

1) Open a web page – https://www.seleniumeasy.com/test/
2) Click on BootStrap DropDown – Input Forms by using (“//*[@id=’navbar-brand-centered’]/ul[1]/li[1]/a”
3) Get the all WebElements inside the dropdown in List  by using
(“//ul[contains(@class,’dropdown-menu’)]//li//a”)
4) Print all the options of DropDown using dropdown_list.get(i).getText()

How to select a particular option from Bootstrap dropdown

In the below example, there is a Bootstrap dropdown. I want to
Check if an element – Checkbox Demo is present in the dropdown or not.
If Yes, click on that option.

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.chrome.ChromeDriver;
 
public class BootStrapDemo {
        public static void main(String[] args) {

System.setProperty("webdriver.chrome.driver","C:\\Users\\Desktop\\Drivers\\chromedriver_win32\\chromedriver.exe");

          WebDriver driver= new ChromeDriver();
          driver.manage().window().maximize();
          driver.get("https://www.seleniumeasy.com/test/");
          driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
 
                // Clicking on Bootstrap Dropdown
               driver.findElement(By.xpath("//*[@id='navbar-brand-centered']/ul[1]/li[1]/a")).click(); 
 
                // Get the all WebElements inside the dropdown in List  
               List dropdown_list =  driver.findElements(By.xpath("//ul[contains(@class,'dropdown-menu')]//li//a"));
 
              // Printing the amount of WebElements inside the list
               System.out.println("The Options in the Dropdown are: " + dropdown_list.size());
 
              // Condition to get the WebElement for list
              for(int i=0; i<dropdown_list.size(); i++)
              {
                   // Printing All the options from the dropdown
                   System.out.println(dropdown_list.get(i).getText());                 
// Checking the condition whether option in text "Checkbox Demo" is coming
 
          if(dropdown_list.get(i).getText().contains("Checkbox Demo"))
            {
                 // Clicking if text "Checkbox Demo" is there
                 dropdown_list.get(i).click();
              // Breaking the condition if the condition get satisfied
                 break;
          }
       }
   driver.quit();            
  }
}

OutPut
The Options in the Dropdown are: 29
Simple Form Demo
Checkbox Demo

This program can be re-written by using Enhanced for loop instead of For loop.

getText() can be replaced by getAttribute(“innerHTML”)

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.chrome.ChromeDriver;
 
public class BootStrapDemo {
        public static void main(String[] args) {
 System.setProperty("webdriver.chrome.driver","C:\\Users\\Desktop\\Drivers\\chromedriver_win32\\chromedriver.exe");

          WebDriver driver= new ChromeDriver();
          driver.manage().window().maximize();
          driver.get("https://www.seleniumeasy.com/test/");
          driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
 
                // Clicking on Bootstrap Dropdown
               driver.findElement(By.xpath("//*[@id='navbar-brand-centered']/ul[1]/li[1]/a")).click(); 
 
                // Get the all WebElements inside the dropdown in List  
               List dropdown_list =  driver.findElements(By.xpath("//ul[contains(@class,'dropdown-menu')]//li//a"));
 
              // Printing the amount of WebElements inside the list
               System.out.println("The Options in the Dropdown are: " + dropdown_list.size());
 
              // Condition to get the WebElement using Enhanced For loop
 
               for(WebElement element:dropdown_list)
 
              {
                   // Printing All the options from the dropdown
                   System.out.println(element.getAttribute("innerHTML"));             
 
                  // Checking the condition whether option in text "Checkbox Demo" is coming
       if(element.getAttribute("innerHTML").contains("Checkbox Demo")) 
            {
                 // Clicking if text "Checkbox Demo" is there
                 element.click();
              // Breaking the condition if the condition get satisfied
                 break;
          }
       }
   driver.quit();            
  }
}

TestNG Framework – How to download and install TestNG in Eclipse

HOME

 

In the previous tutorial, we have discussed about what is TestNG and why it is important. In this tutorial, will discuss how can we download and install TestNG in Eclipse and how to use it.

Pre-Requisite 
1) Eclipse should be installed and configure. Please refer Install and Configure to setup Eclipse to your system.

Install/Setup TestNG
1) Launch Eclipse and go to Help option present at the top and select -“Install New Software”.

 
2) A dialog box will appear, click the Add button.
 
 
3) A new dialog box will appear. Mention Name as TestNG and location as “TestNG P2 – https://testng.org/testng-p2-update-siteand click the Add button.
 
 
4) This time we will see TestNG is added to Install dialog box.
 
 
 
5) Accept the terms and condition and then click the “Finish” button.
 
 
6) Once the installation is completed, you will get a message to Restart the Eclipse .Select to Restart the Eclipse
 
7) To verify if TestNG is installed successfully or not, go to Window, select Show View and then Other.
 
 
8) Select Java and see within Java folder, you will see TestNG. This shows that TestNG is successfully installed on the machine.
 
 
Steps to follow to create a TestNG class
 
1) Create a new TestNG class. Right click on Folder where you want to create the TestNG class. Select TestNG and then Create TestNG class as shown in the below image.
 
 
 
2) In the below image, we can see that Source folder is the name of the folder we want to create the class and we can mention the name of the class in Class name. Under annotations, I have checked @BeforeTest and @AfterTest and click the Finish button.
 
 
 
 
3) We can see that the structure of new TestNG class looks like as shown below.
 
 
4) In the below example, we want to navigate to Amazon page and search for Hard Drive.
@BeforeTest : Launch Firefox and direct it to the Base URL
@Test : Search for HardDrive
@AfterTest : Close Firefox browser

import org.testng.annotations.Test;
import org.testng.annotations.BeforeTest;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterTest;

public class TestNG_Demo {

   public WebDriver driver;

   @BeforeTest
    public void beforeTest() {
      
     System.setProperty("webdriver.gecko.driver","C:\\Users\\vibha\\Downloads\\geckodriver-v0.26.0-win64\\geckodriver.exe");
    driver = new FirefoxDriver();
    driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
    driver.manage().window().maximize();
    driver.get("https://www.amazon.com//");
 }

@Test
public void Validation() {
    driver.findElement(By.xpath("//*[@id='twotabsearchtextbox']")).sendKeys("hard drive");
    //XPath for search button
      driver.findElement(By.xpath("//*[@class='nav-input']")).click();
   }

@AfterTest
public void afterTest() {
    driver.quit();
  } 
}

5) To execute this program, we need to Right click and select Run as – TestNG Test.

6) The result will look like something shown below. Here, we can see that Test Case Passed is 1, Failed 0 and Skipped 0.

7) As we know that TestNG also produce HTML Reports. To access the report, go to the Eclipse folder and you can see a folder with name test-output inside the Project where we have created TestNG class. Here, it is  C:\Users\vibha\Downloads\eclipse-workspace\Demo

8) Open ‘emailable-report.html‘, as this is a html report open it with browser. It will look like something below.   TestNG also produce ‘index.html‘ report and it resides in the same test-output folder. This reports gives the link to all the different component of the TestNG reports like Groups& Reporter Output. On clicking these will display detailed descriptions of execution.  

We are done! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!!

TestNG Framework – Introduction to TestNG

Definition of TestNG as per official site –

TestNG is a testing framework inspired from JUnit and NUnit but introducing some new functionalities that make it more powerful and easier to use.

A famous programmer named as “Cedric Beust” developed TestNG. It is distribute under Apache Software License and is easily available to download.
TestNG requires JDK 7 or higher.

Features of TestNG

1)   Report Generation – Selenium does not support report generation. TestNG provides the ability to generate HTML Reports

2)   Support for Annotations – It has inbuilt annotations, like @Test, @BeforeTest, @AfterTest, and soon which makes code more clean. These annotations are strongly typed, so the compiler will flag mistakes right away if any detected in the code.

3)   Grouping of Test Cases – It enable user to group the test cases easily. “Groups” is one annotation of TestNG that can be use in the execution of multiple tests.

4)   Set Test Execution Priority –   It enable user to set execution priorities of the test cases. There is a parameter called “Priority” which is used to execute the methods in a particular order. It also allows user to run the test cases of a particular group.

Let us consider a scenario where we have created two groups such as ‘Smoke’ and ‘Regression’. If we want to execute the test cases in a ‘Regression’ group, then this can only be possible in the TestNG framework. If we want to skip the execution of a particular test case, there is a parameter called (enabled = true or false)

 5)   Support Data Driven Testing –  It provide support to Data Driven testing using @DataProviders

 6)   Powerful Execution Model TestNG does not extend any class. TestNG framework allows user to define the test cases where each test case is independent of other test cases.


 7)   Supports Parallel or Multi Threading Testing – It allow user to run same test cases on 2 different browsers at the same time. 


 8)   Supports Logging It also provides the logging facility for the test. For example during the execution of test case, user wants some information to be log in the console. Information could be any detail depends upon the purpose. Keeping this in mind that we are using Selenium for testing, we need the information that helps the user to understand the test steps or any failure during the test case execution. With the help of TestNG Logs, it is possible to enable logging during the Selenium test case execution.


 9)   Integration with other third party tools – It can be easily integrated with other tools or plugins like build tool Maven, Integrated Development Environment (Eclipse), Selenium, Cucumber and many other.

There are lot more features apart from mentioned above, but I feel these are the most commonly used features in TestNG. 

Maven – How to create a Java project using Command Line

 
 

     In the previous tutorial, we have discussed about How to install Maven on Windows. In this tutorial, we will see how to use Maven to manage a Java project – Create and update the dependencies.

   1) Change current folder to the folder where we want to create the Java project 

   In my case I have my Eclipse Workspace mentioned at the below mentioned path 

    cd C:\Users\vibha\eclipse-workspace\Selenium

  2) Create a Project from Maven Template

This tells Maven to generate a Java project from a Maven template.

mvn archetype:generate

3) We need to mention the number as displayed on your screen in Command Prompt to proceed further. Like here, Choose a folder or apply has 1394, so I have also mentioned 1394 in command prompt.

4) We need to provide again  input in command prompt. This time program wants to know which version we want to use. I prefer to use the latest version. Here, it is 8, so I have selected version 8.

5) We need to provide 2 input here

A) Value of groupId – This serves as the group identifier of your Maven project, it should be in a form similar to Java packages, such as com.Selenium
B) Value of artifactId – This serves as the group-local identifier of my Maven project like MavenProjectFromCMD
C) Value of Version – The initial version of our project. The default is 1.0-SNAPSHOT
D) Value of package – The name of our root package. The default is groupId we have created earlier.
We will notice the INFO message about the properties. If the displayed settings are correct, then just enter Y in :: prompt.

Successful Build – Below screenshot shows that the Maven Project built successfully.

  6) Project Folder Creation – We can see a folder with the name of project – MavenProjectFromCMD in our Eclipse Workspace. In my case, it is                     

    C:\Users\vibha\eclipse-workspace\Selenium\MavenProjectFromCMD

7) Contents of Project Folder – Open folder MavenProjectFromCMD to see the contents of the folder. It should have POM file and src

Method Overloading in Java

HOME

 

What is Method Overloading?

It is a feature that allows a class to have more than one method of same name, but different parameters. Method can be overload if:-

  1. No of parameters are different in two methods
  2. Type of parameters are different
  3. Sequence of parameters are different

Note:- If two methods have same name, same no of parameters, same sequence of parameters and same type of parameters but different return type, then the methods are not overloaded. It will show compile time error.

Why do we need Method Overloading?

If we need to perform same kind of operation with different data inputs, we go for method overloading. Below is an example of addition operation with different inputs to explain method overloading. It is an example of static polymorphism or early binding or compile time binding. Here, binding of method call to its definition happens at compile time.

public class MethodOverloading_Demo {                    
       public void Calculation(int a, float b)   {  
                System.out.println("Sum of 2 numbers :"+(a+b));  
 }  

   //Different type of parameters
   public void Calculation(float x, float y)   {
                   System.out.println("Sum of 2 numbers :"+(x+y));
   }

   //Different number of parameters
   public void Calculation(int i, int j, int k)  {
                   System.out.println("Sum of 3 numbers :"+(i+j+k));
   }

   //Different sequence of parameters
   public void Calculation(float p, int r)  {
                   System.out.println("Sum of 3 numbers :"+(p+r));
   }
          public static void main(String[] args) {
                 MethodOverloading_Demo add = new MethodOverloading_Demo();              
                  //Call overloaded methods
                  add.Calculation(5,12f);
                  add.Calculation(13f,12.0f);
                  add.Calculation(22,33,50);
                  add.Calculation(11f, 10);
           }
 
}

Output
Sum of 2 numbers :17.0
Sum of 2 numbers :25.0
Sum of 3 numbers :105
Sum of 3 numbers :21.0

What is Type Promotion?

When a data type of smaller type, promote to bigger type, it called type promotion.  Suppose a method has double data type and object provides float, then the program works fine. Float will be promote to double.

Let us explain this with an example. In the below example, object has provided float data type, but method has double data type, so there is type promotion.

public class Addition {        
       public void Calculation(int a, int b)  { 
                            System.out.println("Sum of 2 numbers :"+(a+b));
                   }  
                   public void Calculation(int x, double y)   {
                               System.out.println("Sum of 2 numbers :"+(x+y));
                   }     
                   public static void main(String[] args) {
                          Addition add = new Addition();                     
                           //Type Promotion method
                            add.Calculation(5,12);
                            add.Calculation(13,12f);
               }
 
}

Output
Sum of 2 numbers :17
Sum of 2 numbers :25.0

Class and Object in Java

HOME

 

In this blog, we will discuss about Classes and Objects. Java is an Object Oriented Programming language. Class, Objects, Variables, Methods and Constructors are the building blocks of Object Oriented language.

What is a Class?

Class is a user defined template or prototype that used to create objects and define object data types and methods.

What is an Object?

Object is an instance of class. An entity that has state and behavior

Let us consider Phone as the object. The state of Phone is color like grey, black, type like IPhone, Samsung and behavior is calling, sending message, internet browsing.

How to create a class?

To create a class, keyword class is used.

Here, I am creating a class with name Student with variable as Name

public class Student {
          String Name;
}

How to create an Object ?

To create an object, specify class name like Student, object name like stud and use new keyword. 

Student stud = new Student();

Let us create a class and an object of its class and print the value of variable name.

public class Student {
 
          String Name = "Tom";
          public static void main(String[] args) 

          {
                   Student stud = new Student();
                   System.out.println("Name of Student :"+stud.Name);
          }
}
 
Output
Name of Student :Tom

Multiple Objects of a class

We can create multiple objects of a class. In the below example, we have created 2 objects of class Student.

public class Student {
 
          String Name = "Tom";
                public static void main(String[] args)
          {
                          Student stud1 = new Student();
                          Student stud2 = new Student();
                          System.out.println("Name of Student :"+stud1.Name);
                          System.out.println("Name of Student :"+stud2.Name);
              }                          
          }

Output
Name of Student :Tom
Name of Student :Tom

Multiple Classes

We can create a class and then create object of that class in another class. Like, here, we have created a class called Student.java and another class is Student_Demo.java where we will create the object of class Student. This is the better approach than the previous one.

public class Student {
          String Name = "Tom";         
}
public class Student_Test{
          public static void main(String[] args)
          {
                        Student stud = new Student();
                        System.out.println("Name of Student :"+stud.Name);
            }                          
      }

There are multiple ways to initialize the classes and objects

1) Initialize through reference

Here, initializing an object means storing data into the object. Let’s see a simple example where we are going to initialize the object through a reference variable.

public class Student {
          String Name ;
          int Age;
}

public class Student_Test {
      public static void main(String[] args)
          {
                     Student stud = new Student();
                     stud.Name ="Tom";
                     stud.Age=35;       
                     System.out.println("Name of Student :"+stud.Name);
                     System.out.println("Age of Student :"+stud.Age);
              }                          
          }

Output
Name of Student :Tom
Age of Student :35

2) Initializing through method

We are creating the two objects of Student class and initializing the value to these objects by invoking the InsertData() method. Here, we are displaying the state (data) of the objects by invoking the DisplayData() method.

public class Student {
	String Name;
	int Age;

	void InsertData(String n, int a) {
		Name = n;
		Age = a;
	}

	void DisplayData() {
		System.out.println("Name of Student :" + Name);
		System.out.println("Age of Student :" + Age);
	}
}

public class Student_Test {
	public static void main(String[] args) {
		Student stud = new Student();
		stud.InsertData("Tom", 34);
		stud.DisplayData();
	}
}

Output
Name of Student :Tom
Age of Student :34

We can create multiple objects

public class Student {
          String Name ;
          int Age;

          void InsertData(String n, int a)
          {
                   Name =n;
                   Age = a;
          }

          void DisplayData()
          {
                   System.out.println("Name of Student :"+Name);
                   System.out.println("Age of Student :"+Age);
          }
    }  

public class Student_Test {
          public static void main(String[] args)
          {
                     Student stud1 = new Student();
                     Student stud2 = new Student();
                     stud1.InsertData("Tom",34);
                     stud1.DisplayData();  
                     stud2.InsertData("Terry",36);        
                     stud2.DisplayData();
              }                          
          }

Output
Name of Student :Tom
Age of Student :34
Name of Student :Terry
Age of Student :36