Most commonly used Java methods and utilities for Selenium Automation

Below is an exclusive list of  Java methods and utilities most commonly used in Selenium Automation Frameworks. These methods could be used in different scenarios while you are developing automation frameworks for any web application using Selenium and Java.

1. Collections.sort() method: It is used to sort the elements presents in the specified list of collection in ascending order.

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class SortLists{
    public static void main(String[] args){
        List<String> categories = new ArrayList<>();
        categories.add("Selenium");
        categories.add("UFT");
        categories.add("TestComplete");
        System.out.println("List before sorting: \n"+categories);
        Collections.sort(categories);
        System.out.println("List after sorting: \n"+categories);

    }
}

Output:

List before sorting: 
[Selenium, UFT, TestComplete]
List after sorting: 
[Selenium, TestComplete, UFT]

2. List equals() method: This method is used to compare two lists. It compares the lists as, both lists should have the same size, and all corresponding pairs of elements in the two lists are equal.

import java.util.ArrayList;
import java.util.List;
public class CompareLists{
    public static void main(String[] args){
        List<String> expectedCategories = new ArrayList<>();
        expectedCategories.add("Selenium");
        expectedCategories.add("UFT");
        expectedCategories.add("TestComplete");
        List<String> actualCategories = new ArrayList<>();
        expectedCategories.add("Java");
        expectedCategories.add("C#");
        expectedCategories.add(".Net");
        boolean isEqual = expectedCategories.equals(actualCategories);      
        if(isEqual){
            System.out.println("Lists are equal");
        } else{
            System.out.println("Lists are not equal");
        }
    }
}

OUTPUT:
Lists are not equal

3. Properties getProperty(key) method: The getProperty(key) method of Properties class is used to get the value mapped to this key, passed as the parameter, in this Properties object. This method will fetch the corresponding value to this key, if present, and return it. If there is no such mapping, then it returns null.

Properties file:

