Framework project SuitCRM - Notes By ShariqSP

Framework project SuitCRM

SuiteCRM Overview

SuiteCRM is an open-source Customer Relationship Management (CRM) software designed to help businesses of all sizes manage their customer interactions, sales, and marketing efforts effectively. With its open-source foundation, SuiteCRM allows for high customization, making it adaptable to various industries and business needs. It is a popular alternative to proprietary CRM solutions due to its flexibility, scalability, and cost-effectiveness.

Installation and Configuration

Installing and configuring SuiteCRM requires a few key steps, including setting up a web server, database, and SuiteCRM files.

  1. Server Requirements:
    • Operating System: Compatible with Windows, Linux, or MacOS.
    • Web Server: Apache or Nginx (recommended).
    • PHP: Version 7.3 - 7.4 (check SuiteCRM's documentation for the latest compatibility).
    • Database: MySQL, MariaDB, or MSSQL.
  2. Download SuiteCRM:

    Visit the SuiteCRM Download page and download the latest version of the SuiteCRM package.

  3. Upload and Extract Files:

    Upload the SuiteCRM package to your web server's root directory (e.g., `/var/www/html/` for Apache) and extract it:

    tar -xzvf SuiteCRM-X.X.X.tar.gz -C /var/www/html/
  4. Set Directory Permissions:

    Ensure that the web server has appropriate permissions for the SuiteCRM directory:

    sudo chown -R www-data:www-data /var/www/html/suitecrm

    This allows SuiteCRM to read, write, and modify necessary files.

  5. Create a Database:

    Log in to your MySQL or MariaDB server and create a new database and user for SuiteCRM:

    
            CREATE DATABASE suitecrm_db;
            CREATE USER 'suitecrm_user'@'localhost' IDENTIFIED BY 'your_password';
            GRANT ALL PRIVILEGES ON suitecrm_db.* TO 'suitecrm_user'@'localhost';
            FLUSH PRIVILEGES;
                        
  6. Run the Installation Wizard:

    Navigate to SuiteCRM's directory in your browser (e.g., `http://yourserver/suitecrm`). Follow the installation wizard steps, enter the database details, and complete the setup.

  7. Post-Installation Configuration:

    After installation, configure SuiteCRM’s settings, such as email, user roles, and access permissions.

Features of SuiteCRM

SuiteCRM offers a range of robust features designed to help businesses manage customer relationships, streamline workflows, and enhance collaboration. Here’s a detailed overview of its features:

  • Sales Management:

    Track and manage sales processes from lead acquisition to deal closure. SuiteCRM includes tools for pipeline management, sales forecasting, and customer segmentation.

  • Marketing Automation:

    Helps in planning, executing, and tracking marketing campaigns. SuiteCRM includes tools for email marketing, campaign ROI analysis, and segmentation, allowing businesses to engage with the right audience.

  • Customer Support:

    Manage and track customer service cases, providing a full view of customer issues. Includes case management, knowledge base, and portal access for better customer support.

  • Workflow Automation:

    Automate repetitive tasks and workflows, allowing users to focus on high-value tasks. Workflow automation in SuiteCRM can be configured for notifications, task assignments, and approval processes.

  • Reporting and Analytics:

    SuiteCRM’s reporting and dashboard tools provide insights into customer data, sales metrics, and campaign effectiveness, helping businesses make data-driven decisions.

  • Custom Modules and Field Management:

    Customize modules and fields to match business requirements. SuiteCRM allows for adding, editing, and managing modules, as well as customizing views for better usability.

  • Role-based Access Control:

    Manage user permissions with role-based access control, ensuring data security and preventing unauthorized access.

  • Mobile Access:

    SuiteCRM is mobile-responsive, allowing users to access CRM functionalities on mobile devices.

  • Integrations:

    SuiteCRM supports various integrations with external services, such as email, telephony, and ERP systems, enhancing its functionality.

Explanation of the Maven Configuration for SuiteCRM Selenium Framework

pom.xml File

                <project xmlns="http://maven.apache.org/POM/4.0.0"
                         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
                    <modelVersion>4.0.0</modelVersion>
        
                    <groupId>com.SuitCRMApp</groupId>
                    <artifactId>SuiteCRM_Selenium_Framework</artifactId>
                    <version>1.0-SNAPSHOT</version>
        
                    <properties>
                        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
                        <maven.compiler.source>1.8</maven.compiler.source>
                        <maven.compiler.target>1.8</maven.compiler.target>
                    </properties>
        
                    <dependencies>
                        <dependency>
                            <groupId>commons-io</groupId>
                            <artifactId>commons-io</artifactId>
                            <version>2.12.0</version>
                        </dependency>
                        
                        <dependency>
                            <groupId>org.seleniumhq.selenium</groupId>
                            <artifactId>selenium-java</artifactId>
                            <version>4.21.0</version>
                        </dependency>
        
                        <dependency>
                            <groupId>org.apache.logging.log4j</groupId>
                            <artifactId>log4j-api</artifactId>
                            <version>2.20.0</version>
                        </dependency>
        
                        <dependency>
                            <groupId>org.apache.logging.log4j</groupId>
                            <artifactId>log4j-core</artifactId>
                            <version>2.20.0</version>
                        </dependency>
        
                        <dependency>
                            <groupId>io.github.bonigarcia</groupId>
                            <artifactId>webdrivermanager</artifactId>
                            <version>5.8.0</version>
                        </dependency>
        
                        <dependency>
                            <groupId>com.mysql</groupId>
                            <artifactId>mysql-connector-j</artifactId>
                            <version>8.1.0</version>
                        </dependency>
        
                        <dependency>
                            <groupId>com.google.code.gson</groupId>
                            <artifactId>gson</artifactId>
                            <version>2.8.9</version>
                        </dependency>
        
                        <dependency>
                            <groupId>com.googlecode.json-simple</groupId>
                            <artifactId>json-simple</artifactId>
                            <version>1.1.1</version>
                        </dependency>
        
                        <dependency>
                            <groupId>org.testng</groupId>
                            <artifactId>testng</artifactId>
                            <version>7.7.0</version>
                            <scope>test</scope>
                        </dependency>
        
                        <dependency>
                            <groupId>org.assertj</groupId>
                            <artifactId>assertj-core</artifactId>
                            <version>3.24.2</version>
                        </dependency>
        
                        <dependency>
                            <groupId>org.apache.commons</groupId>
                            <artifactId>commons-lang3</artifactId>
                            <version>3.12.0</version>
                        </dependency>
        
                        <dependency>
                            <groupId>com.aventstack</groupId>
                            <artifactId>extentreports</artifactId>
                            <version>5.0.9</version>
                        </dependency>
        
                        <dependency>
                            <groupId>com.fasterxml.jackson.core</groupId>
                            <artifactId>jackson-databind</artifactId>
                            <version>2.15.2</version>
                        </dependency>
        
                        <dependency>
                            <groupId>org.slf4j</groupId>
                            <artifactId>slf4j-api</artifactId>
                            <version>1.7.36</version>
                        </dependency>
        
                        <dependency>
                            <groupId>org.slf4j</groupId>
                            <artifactId>slf4j-simple</artifactId>
                            <version>1.7.36</version>
                        </dependency>
        
                        <dependency>
                            <groupId>org.apache.poi</groupId>
                            <artifactId>poi</artifactId>
                            <version>5.2.3</version>
                        </dependency>
        
                        <dependency>
                            <groupId>org.apache.poi</groupId>
                            <artifactId>poi-ooxml</artifactId>
                            <version>5.2.3</version>
                        </dependency>
                    </dependencies>
        
                    <build>
                        <plugins>
                            <plugin>
                                <groupId>org.apache.maven.plugins</groupId>
                                <artifactId>maven-surefire-plugin</artifactId>
                                <version>3.0.0-M5</version>
                                <configuration>
                                    <includes>
                                        <include>**/*Test.java</include>
                                    </includes>
                                </configuration>
                            </plugin>
                        </plugins>
                    </build>
                </project>
            

Explanation of Each Part

This Maven configuration file (pom.xml) sets up the SuiteCRM Selenium Framework for testing. It includes project metadata, build properties, dependencies, and a build configuration:

  • Project Metadata: Defines essential project information, including group ID, artifact ID, and version.
  • Properties: Sets the source and target compatibility to Java 1.8 and uses UTF-8 encoding.
  • Dependencies: A comprehensive set of libraries for logging (Log4j), database connectivity (MySQL), Selenium for UI testing, JSON processing, and Apache POI for Excel handling, among others.
  • Build Configuration: Configures the Maven Surefire plugin to execute all test classes that follow the naming convention ending in *Test.java.

This configuration optimizes the SuiteCRM Selenium Framework for testing and reporting, supporting data handling, logging, and reporting across various functionalities.

Commons IO

Group ID: commons-io
Artifact ID: commons-io
Version: 2.12.0

Commons IO is an Apache library that provides utility classes to handle file and input/output (I/O) operations. It simplifies tasks like reading/writing files, copying, and managing directories, which are often needed for handling data files or log files during test executions.

Selenium Java

Group ID: org.seleniumhq.selenium
Artifact ID: selenium-java
Version: 4.21.0

Selenium Java is a core library for automating web browsers, allowing testers to perform automated UI testing of web applications. It provides the APIs necessary to interact with web elements, execute scripts, and control browsers in various environments, essential for end-to-end testing.

Log4j2 (API and Core)

Group ID: org.apache.logging.log4j
Artifact IDs: log4j-api, log4j-core
Version: 2.20.0

Log4j2 is a powerful logging framework from Apache that provides APIs for logging messages. It’s used to record events during test execution, making it easy to trace and debug issues. The API handles logging functionality, while the Core provides the actual logging implementations.

WebDriverManager

Group ID: io.github.bonigarcia
Artifact ID: webdrivermanager
Version: 5.8.0

WebDriverManager simplifies the management of WebDriver binaries for browsers like Chrome, Firefox, and others. Instead of manually setting driver paths, this library automatically downloads the required binaries, helping tests run on the latest supported browser versions.

MySQL Connector

Group ID: com.mysql
Artifact ID: mysql-connector-j
Version: 8.1.0

The MySQL Connector/J is a Java library for connecting Java applications to MySQL databases. It’s crucial in scenarios where test cases interact with a database, such as validating data persistence, retrieving test data, or verifying database states post-testing.

Gson and JSON Simple

Group ID: com.google.code.gson / com.googlecode.json-simple
Artifact IDs: gson / json-simple
Versions: 2.8.9 / 1.1.1

Gson and JSON Simple are libraries for parsing and handling JSON data. They allow the SuiteCRM Selenium Framework to serialize/deserialize JSON objects, a useful feature when interacting with RESTful APIs or reading data from JSON files in test cases.

TestNG

Group ID: org.testng
Artifact ID: testng
Version: 7.7.0

TestNG is a testing framework inspired by JUnit, designed to simplify testing setups. It offers a range of features like parallel execution, dependency testing, and data-driven testing, making it an ideal choice for automated test cases.

AssertJ

Group ID: org.assertj
Artifact ID: assertj-core
Version: 3.24.2

AssertJ provides fluent assertion methods for Java testing, allowing test code to read more naturally. It’s used for more powerful and readable assertions, making test validation statements easier to write and understand.

Apache Commons Lang

Group ID: org.apache.commons
Artifact ID: commons-lang3
Version: 3.12.0

Apache Commons Lang extends Java’s standard libraries by providing utilities for handling strings, numbers, objects, and dates. This library is often used to simplify common tasks within test code.

ExtentReports

Group ID: com.aventstack
Artifact ID: extentreports
Version: 5.0.9

ExtentReports is a reporting library that produces HTML reports of test execution. It includes details on pass/fail statuses, screenshots, and logs, making it useful for sharing results with stakeholders.

Jackson Databind

Group ID: com.fasterxml.jackson.core
Artifact ID: jackson-databind
Version: 2.15.2

Jackson Databind is used for JSON processing and helps in reading and writing JSON content. This is especially helpful for data-driven testing, as it enables interaction with complex JSON structures.

SLF4J

Group ID: org.slf4j
Artifact IDs: slf4j-api, slf4j-simple
Version: 1.7.36

The Simple Logging Facade for Java (SLF4J) is a logging abstraction for Java. By decoupling logging from specific libraries, SLF4J allows the choice of any logging framework, making it a versatile addition to any testing framework.

Apache POI

Group ID: org.apache.poi
Artifact IDs: poi, poi-ooxml
Version: 5.2.3

Apache POI provides libraries to read and write Microsoft Office files, including Excel. For test automation, this is used to manage test data stored in Excel, allowing the framework to interact with spreadsheets for data-driven tests.

Maven Surefire Plugin

Group ID: org.apache.maven.plugins
Artifact ID: maven-surefire-plugin
Version: 3.0.0-M5

The Maven Surefire Plugin is used to run unit tests in the Maven environment. In this configuration, it’s set up to execute all test classes that end with *Test.java, ensuring consistent and automated test execution.

Access to the SuiteCRM Selenium Framework Code

The entire code for the SuiteCRM Selenium testing framework is available on GitHub. This repository contains the basic framework that has been carefully developed to support Selenium-based testing for SuiteCRM applications. It includes configurations, dependencies, plugins, and key code files essential for setting up and running automated tests on SuiteCRM.

Anyone interested in using or building upon this framework can clone or download it from the following GitHub link: https://github.com/ShariqSp/SuiteCRM.git

Feel free to explore and continue working on the framework to enhance its capabilities or adapt it to your project’s requirements.

Importing the SuiteCRM Selenium Framework Project into Eclipse

Follow the steps below to import the SuiteCRM Selenium Framework into your Eclipse IDE:

  1. Clone or Download the Project: Start by cloning the project from GitHub or downloading it as a ZIP file:
  2. Open Eclipse: Launch Eclipse and go to the Workspace where you want to import the project.
  3. Import as a Maven Project:
    • In Eclipse, navigate to File > Import.
    • Select Maven > Existing Maven Projects and click Next.
    • In the next window, browse to the location of your cloned or extracted project folder.
    • Eclipse should automatically detect the pom.xml file. Select the project and click Finish.
  4. Resolve Dependencies: Eclipse will automatically download all required dependencies as specified in the pom.xml file. Wait for the download to complete.
  5. Project is Ready: Once all dependencies are resolved, the project should be ready for use. You can begin running or editing test scripts within Eclipse.

By following these steps, you’ll have the SuiteCRM Selenium Framework set up in your Eclipse environment and ready for development or testing.

Understanding the MySQL Database Utility Code

This section explains the functionality of the Java code in mySQLDatabaseUtility, which is designed to interact with a MySQL database, specifically for inserting data into a specified table. This code provides a basic setup for connecting to a MySQL database and performing an insert operation using JDBC.

Code Overview

package com.scrm.generic.databaseUtility;
        
        import java.sql.Connection;
        import java.sql.DriverManager;
        import java.sql.PreparedStatement;
        import java.sql.SQLException;
        
        public class mySQLDatabaseUtility 
        {
            // Database URL, Username, and Password
            private static final String URL = "jdbc:mysql://localhost:3306/suitecrm";
            private static final String USER = "root";
            private static final String PASSWORD = "";
        
            public static void main(String[] args) throws ClassNotFoundException {
                insertData("Shariq",12234);
            }
            
            // Method to insert data
            public static void insertData(String name, int age) throws ClassNotFoundException {
                Class.forName("com.mysql.cj.jdbc.Driver");
        
                String insertQuery = "INSERT INTO users_dummy (name, age) VALUES (?, ?)";
                try (Connection connection = DriverManager.getConnection(URL, USER, PASSWORD);
                     PreparedStatement preparedStatement = connection.prepareStatement(insertQuery)) {
                    preparedStatement.setString(1, name);
                    preparedStatement.setInt(2, age);
                    int rowsInserted = preparedStatement.executeUpdate();
                    if (rowsInserted > 0) {
                        System.out.println("Data inserted successfully!");
                    }
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }

Explanation of Each Component

1. Package Declaration and Imports

The code belongs to the package com.scrm.generic.databaseUtility. The necessary imports for SQL operations are included:

  • java.sql.Connection - Manages the database connection.
  • java.sql.DriverManager - Establishes a connection to the database.
  • java.sql.PreparedStatement - Allows pre-compiling SQL statements with placeholders for efficiency and security.
  • java.sql.SQLException - Handles SQL-related exceptions.

2. Database Connection Details

The constants URL, USER, and PASSWORD specify the connection details for the MySQL database:

  • URL: Specifies the JDBC URL for the MySQL database hosted on localhost with the database name suitecrm.
  • USER and PASSWORD: Credentials for accessing the database. Here, root is the username, and an empty string is used for the password.

3. Main Method

The main method calls insertData() with sample values to test the functionality. Here, the values "Shariq" (String) and 12234 (Integer) are passed as arguments.

4. The insertData Method

The insertData method is a static method that takes two parameters:

  • name: Represents a String value to be inserted into the name column.
  • age: Represents an int value to be inserted into the age column.
The method performs the following actions:
  • Load the MySQL Driver: Class.forName("com.mysql.cj.jdbc.Driver") loads the MySQL JDBC driver.
  • SQL Insert Statement: Defines an SQL statement to insert values into the users_dummy table with placeholders (?, ?) for parameterized values.
  • Establish a Connection: Uses DriverManager.getConnection() with the URL, USER, and PASSWORD constants to establish a connection.
  • Prepare and Execute Statement: The PreparedStatement sets the values for the placeholders:
    • setString(1, name): Sets the first placeholder to the name parameter.
    • setInt(2, age): Sets the second placeholder to the age parameter.
  • Execute Update: Executes the executeUpdate() method, which returns the number of rows affected. A success message prints if rows are inserted successfully.

5. Exception Handling

SQL exceptions are handled in a try-catch block. If an SQLException occurs, e.printStackTrace() prints the stack trace to the console for debugging.

Usage

To use this utility, modify the URL, USER, and PASSWORD to match your database configuration and call the insertData method with the desired values.

Understanding Variables and Methods in the readExcelFile Program

This Java program demonstrates reading data from an Excel file and converting it into a 2D array using the Apache POI library. Below is a detailed explanation of the key variables and methods used in the program, along with the program code.

Program Code


        package com.scrm.generic.fileutility;
        
        import java.io.File;
        import java.io.IOException;
        import java.util.ArrayList;
        
        import org.apache.poi.EncryptedDocumentException;
        import org.apache.poi.ss.usermodel.Cell;
        import org.apache.poi.ss.usermodel.Row;
        import org.apache.poi.ss.usermodel.Sheet;
        import org.apache.poi.ss.usermodel.Workbook;
        import org.apache.poi.ss.usermodel.WorkbookFactory;
        
        public class readExcelFile 
        {
            public static Object[][] convertTo2DArray(ArrayList> listOfLists) {
                int rows = listOfLists.size();
                Object[][] array = new Object[100][100];
        
                for (int i = 0; i < rows; i++) {
                    ArrayList rowList = listOfLists.get(i);
                    int cols = listOfLists.get(i).size();  
                    for (int j = 0; j < cols; j++) {
                        array[i][j] = rowList.get(j);
                    }
                }
        
                return array;
            }
        
            public static Object[][] readExcelData(String Path) throws EncryptedDocumentException, IOException
            {
                ArrayList> data = new ArrayList>();
                File f = new File(Path);
                Workbook wb = WorkbookFactory.create(f); 
                Sheet sh = wb.getSheet("AccountsNew");
                int rowNum = sh.getPhysicalNumberOfRows();
                for(int i = 0; i < rowNum; i++) {
                    ArrayList arr = new ArrayList();
                    int col = sh.getRow(i).getPhysicalNumberOfCells();
                    for(int j = 0; j < col; j++) {
                        arr.add(sh.getRow(i).getCell(j) + "");
                    }
                    data.add(arr);
                    arr = null;
                }
                Object[][] o = convertTo2DArray(data);
                return o;
            }
        
            public static String[] getRow(String path, int rowNo) throws Exception, IOException
            {
                ArrayList> data = new ArrayList>();
                File f = new File(path);
                Workbook wb = WorkbookFactory.create(f); 
                Sheet sh = wb.getSheet("AccountsNew");
                Row rowData = sh.getRow(rowNo);
                String[] str = new String[rowData.getPhysicalNumberOfCells()];
                int j = 0;
                for(Cell i : rowData)
                    str[j++] = i + " ";
                return str;
            }
        }
            

Variables

  • ArrayList<ArrayList<String>> data: This is a two-dimensional ArrayList used to store the contents of the Excel sheet. Each inner ArrayList represents a row of the Excel sheet, and the outer ArrayList stores all the rows.
  • File f: Represents the Excel file to be read. It is initialized with the file path provided as an argument to the methods.
  • Workbook wb: This variable represents the Excel workbook. It is created using WorkbookFactory.create(f), which opens the file.
  • Sheet sh: Refers to the specific sheet in the workbook. In this case, the program works with a sheet named "AccountsNew".
  • int rowNum: Stores the number of rows present in the sheet. It is retrieved using sh.getPhysicalNumberOfRows().
  • int col: Represents the number of columns (cells) in a specific row. It is calculated using sh.getRow(i).getPhysicalNumberOfCells().
  • Object[][] array: A 2D object array used to store the data read from the Excel sheet in the method convertTo2DArray.
  • String[] str: An array used in the getRow method to store the data of a specific row in string format.

Methods

convertTo2DArray(ArrayList<ArrayList<String>> listOfLists)

This method converts a two-dimensional ArrayList into a 2D object array. It iterates through the rows and columns of the input ArrayList and stores each element in a 2D object array.

  • int rows = listOfLists.size();: Determines the number of rows in the listOfLists.
  • Object[][] array = new Object[100][100];: Initializes a 2D object array with a size of 100x100 (can be adjusted based on the data).
  • for (int i = 0; i < rows; i++): Iterates through each row of the listOfLists.
  • rowList.get(j): Retrieves the value at column j in row i of the listOfLists.

readExcelData(String Path)

This method reads data from an Excel file and returns it as a 2D object array. It uses the Apache POI library to read the workbook, sheet, rows, and cells.

  • File f = new File(Path);: Creates a new File object with the given file path.
  • Workbook wb = WorkbookFactory.create(f);: Opens the Excel file and creates a workbook instance.
  • Sheet sh = wb.getSheet("AccountsNew");: Retrieves the sheet named "AccountsNew" from the workbook.
  • for (int i = 0; i < rowNum; i++): Loops through each row in the sheet.
  • for (int j = 0; j < col; j++): Loops through each cell in the row and adds its value to the ArrayList.
  • Object[][] o = convertTo2DArray(data);: Converts the 2D ArrayList into a 2D object array and returns it.

getRow(String path, int rowNo)

This method reads a specific row from an Excel sheet and returns its data as a string array. The row is identified by its row number, and the method returns the data in string format.

  • Row rowData = sh.getRow(rowNo);: Retrieves the row at the specified index from the sheet.
  • for (Cell i : rowData): Iterates through each cell in the row.
  • str[j++] = i + " ";: Converts the cell value to a string and stores it in the str array.

Understanding Variables and Methods in the readFromJson Program

This Java program demonstrates reading data from a JSON file and retrieving a value based on a provided key. The program utilizes the org.json.simple library to parse the JSON data. Below is a detailed explanation of the key variables and methods used in the program, along with the program code.

Program Code


        package com.scrm.generic.fileutility;
        
        import java.io.FileNotFoundException;
        import java.io.FileReader;
        import java.io.IOException;
        
        import org.json.simple.JSONObject;
        import org.json.simple.parser.JSONParser;
        import org.json.simple.parser.ParseException;
        
        public class readFromJson 
        {
            /**
             * 
             * @param Path : enter the path to json object file
             * @param key : enter the key you want to retrieve
             * @return value in String format
             * @throws ParseException
             * @throws FileNotFoundException
             * @throws IOException
             */
            public static String readFromJsonFile(String Path, String key) throws ParseException, FileNotFoundException, IOException
            { 
                // Parsing the JSON file
                Object obj = new JSONParser().parse(new FileReader(Path)); 
                
                // Typecasting obj to JSONObject
                JSONObject jo = (JSONObject) obj; 
                
                // Retrieving the value for the specified key
                String name = (String) jo.get(key); 
                return name;
            }
        }
            