application.url = https://qascript.com
public class GetFromProperties{
    public static void main(String[] args) {
        Properties properties = new Properties();
        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream("src/test/resources/config/application.properties");
            properties.load(fileInputStream);
            String url = properties.getProperty("application.url");
            System.out.println("Application URL obtained from properties file: " + url);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

OUTPUT:
Application URL obtained from properties file: https://qascript.com/

4. String trim() method: It is a built-in function that eliminates leading and trailing spaces.

public class TrimSpaces{
    public static void main(String[] args) {
        String s = " Welcome to QAScript ";
        System.out.println(s.trim());
    }
}

OUTPUT:
Welcome to QAScript

5. String toLowercase() method: This method converts all characters of the string into lowercase letter.

public class CovertToLower {

    public static void main(String[] args) {

        String s = "Welcome to QAScript";
        System.out.println(s.toLowerCase());
    }
}

OUTPUT:
welcome to qascript

6. String startsWith(String prefix) method:This method tests if a string starts with the specified prefix beginning from 1st index.

startsWith(String prefix, int strt_pos): This method tests if a string starts with the specified prefix beginning a specified index.

public class TestStartsWith{
    public static void main(String[] args) {
        String s = "Welcome to QAScript";
        System.out.println(s.startsWith("QA"));
        System.out.println(s.startsWith("QA",11));
    }
}

OUTPUT:
false
true

7. String contains(CharSequence s) method: This method searches the sequence of characters in the given string. It returns true if sequence of char values are found in this string otherwise returns false.

public class TestContains {
    public static void main(String[] args) {
        String s = "Welcome to QAScript";
        System.out.println(s.contains("QA"));
        System.out.println(s.contains("Testing"));
    }
}

OUTPUT:
true
false

8. String substring(int beginIndex) method: It returns a new string that is a substring of this string. The substring begins with the character at the specified index and extends to the end of this string.

substring(int beginIndex,int endIndex): It returns a new string that is a substring of this string. The substring begins with the character at the specified index and extends to the end of this string or up to endIndex – 1.

public class TestSubstring{

    public static void main(String[] args) {
        String s = "Welcome to QAScript";
        System.out.println(s.substring(11));
        System.out.println(s.substring(0,8));
    }
}

OUTPUT:
QAScript
Welcome

9. String indexOf(String str) method: This method returns the index within this string of the first occurrence of the specified character or -1, if the character does not occur.

public class TestIndexof{
    public static void main(String[] args) {
        String s = "Welcome to QAScript";
        System.out.println(s.indexOf("QA"));
        System.out.println(s.indexOf("Z"));
    }
}

10. String equalsIgnoreCase(String anotherString) method: This method compares two strings, ignoring lower case and upper case differences. This method returns true if the strings are equal, and false if not.

public class TestIgnoreCase{

    public static void main(String[] args) {
        String s1 = "Welcome to QAScript";
        String s2 = "welcome to qascript";
        System.out.println(s1.equalsIgnoreCase(s2));
    }
}

Output:
true

 

11. DateFormat format() method: The format() Method of DateFormat class in Java is used to format a given date into Date/Time string. It is used to convert this date and time into a particular format i.e., mm/dd/yyyy.

public static void main(String[] args) {
        Date date = Calendar.getInstance().getTime();
        DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
        String today = dateFormat.format(date);
        System.out.println(today);
}

OUTPUT:
17/06/2020

12. daysFromCurrentDate utility: This common utility will add or subtract days from the current date.

public static String daysFromCalendarDate(int offsetInDays, String dateFormat){
    Calendar calendar= Calendar.getInstance();
    calendar.add(Calendar.DAY_OF_MONTH, offsetInDays);
    SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
    String newDate = sdf.format(calendar.getTime());
    return newDate;
}

Ex:
String date = CommonUtils.daysFromCalendarDate(4, "yyyy-MM-dd");
System.out.println(date);

Output:
2020-06-26

13. getLastWorkingDayOfPrevMonth utility: It will return the last working day of the previous month.

public static String getLastWorkingDayOfPrevMonth(String strDateFormat){
        SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.MONTH,-1);
        int lastDate = cal.getActualMaximum(Calendar.DATE);
        cal.set(Calendar.DATE,lastDate);
        int lastDay = cal.get(Calendar.DAY_OF_WEEK);
        switch(lastDay){
            case 1:
                cal.add(Calendar.DAY_OF_MONTH,-2);
                return sdf.format(cal.getTime());
            case 2:
                cal.add(Calendar.DAY_OF_MONTH,-1);
                return sdf.format(cal.getTime());
            default:
                return sdf.format(cal.getTime());
        }
    }

EXAMPLE: 
String date1 = CommonUtils.getLastWorkingDayOfPrevMonth("yyyy-MM-dd");
System.out.println(date1);

OUTPUT:
2020-05-29

14. getLastWorkingDayOfPrevYear utility: It will return the last working day of the previous year.

public static String getLastWorkingDayOfPrevYear(String strDateFormat){
        SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.YEAR,-1);
        cal.set(Calendar.MONTH,11);
        cal.set(Calendar.DAY_OF_MONTH,31);
        int lastDay = cal.get(Calendar.DAY_OF_WEEK);
        switch(lastDay){
            case 1:
                cal.add(Calendar.DAY_OF_MONTH,-2);
                return sdf.format(cal.getTime());
            case 2:
                cal.add(Calendar.DAY_OF_MONTH,-1);
                return sdf.format(cal.getTime());
            default:
                return sdf.format(cal.getTime());
        }
    }

EXAMPLE:
String date2 = CommonUtils.getLastWorkingDayOfPrevYear("yyyy-MM-dd");
System.out.println(date2);

OUTPUT:
2019-12-31

15. isStringPresentInArray utility: This common utility will check if the input string is present in an Array and return a boolean result.

public boolean isStringPresentInArray(String[] array,String strValue,boolean ignoreCase, boolean ignoreSpace){
        for(String str: array){
            if(ignoreSpace){
                str= str.trim();
                strValue = strValue.trim();
            }
            if(ignoreCase){
                str= str.toLowerCase();
                strValue = strValue.toLowerCase();
            }
            if(strValue.equals(str))
                return true;
        }
        return false;
    }

16. convertToIntegerArray utility: This common utility will convert any List type to Integer type Array List.

public static List<String> convertToIntegerArray(List<Object> list){
     List<Integer> newList = new ArrayList<>();
     for(Object element: list)
        newList.add((Integer) element);
     return newLsist;
}

 

Please follow and like us:
Share

Bijan Patel

Founder & Creator of QAScript | 12+ years of IT Experience | Full Stack Automation Engineer | Blogger | Trainer

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

error: Content is protected !!