Variables

  • Object obj: This variable stores the parsed JSON object after reading the JSON file. It is initialized using the JSONParser().parse() method.
  • JSONParser parser: An instance of the JSONParser class, which is used to parse the contents of the JSON file and convert it into a JSON object.
  • JSONObject jo: This variable holds the actual JSON object after typecasting the parsed Object to a JSONObject. It allows access to the JSON data structure for further operations.
  • String name: Stores the value associated with the specified key. This value is retrieved by calling the jo.get(key) method, which accesses the key-value pair in the JSON object.

Methods

readFromJsonFile(String Path, String key)

This method reads data from a JSON file and retrieves the value associated with the specified key. The method uses JSONParser to parse the JSON file and JSONObject to access the key-value pairs in the file.

  • Object obj = new JSONParser().parse(new FileReader(Path));: Reads the file from the specified Path and parses it into a JSON object. The parse() method converts the JSON data into a format that can be processed in Java.
  • JSONObject jo = (JSONObject) obj;: Typecasts the parsed object into a JSONObject to allow access to key-value pairs in the JSON structure.
  • String name = (String) jo.get(key);: Retrieves the value for the specified key from the JSON object. The value is stored as a string.
  • return name;: Returns the value associated with the specified key in string format.

Exception Handling

The method also includes exception handling for various potential issues:

  • ParseException: Thrown if the JSON file cannot be parsed correctly.
  • FileNotFoundException: Thrown if the specified JSON file cannot be found at the provided path.
  • IOException: Thrown in case of an input/output error while reading the file.

Understanding Variables and Methods in the readPropertyFile Program

This Java program is designed to read configuration data from a properties file, typically used in software applications to store settings such as URLs, usernames, passwords, and other application-specific configurations. The program uses the java.util.Properties class to load and access the property values. Below is a detailed explanation of the key variables and methods used in the program, along with the program code.

Program Code


        package com.scrm.generic.fileutility;
        
        import java.io.FileInputStream;
        import java.io.IOException;
        import java.util.Properties;
        
        public class readPropertyFile 
        {
            private String userName;
            private String userpassword;
            private String url;
            private String browser;
        
            // Default constructor to load properties from a fixed file path
            public readPropertyFile() throws IOException
            {
                String propFile = "./resourceFiles/appProperties.properties";
                FileInputStream fis = new FileInputStream(propFile);
                Properties pos = new Properties();
                pos.load(fis);
                userName = pos.getProperty("username");
                userpassword = pos.getProperty("password");
                url = pos.getProperty("url");
                browser = pos.getProperty("browser"); 
            }
        
            // Constructor that takes a file path as input
            public readPropertyFile(String propFile) throws IOException
            {
                FileInputStream fis = new FileInputStream(propFile);
                Properties pos = new Properties();
                pos.load(fis);
                userName = pos.getProperty("username");
                userpassword = pos.getProperty("password");
                url = pos.getProperty("url");
                browser = pos.getProperty("browser"); 
            }
        
            // Getters for the property values
            public String getUserName() {
                return userName;
            }
        
            public String getUserpassword() {
                return userpassword;
            }
        
            public String getUrl() {
                return url;
            }
        
            public String getBrowser() {
                return browser;
            }
        }
            

Variables

  • String userName: Stores the username retrieved from the properties file. This is initialized in the constructor by calling pos.getProperty("username").
  • String userpassword: Stores the password retrieved from the properties file. It is also initialized in the constructor by calling pos.getProperty("password").
  • String url: Stores the URL of the application or service that is fetched from the properties file using pos.getProperty("url").
  • String browser: Stores the name of the browser specified in the properties file, such as "Chrome" or "Firefox". This is retrieved using pos.getProperty("browser").
  • Properties pos: An instance of the Properties class, which is used to load and access the key-value pairs from the properties file.
  • FileInputStream fis: A stream object used to read the contents of the properties file. It points to the file specified by the path and is passed to the Properties.load() method.
  • String propFile: This variable stores the path to the properties file. In the default constructor, it points to "./resourceFiles/appProperties.properties", and in the parameterized constructor, it accepts a file path as an argument.

Methods

Constructors

There are two constructors in the class:

  • Default Constructor: readPropertyFile():
    • This constructor is used when the properties file path is fixed. It points to "./resourceFiles/appProperties.properties".
    • It reads the file using FileInputStream, loads it into a Properties object, and retrieves the values for username, password, url, and browser.
  • Parameterized Constructor: readPropertyFile(String propFile):
    • This constructor allows the user to specify the path to the properties file. It reads the file using the provided path and behaves similarly to the default constructor in loading the property values.

getUserName()

This method returns the value of the userName property. The userName is initially set by reading the "username" property from the properties file.

getUserpassword()

This method returns the value of the userpassword property, which is retrieved from the "password" key in the properties file.

getUrl()

This method returns the URL of the application or service. The URL is read from the "url" property in the properties file.

getBrowser()

This method returns the name of the browser, such as Chrome or Firefox, as specified in the "browser" property of the properties file.

Exception Handling

The constructors are declared to throw IOException in case of input/output errors while reading the properties file. This ensures that the program handles scenarios where the file is missing or unreadable.

Understanding Variables and Methods in the javaUtility Program

The javaUtility class is a utility class that provides various helpful methods for generating random data (such as emails, mobile numbers, and names), browser handling for Selenium WebDriver, and taking screenshots during automated tests. Below is a detailed explanation of the key variables and methods used in the program, along with the program code.

Program Code


        package com.scrm.generic.javautility;
        
        import java.io.File;
        import java.io.FileOutputStream;
        import java.io.IOException;
        import java.time.LocalDateTime;
        import java.time.format.DateTimeFormatter;
        import java.util.ArrayList;
        import java.util.List;
        import java.util.Random;
        
        import org.openqa.selenium.OutputType;
        import org.openqa.selenium.TakesScreenshot;
        import org.openqa.selenium.WebDriver;
        import org.openqa.selenium.chrome.ChromeDriver;
        import org.openqa.selenium.edge.EdgeDriver;
        import org.openqa.selenium.firefox.FirefoxDriver;
        
        import com.google.common.io.Files;
        
        import net.bytebuddy.utility.RandomString;
        
        public class javaUtility {
            public static List l = new ArrayList();
            public static Random rd = new Random();
            public static RandomString rs = new RandomString();
        
            // Generates random email addresses
            public static  List randomStrings(String domain, int n) {
                String randomEmail = "";
                List Emails = new ArrayList();
                while(n != 0) {
                    randomEmail = rs.nextString() + domain;
                    if(!Emails.contains(randomEmail))
                        Emails.add(randomEmail);
                    n--;
                }
                return Emails;
            }
        
            // Generates random mobile numbers
            public static List randomNUmber(int n) {
                long rdNUmber = 1;
                while(n != 0) {
                    rdNUmber = rdNUmber + rd.nextLong(999999999l); 
                    rdNUmber = new Long(9 + "" + rdNUmber);
                    if(!l.contains(rdNUmber) && (rdNUmber + "").length() == 10) {
                        l.add(rdNUmber);
                        n--;
                    }
                    rdNUmber = 1;
                }
                return l;
            }
        
            // Generates random strings for names
            public static  List randomNames(int n) {
                String name = "";
                List names = new ArrayList();
                while(n != 0) {
                    name = rs.nextString();
                    if(!names.contains(name))
                        names.add(name);
                    n--;
                }
                return names;
            }
        
            // Selects and returns the browser object
            public static WebDriver getBrowser(String browser) {
                if(browser.equalsIgnoreCase("chrome"))
                    return new ChromeDriver();
                else if(browser.equalsIgnoreCase("firefox"))
                    return new FirefoxDriver();
                else if(browser.equalsIgnoreCase("edge"))
                    return new EdgeDriver();
                else 
                    return new ChromeDriver();
            }
        
            // Takes a screenshot and saves it as a file
            public static void takeScreenShotasFile(WebDriver driver) throws IOException {
                TakesScreenshot ts  = (TakesScreenshot) driver;
                File src = ts.getScreenshotAs(OutputType.FILE);	
                DateTimeFormatter dt =  DateTimeFormatter.ofPattern("dd_MM_yyyy_HH_mm+ss");
                LocalDateTime lcd = LocalDateTime.now();
                File dst = new File("./ScreenShots/" + dt.format(lcd).toString() + ".png"); 
                Files.copy(src, dst);
            }
        
            // Takes a screenshot and returns it as a Base64 string
            public static String takeScreenShotasBase64(WebDriver driver) throws IOException {
                TakesScreenshot ts  = (TakesScreenshot) driver;
                String src = ts.getScreenshotAs(OutputType.BASE64);	
                return src;
            }
        }
            

Variables

  • List l: A static list used to store generated random mobile numbers. This list ensures that duplicate numbers are not generated.
  • Random rd: A static instance of the Random class, used to generate random numbers. It helps in creating mobile numbers or other numeric data.
  • RandomString rs: A static instance of RandomString from the net.bytebuddy.utility package, which generates random strings used for email addresses and names.

Methods

randomStrings(String domain, int n)

This method generates a list of random email addresses. The domain argument specifies the email domain (e.g., "@gmail.com"), and n specifies the number of email addresses to generate. It uses the RandomString object to create random strings for the email addresses and appends the provided domain. Duplicates are avoided by checking the Emails list.

randomNUmber(int n)

This method generates a list of random mobile numbers, each of which is 10 digits long. It uses the Random object to generate random numeric values. The generated numbers are added to the list l, and duplicates are avoided.

randomNames(int n)

This method generates a list of random strings representing names. It uses the RandomString object to create each name and ensures that no duplicate names are added to the list.

getBrowser(String browser)

This method selects and returns the browser object based on the input string browser. It checks if the browser is "chrome", "firefox", or "edge", and returns the appropriate WebDriver object. If no matching browser is found, it defaults to Chrome.

takeScreenShotasFile(WebDriver driver)

This method captures a screenshot of the browser window using Selenium WebDriver. It casts the driver to TakesScreenshot and saves the screenshot as a file. The filename is generated using the current date and time.

takeScreenShotasBase64(WebDriver driver)

Similar to the previous method, this one captures a screenshot but returns the screenshot as a Base64-encoded string rather than saving it to a file. This is useful when the screenshot needs to be transferred or displayed within a webpage or report.

Exception Handling

Methods like takeScreenShotasFile and takeScreenShotasBase64 declare IOException, ensuring that errors related to file handling and saving screenshots are properly handled.

Understanding Variables and Methods in the AccountPOM Program

The AccountPOM class is a Page Object Model (POM) class that represents the "Account" page in a web application. It helps encapsulate the interaction with the page by defining WebElements and providing methods for interacting with them. POM is widely used in Selenium to create a more maintainable test automation framework by keeping page elements and their interactions in one place. Below is the explanation of the key elements and methods used in the AccountPOM class.

Program Code


        package com.scrm.generic.webdriverutility;
        
        import org.openqa.selenium.WebDriver;
        import org.openqa.selenium.WebElement;
        import org.openqa.selenium.support.FindBy;
        import org.openqa.selenium.support.PageFactory;
        
        public class AccountPOM 
        {
            private WebDriver driver;
        
            public AccountPOM(WebDriver driver) {
                this.driver = driver;
                PageFactory.initElements(driver, this); // Initialize elements using @FindBy
            }
        
            @FindBy(id = "grouptab_0")
            private WebElement sales;
        
            @FindBy(linkText = "Accounts")
            private WebElement AccountLinktext;
        
            @FindBy(xpath = "//div[contains(text(),\"Create Account\")]")
            private WebElement createAccount;
        
            @FindBy(xpath = "//div[contains(text(),\"View Accounts\")]")
            private WebElement viewAccounts;
        
            @FindBy(xpath = "//div[contains(text(),\"Import Accounts\")]")
            private WebElement importAccount;
        
            @FindBy(id = "name")
            private WebElement accountHolderName;
        
            @FindBy(id = "phone_office")
            private WebElement officePhone;
        
            @FindBy(id = "website")
            private WebElement website;
        
            @FindBy(id = "phone_fax")
            private WebElement fax;
        
            @FindBy(id = "Accounts0emailAddress0")
            private WebElement AccountsHolderemailAddress;
        
            @FindBy(id = "Accounts0emailAddressPrimaryFlag")
            private WebElement AccountHolderPrimaryAddress;
        
            @FindBy(id = "Accounts0emailAddressOptOutFlag0")
            private WebElement AccountsEmailAddressOptOutFlag;
        
            @FindBy(id = "Accounts0emailAddressInvalidFlag0")
            private WebElement AccountsEmailAddressInvalidFlag;
        
            @FindBy(id = "billing_address_street")
            private WebElement billingAddressStreet;
        
            @FindBy(id = "shipping_address_street")
            private WebElement shippingAddressStreet;
        
            @FindBy(id = "billing_address_city")
            private WebElement billingAddressCity;
        
            @FindBy(id = "shipping_address_city")
            private WebElement shippingAddressCity;
        
            @FindBy(id = "billing_address_state")
            private WebElement billingAddressState;
        
            @FindBy(id = "shipping_address_state")
            private WebElement shippingAddressState;
        
            @FindBy(id = "billing_address_postalcode")
            private WebElement billingAddressPostalcode;
        
            @FindBy(id = "shipping_address_postalcode")
            private WebElement shippingAddressPostalcode;
        
            @FindBy(id = "billing_address_country")
            private WebElement billingAddressCountry;
        
            @FindBy(id = "shipping_address_country")
            private WebElement shippingAddressCountry;
        
            @FindBy(id = "shipping_checkbox")
            private WebElement shippingCheckbox;
        
            @FindBy(id = "description")
            private WebElement description;
        
            @FindBy(id = "account_type")
            private WebElement accountType;
        
            @FindBy(id = "industry")
            private WebElement industry;
        
            @FindBy(id = "annual_revenue")
            private WebElement annual_revenue;
        
            @FindBy(id = "employees")
            private WebElement employees;
        
            @FindBy(id = "parent_name")
            private WebElement parentName;
        
            @FindBy(id = "campaign_name")
            private WebElement campaignName;
        
            @FindBy(xpath  = "(//input[@title=\"Save\"])[2]")
            private WebElement saveButton;
        
            @FindBy(id = "CANCEL")
            private WebElement cancelButton;
        
            // Getters for WebElements
            public WebDriver getDriver() { return driver; }
            public WebElement getSales() { return sales; }
            public WebElement getAccountLinktext() { return AccountLinktext; }
            public WebElement getCreateAccount() { return createAccount; }
            public WebElement getViewAccounts() { return viewAccounts; }
            public WebElement getImportAccount() { return importAccount; }
            public WebElement getAccountHolderName() { return accountHolderName; }
            public WebElement getOfficePhone() { return officePhone; }
            public WebElement getWebsite() { return website; }
            public WebElement getFax() { return fax; }
            public WebElement getAccountsHolderemailAddress() { return AccountsHolderemailAddress; }
            public WebElement getAccountHolderPrimaryAddress() { return AccountHolderPrimaryAddress; }
            public WebElement getAccountsEmailAddressOptOutFlag() { return AccountsEmailAddressOptOutFlag; }
            public WebElement getAccountsEmailAddressInvalidFlag() { return AccountsEmailAddressInvalidFlag; }
            public WebElement getBillingAddressStreet() { return billingAddressStreet; }
            public WebElement getShippingAddressStreet() { return shippingAddressStreet; }
            public WebElement getBillingAddressCity() { return billingAddressCity; }
            public WebElement getShippingAddressCity() { return shippingAddressCity; }
            public WebElement getBillingAddressState() { return billingAddressState; }
            public WebElement getShippingAddressState() { return shippingAddressState; }
            public WebElement getBillingAddressPostalcode() { return billingAddressPostalcode; }
            public WebElement getShippingAddressPostalcode() { return shippingAddressPostalcode; }
            public WebElement getBillingAddressCountry() { return billingAddressCountry; }
            public WebElement getShippingAddressCountry() { return shippingAddressCountry; }
            public WebElement getShippingCheckbox() { return shippingCheckbox; }
            public WebElement getDescription() { return description; }
            public WebElement getAccountType() { return accountType; }
            public WebElement getIndustry() { return industry; }
            public WebElement getAnnual_revenue() { return annual_revenue; }
            public WebElement getEmployees() { return employees; }
            public WebElement getParentName() { return parentName; }
            public WebElement getCampaignName() { return campaignName; }
            public WebElement getSaveButton() { return saveButton; }
            public WebElement getCancelButton() { return cancelButton; }
        }
            

Variables

  • WebDriver driver: The Selenium WebDriver instance used to interact with the browser.
  • WebElement instances such as sales, AccountLinktext, createAccount, etc.: These are elements on the "Account" page, identified by their locators (like id, xpath, etc.), used for interacting with the web page.

Constructor

AccountPOM(WebDriver driver)

This constructor initializes the driver and uses PageFactory.initElements(driver, this) to initialize all the WebElements annotated with @FindBy. The PageFactory pattern helps to organize code and allows Selenium to easily locate and interact with the elements on the page.

WebElements and Their Usage

  • @FindBy(id = "grouptab_0") private WebElement sales; This element represents the "Sales" tab on the page. It is identified using the id locator.
  • @FindBy(linkText = "Accounts") private WebElement AccountLinktext; This element is a link to the "Accounts" page, located using its text "Accounts".
  • @FindBy(xpath = "//div[contains(text(),\"Create Account\")]") private WebElement createAccount; Represents the "Create Account" button or link on the page, identified by its text.

Getters for WebElements

The class provides getter methods for each WebElement, such as getSales(), getAccountLinktext(), etc., so that they can be accessed and interacted with in the test scripts.

Advantages of Page Object Model (POM)

The POM design pattern helps in improving code maintainability, reusability, and readability. By separating the page elements from the test logic, you can easily update the element locators if the UI changes without modifying the actual test scripts.

Understanding Variables and Methods in the loginPOM Program

The loginPOM class represents a Page Object Model (POM) for the login page of a web application. It helps to encapsulate the interaction with the login page elements and provides methods to access these elements. This POM design pattern improves the maintainability and readability of the test automation framework, particularly when using Selenium. Below is a detailed explanation of the key elements and methods used in the loginPOM class.

Program Code


        package com.scrm.generic.webdriverutility;
        
        import org.openqa.selenium.WebDriver;
        import org.openqa.selenium.WebElement;
        import org.openqa.selenium.support.FindBy;
        import org.openqa.selenium.support.PageFactory;
        
        public class loginPOM 
        {
            private WebDriver driver;
        
            public loginPOM(WebDriver driver) {
                this.driver = driver;
                PageFactory.initElements(driver, this); // Initialize elements using @FindBy
            }
        
            @FindBy(id = "user_name")
            private WebElement username;
        
            @FindBy(id = "username_password")
            private WebElement password;
        
            @FindBy(id = "bigbutton")
            private WebElement loginbutton;
        
            // Getters for WebElements
            public WebElement getUsername() { return username; }
            public WebElement getPassword() { return password; }
            public WebElement getLoginbutton() { return loginbutton; }
        }
            

Variables

  • WebDriver driver: The Selenium WebDriver instance used to interact with the browser.
  • WebElement instances such as username, password, and loginbutton: These elements represent the username input field, password input field, and login button on the login page. They are identified by their respective locators (like id).

Constructor

loginPOM(WebDriver driver)

This constructor initializes the driver and uses PageFactory.initElements(driver, this) to initialize all the WebElements annotated with @FindBy. The PageFactory pattern helps to organize code by automating the initialization of page elements, making the code cleaner and easier to maintain.

WebElements and Their Usage

  • @FindBy(id = "user_name") private WebElement username; This element represents the username input field on the login page. It is identified using the id locator.
  • @FindBy(id = "username_password") private WebElement password; This element represents the password input field, located using its id attribute.
  • @FindBy(id = "bigbutton") private WebElement loginbutton; Represents the login button, identified by its id as well.

Getters for WebElements

The class provides getter methods for each WebElement, such as getUsername(), getPassword(), and getLoginbutton(). These methods allow access to the elements so that they can be interacted with in the test scripts. For example, the login test script can use the getter methods to enter the username and password, and then click the login button.

Advantages of Page Object Model (POM)

The POM design pattern helps to separate the web element locators and the test logic, leading to better code maintainability and reusability. If the UI changes (e.g., the locators of elements are updated), you only need to modify the locators in the POM class without changing the test scripts.

Understanding Variables and Methods in the CreateAccountTest Program

The CreateAccountTest class is a TestNG-based test class that automates the creation of an account in a CRM system using Selenium WebDriver. It leverages the Page Object Model (POM) for interacting with the web elements of the account creation page. Below is an in-depth explanation of the class's components and their functionality.

Program Code


        package com.scrm.AccountsTest;
        
        import static org.testng.Assert.fail;
        
        import java.io.IOException;
        import java.util.List;
        
        import org.openqa.selenium.By;
        import org.openqa.selenium.WebElement;
        import org.openqa.selenium.interactions.Actions;
        import org.testng.annotations.Test;
        
        import com.scrm.BaseTest.baseClass;
        import com.scrm.generic.javautility.javaUtility;
        import com.scrm.generic.webdriverutility.AccountPOM;
        
        public class CreateAccountTest extends baseClass {
        
            @Test
            public void testCreateAcountTest() throws InterruptedException, IOException {
                String randomName = javaUtility.randomNames(1).get(0) + "",
                        randomEmail = javaUtility.randomStrings("@gmail.com", 1).get(0),
                        randomMobile = "javaUtility.randomNUmber(1).get(0) + ";
        
                // Create an AccountPOM object for accessing the web elements of the account page
                AccountPOM ap = new AccountPOM(driver);
                Actions act = new Actions(driver);
        
                // Navigate to the Accounts page
                act.moveToElement(ap.getSales()).perform();
                act.moveToElement(ap.getAccountLinktext()).click().perform();
        
                // Fill in account creation details
                ap.getCreateAccount().click();
                ap.getAccountHolderName().sendKeys(randomName);
                ap.getOfficePhone().sendKeys(randomMobile);
                ap.getWebsite().sendKeys("www.shariqsp.com");
                ap.getFax().sendKeys("NA");
                ap.getAccountsHolderemailAddress().sendKeys(randomEmail);
                ap.getAccountHolderPromaryAddress().click();
                ap.getAccountsemailAddressOptOutFlag().click();
                ap.getAccountsemailAddressInvalidFlag().click();
                ap.getBillingAddressAstreet().sendKeys("abcd");
                ap.getBillingAddressCity().sendKeys("bengaluru");
                ap.getBillingAddressState().sendKeys("karnatak");
                ap.getBillingAddressPostalcode().sendKeys("560001");
                ap.getBillingAddressCountry().sendKeys("india");
                ap.getShippingCheckbox().click();
                ap.getDescription().sendKeys("nothing");
        
                // Select values from dropdowns
                selectFromDropDownByText(ap.getAccountType(), "Analyst");
                selectFromDropDownByText(ap.getIndustry(), "Banking");
        
                // Fill in additional details and save
                ap.getAnnual_revenue().sendKeys("1000000");
                ap.getEmployees().sendKeys("nothing");
                ap.getParentName().sendKeys("nothing");
                ap.getCampaignName().sendKeys("nothing");
                ap.getSaveButton().click();
        
                // View accounts and verify creation
                ap.getViewAccounts().click();
                List names = driver.findElements(By.xpath("//td[@field=\"name\"]"));
                boolean flag = false;
        
                // Check if the new account is present
                for (WebElement i : names) {
                    if (i.getText().equals(randomName + "op")) {
                        flag = true;
                        break;
                    }
                }
        
                if (!flag) {
                    org.testng.Assert.fail();
                }
            }
        }
            

Key Components

  • AccountPOM ap = new AccountPOM(driver); This creates an instance of the AccountPOM class, which represents the page elements for the account creation page. It provides access to methods that interact with elements like the account name, phone number, and email fields.
  • Actions act = new Actions(driver); This initializes the Actions class, which is used to perform complex actions, such as moving to a specific element before clicking.

Methods and Functionality

  • testCreateAcountTest(): This method is the main test case. It automates the process of creating an account by entering random values for the account name, phone number, and email address, among others.
  • randomName = javaUtility.randomNames(1).get(0): This generates a random name using the randomNames() method from the javaUtility class.
  • ap.getAccountHolderName().sendKeys(randomName);: This inputs the generated random name into the account holder name field.
  • ap.getSaveButton().click();: Clicks the save button to submit the account creation form.
  • ap.getViewAccounts().click();: Navigates to the view accounts page after the account is saved.
  • org.testng.Assert.fail();: If the newly created account is not found in the list of accounts, this assertion will fail the test case.

Assertions and Validations

After submitting the account creation form, the test case verifies if the new account was successfully created by comparing the account name with the one that was generated. If the account is not found, the test fails.

Summary

The CreateAccountTest class automates the account creation process and uses TestNG for structuring the test. It also uses the Page Object Model (POM) design pattern to interact with the page elements in a cleaner and more organized way.

Explanation of the baseClass in the Framework

The baseClass is the core class that sets up and manages the browser for test cases in the automation framework. It implements the ITestListener interface from TestNG, which provides hooks to perform actions before and after the test suite, test methods, and test execution lifecycle events. Below is an analysis of the code components and their significance.

Program Code


        package com.scrm.BaseTest;
        
        import java.io.File;
        import java.io.IOException;
        import java.time.Duration;
        
        import org.openqa.selenium.WebDriver;
        import org.openqa.selenium.WebElement;
        import org.openqa.selenium.chrome.ChromeDriver;
        import org.openqa.selenium.edge.EdgeDriver;
        import org.openqa.selenium.firefox.FirefoxDriver;
        import org.openqa.selenium.support.ui.Select;
        import org.testng.ITestListener;
        import org.testng.ITestResult;
        import org.testng.annotations.AfterSuite;
        import org.testng.annotations.BeforeSuite;
        import org.testng.annotations.BeforeTest;
        
        import com.aventstack.extentreports.ExtentReports;
        import com.aventstack.extentreports.ExtentTest;
        import com.aventstack.extentreports.reporter.ExtentSparkReporter;
        import com.aventstack.extentreports.reporter.configuration.Theme;
        import com.scrm.generic.fileutility.readPropertyFile;
        import com.scrm.generic.javautility.javaUtility;
        import com.scrm.generic.webdriverutility.loginPOM;
        
        public class baseClass implements ITestListener {
            
            ExtentSparkReporter ext;
            ExtentReports exR;
            ExtentTest test;
            public static WebDriver driver;    
            readPropertyFile rd;
        
            /**
             * Setup method to launch the browser and initialize reporting.
             * @throws IOException
             */
            @BeforeSuite
            public void launchBrowser() throws IOException {
                
                // Configure Extent Report
                ext = new ExtentSparkReporter("./Reports/report.html");
                ext.config().setTheme(Theme.DARK);
                ext.config().setDocumentTitle("Extent Report");
                ext.config().setReportName("Framework Report");
                
                exR = new ExtentReports();
                exR.attachReporter(ext);
                exR.setSystemInfo("OS", "Windows 10");
                exR.setSystemInfo("Browser", "Chrome");
        
                // Initialize ExtentTest instance for logging
                test = exR.createTest("Account Creation", "Testing account creation with automation script");
        
                // Read property file for browser and URL details
                rd = new readPropertyFile();
                String browser = rd.getBrowser();
                String url = rd.getUrl();
        
                // Launch the browser
                driver = javaUtility.getBrowser(browser);
                driver.manage().window().maximize();
                driver.get(url);
                driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(20));
            }
        
            /**
             * Method to log in before starting the test.
             * @throws Exception
             */
            @BeforeTest
            public void login() throws Exception {
                String username = rd.getUserName();
                String password = rd.getUserpassword();
        
                loginPOM lpm = new loginPOM(driver);
                lpm.getUsername().sendKeys("admin");
                lpm.getPassword().sendKeys("admin");
                lpm.getLoginbutton().click();
            }
        
            /**
             * Method to close the browser after the suite completes.
             * @throws IOException
             */
            @AfterSuite
            public void closeBrowser() throws IOException {
                // Capture screenshot and add to report
                String src = javaUtility.takeScreenShotasBase64(driver);
                test.addScreenCaptureFromBase64String(src, "error");
        
                // Flush the report and quit the browser
                exR.flush();
                driver.quit();
            }
        
            /**
             * Dropdown selection methods for selecting items in HTML select elements.
             */
            public void selectFromDropDownByText(WebElement ele, String text) {
                Select sel = new Select(ele);
                sel.selectByVisibleText(text);
            }
        
            public void selectFromDropDownByText(WebElement ele, int index) {
                Select sel = new Select(ele);
                sel.selectByIndex(index);
            }
        
            public void selectFromDropDownByValue(WebElement ele, String value) {
                Select sel = new Select(ele);
                sel.selectByValue(value);
            }
        }
            

Key Components

  • ExtentSparkReporter: This is used to configure the Extent Reports. It generates an HTML report with details of the test run. The theme and appearance of the report can be configured, and additional system information is logged.
  • ExtentReports and ExtentTest: These are used to log test execution steps and results. The ExtentTest instance represents an individual test case and logs details of its execution.
  • readPropertyFile: This class reads configuration data like browser type and URL from a properties file, allowing dynamic control over the environment.
  • javaUtility.getBrowser(browser): This utility method initializes the appropriate browser driver (Chrome, Firefox, or Edge) based on the configuration file.

Methods and Functionality

  • @BeforeSuite launchBrowser(): This method runs before the test suite begins. It initializes the browser, opens the application URL, and sets up the Extent Reports.
  • @BeforeTest login(): This method runs before each test method. It logs into the application using credentials fetched from the properties file.
  • @AfterSuite closeBrowser(): After all tests have been executed, this method is called. It captures a screenshot (if needed), adds it to the report, and then closes the browser.
  • selectFromDropDownByText(), selectFromDropDownByValue(), and selectFromDropDownByIndex(): These utility methods help select options from dropdown menus based on visible text, index, or value, respectively.

Test Execution Flow

The test execution begins with @BeforeSuite, where the browser is launched and the reporting infrastructure is set up. Next, @BeforeTest handles login actions before each test. After all tests are done, @AfterSuite captures a final screenshot, logs it into the report, and closes the browser.

Summary

The baseClass provides the foundation for all test classes. It manages the setup and teardown of the test environment, configures the reporting infrastructure using Extent Reports, and includes utility methods for common actions like interacting with dropdowns.

Explanation of the listenerImplementation Class in the Framework

The listenerImplementation class implements the ITestListener interface from TestNG, which provides methods that allow you to define actions to be taken at specific points during the test execution lifecycle. This class is primarily responsible for handling events like test failures and logging activities in the test reports.

Program Code


        package com.scrm.BaseTest;
        
        import java.io.IOException;
        
        import org.testng.ITestContext;
        import org.testng.ITestListener;
        import org.testng.ITestResult;
        import org.testng.Reporter;
        
        import com.scrm.generic.javautility.javaUtility;
        
        public class listenerIMplementation implements ITestListener {
            
            /**
             * Invoked when the test context (such as a suite or a test) starts.
             * @param context The TestNG context
             */
            @Override
            public void onStart(ITestContext context) {
                Reporter.log(""); // Can add logging or setup actions here
            }
        
            /**
             * Invoked when a test fails.
             * @param result The result of the test that failed
             */
            @Override
            public void onTestFailure(ITestResult result) {
                try {
                    // Log a message to the TestNG report
                    Reporter.log("hi");
                    
                    // Capture a screenshot when a test fails
                    javaUtility.takeScreenShotasFile(baseClass.driver);
                } catch (IOException e) {
                    e.printStackTrace(); // Print the stack trace for the exception
                }
            }
        }
            

Key Components

  • ITestListener: This interface provides a variety of methods to be overridden, allowing for custom actions at different stages of the test lifecycle (like test start, test success, test failure, etc.). Here, only two methods, onStart and onTestFailure, are implemented.
  • Reporter.log(): This method is used to log messages to the TestNG report. It helps track what happened during test execution and provides useful information in the reports.
  • javaUtility.takeScreenShotasFile(): This utility method is used to capture a screenshot when a test fails. Screenshots can be crucial for debugging and tracking errors in test automation.

Methods and Functionality

  • onStart(ITestContext context): This method is invoked when a test context (which could be a suite or a test) starts. Here, it's left mostly empty but can be used to log or set up any necessary pre-test configurations.
  • onTestFailure(ITestResult result): This method is called when a test case fails. It logs a message ("hi") to the report and captures a screenshot of the failure. The screenshot is saved using the takeScreenShotasFile() method from javaUtility.

Test Execution Flow

During test execution, TestNG will automatically invoke the onStart() method when the test suite or test begins. If a test case fails, the onTestFailure() method will be triggered, which captures a screenshot and logs a message to the report. These listeners allow test failures to be monitored and provide valuable data for diagnosing issues.

Summary

The listenerImplementation class serves as a listener that listens for specific test events and acts upon them, such as capturing screenshots upon failure and logging messages. It enhances the test framework by providing mechanisms for reporting and diagnostics, particularly during test failures.