In this VBScript Tutorial, we are going to learn about the most important and frequently used VBScript String Functions, including vbscript InStr, vbscript StrComp, vbscript Mid function, etc. All the vbscript string functions are explained with an example.
VBScript Tutorial #5: VBScript String Functions
VBScript String Functions:
While working with string in vbscript, we can use vbscript string functions to perform important string operations such as search, replace, extract, get the length, comparisons, etc. Through the “VBScript String Functions” article, we will explain the frequently used built-in VBScript string functions with examples.
Important VBScript String Functions – Summary:
vbscript SubString – This method is used to extract characters from string based on provided criteria.
vbscript InStr – Find the position of a particular expression(first occurrence) within a string.
Important VBScript String Functions – Explanations:
All the important vbscript string functions are explained in this section with real live example.
vbscript InStr:
The vbscript instr function finds the position of first occurrence of a particular expression available within a string and returns the position value.
Syntax: InStr([start,]string1,string2[,compare])
Parameter Description:
Start – This parameter defines the start position of string1 from where searching or checking the first occurrence of string2 will be started. This is an optional parameter. By default, if nothing is specified, the vbscript starts with 1st position.
String 1 – This string is to be searched for the occurrence checking of another string.
String 2 – This is the string expression to search for.
Compare – This is an optional field used to define the comparison type between binary or textual. The default value is 0. The possible values are –
0 = vbBinaryCompare – Perform a binary checking
1 = vbTextCompare – Perform a textual checking
Example:
In this example of the vbscript InStr function, we are going to find and print the first occurrence of a search string.
string1 = "aabbccddee"
string2 = "bb"
nPostionOfOccurance = INSTR(1,string1,string2,1)
msgbox "Position of first occurance - " & nPostionOfOccurance
vbscript string Replace:
The vbscript string replaces function is used to replace the specified parts of a string with another string for a predefined number of occurrences.
mainString – This is the main string that is to be updated for the replacement.
findString – This string portion will be replaced in the main string.
replaceWith – This is the replacement string.
StartPos – This parameter defines the start position of the main string from where searching will be started. This is an optional parameter. By default, if nothing is specified, the vbscript starts with 1st position. Before the start position, all the characters will be removed.
Count – This is an optional parameter that is used to define the numbers of substitutions to be done. The default value for the count parameter is -1, which defines that there is no limitation on number of substitutions to be done.
Compare – This is an optional field used to define the comparison type between binary or textual. The default value is 0. The possible values are –
0 = vbBinaryCompare – Perform a binary checking
1 = vbTextCompare – Perform a textual checking
Example:
In this example of the vbscript Replace function, we are going to replace all the occurrences of a particular string with another string.
mainString = "aa bb cc dd bb ee"
findString = "bb"
replaceWith = "zz"
startPos = 1
updatedString = Replace(mainString,findString,replaceWith,startPos)
msgbox "String after the replacement - " & updatedString
vbscript Mid:
The vbscript Mid function returns the specified number of characters from a string.
Syntax: Mid(string,startPos[,length])
Parameter Description:
string – The specified number of characters will be extracted from this string.
startPos – It defines the start position of the characters which is going to be extracted.
length – This is an optional field that defines the length of the extracted text. If the parameter is not provided, the vbscript mid function extract the entire string after the start position.
Example:
In this example of the vbscript Mid function, we are going to extract characters of length three from position 4.
source_string = "aaabbbcccddd"
startPos = 4
length = 3
captured_string = Mid(source_string,startPos,length)
msgbox "Extracted string of length 3 from position 4 is - " & captured_string
vbscript substring:
There is no specific method with the name substring. But just like the java substring method, we can use the vbscript Mid function.
vbscript string concatenation:
The vbscript string concatenation operator is used to add/ concrete two or more strings. The vbscript string concatenation operator is ‘&.’
Syntax: string1 & string2 & string3 …
Example:
In this example, we will add two strings using the vbscript string concatenation operator,
string1 = “abc” & “def”
After the execution, the variable string1 is going to hold the value as “abcdef”
vbscript Left function:
The vbscript Left function extracts a specified number of characters from the left side of a string.
Syntax: Left(string,length)
Parameter Description:
string – The specified number of characters will be extracted from this string from the left side.
length – It denotes the length of the characters which will be extracted from left side.
Example:
In this example of the vbscript Left function, we are going to extract characters of length three from the left side.
source_string = "aaabbbcccddd"
length = 3
captured_string = Left(source_string,length)
msgbox "Extracted charecters from Left side - " & captured_string
vbscript Right function:
The vbscript Right function extracts a specified number of characters from the right side of a string.
Syntax: Right(string,length)
Parameter Description:
string – The specified number of characters will be extracted from this string from the right side.
length – It denotes the length of the characters which will be extracted from right side.
Example:
In this example of the vbscript Right function, we are going to extract characters of length three from the right side.
source_string = "aaabbbcccddd"
length = 3
captured_string = Right(source_string,length)
msgbox "Extracted charecters from Right side - " & captured_string
vbscript StrComp function:
The vbscript StrComp function is used to compare two strings and returns the result of the comparison.
Syntax: StrComp(string1,string2[,compare])
Parameter Description:
string1 – One of the string expression parameter which required for the comparison.
String2 – Another string expression parameter required for the comparison.
Compare – This is an optional field used to define the comparison type between binary or textual. The default value is 0. The possible values are –
0 = vbBinaryCompare – Perform a binary checking
1 = vbTextCompare – Perform a textual checking
The vbscript StrComp function can return one of the following values:
-1 (if string1 < string2)
0 (if string1 = string2)
1 (if string1 > string2)
Null (if string1 or string2 is Null)
Example:
In this example of the vbscript StrComp function, we are going to see the results for three different comparison conditions.
The vbscript Trim function is used to clear all the spaces from both the side, i.e., from the beginning and end of the string.
Syntax: Trim(string)
Parameter Description:
string – It’s a string containing spaces at the left and right sides.
Example:
In this example of the vbscript Trim function, we are going to remove the spaces from both the sides of a string.
string1 = ” aaa bbb ccc ddd “
string2 = Trim(string1)
After the execution, the string2 variable will contain the value as “aaa bbb ccc ddd,” without the spaces on the left and right sides.
vbscript Ltrim function:
The vbscript LTrim function is used to remove any spaces from the left side of the string.
Syntax: Ltrim(string)
Parameter Description:
string – It’s a string containing spaces on the left side.
Example:
In this example of the vbscript LTrim function, we are going to remove the spaces from the left side of a string.
string1 = ” aaa bbb ccc ddd “
string2 = Ltrim(string1)
After the execution, the string2 variable will contain the value as “aaa bbb ccc ddd,” without the spaces from the left side.
vbscript Rtrim function:
The vbscript RTrim function is used to remove any spaces from the right side of the string.
Syntax: Rtrim(string)
Parameter Description:
string – It’s a string containing spaces on the right side.
Example:
In this example of the vbscript RTrim function, we are going to remove the spaces from the right side of a string.
string1 = ” aaa bbb ccc ddd “
string2 = Rtrim(string1)
After the execution, the string2 variable will contain the value as “ aaa bbb ccc ddd,” without the spaces from the right side.
vbscript Uppercase i.e. vbscript UCase function:
The actual function name for vbscript Uppercase is vbscript Ucase function. The vbscript UCase function is used to convert the characters of any string(irrespective of case) into upper case characters.
Syntax: UCase(string)
Parameter Description:
string – It’s a string to convert into uppercase characters.
Example:
In this example of the vbscript UCase function, we are going to convert a string containing lower and upper cases into upper case characters.
string1 = “aBcD aabb”
string2 = Trim(string1)
After the execution, the string2 variable will contain the value as “ABCD AABB.”
vbscript Lowercase i.e. vbscript LCase:
The vbscript LCase function is used to convert the characters of any string(irrespective of case) into lower case characters.
Syntax: LCase(string)
Parameter Description:
string – It’s a string to convert into lowercase characters.
Example:
In this example of the vbscript LCase function, we are going to convert a string containing lower and upper cases into lower case characters.
string1 = “aBcD aabb”
string2 = Trim(string1)
After the execution, the string2 variable will contain the value as “abcd aabb.”
vbscript length function:
The vbscript Length function is used to find the length of a particular string. It returns the length as an integer value.
Syntax: Length(string)
Parameter Description:
string – Any string expression.
Example:
In this example of the vbscript length function, we are going to find the length of any particular string expression.
string = “aBcD aabb”
strLength = Length(string)
After the execution strLength variable will contain the length of the string as 9.
vbscript StrReverse function:
The vbscript StrReverse function is used to reversing any string.
Syntax: StrReverse(string)
Parameter Description:
string – Any string expression.
Example:
In this example of the vbscript StrReverse function, we are going to reversing the characters of a particular string.
string1 = “abcde”
string2 = Length(string1)
After the execution, the string2 variable will contain the reverse string as “edcba.”
Conclusion:
Through this VBScript String Functions article, we have learned about the important VBScript String Functions, including vbscript InStr, vbscript StrComp, vbscript Mid funtions, etc. In the next vbscript tutorial, we will explain about VBScript Date and Time functions. Please click here to get more details.
In this VBScript Tutorial, we are going to learn about VBScript Procedures, including VBScript Functions and VBScript Sub Procedures. Also, we are going to learn about VBScript Error Handling and approaches to Execute VBScript through this tutorial.
VBScript Tutorial #3:VBScript Procedures
VBScript Procedures:
VBScript procedures are the block of statements enclosed by special keywords to perform specific actions. VBScript procedures have the ability to accept input values and return the output value. Here, the input values are represented as the arguments.
VBScript procedures are mainly used to organize the codes in a professional way for code reusability and better maintenance. Let’s assume a big program or codes have some basic arithmetic operation is performed repetitively. So, if there is a change in that operation, we need to change in every place where it’s used. Instead of doing the same, if we write one VBScript procedure for the same operation and use the reference of that in all the places, then we need to change the code in one place. In this way, we can reduce script maintenance efforts.
VBScript procedures can be referred to by using the keyword “Call”. Also, VBScript allows calling any procedure without using this keyword.
The Advantages of VBScript Procedures:
· Code reusability.
· Reduce script maintenance efforts.
· Better readability of codes.
· Better organization of codes.
Types of VBScript Procedures:
The VBScript procedures are accepting inputs, process it and perform some operation based on the types of procedure. Broadly, VBScript procedures are classified into two types which ate specified below –
· VBScript Sub procedure
· VBScript Function procedure
VBScript Sub Procedures:
The VBScript sub procedures group multiple statements without returning any output values. It can accept the inputs as arguments. This type of procedures is to start and end with Sub and End Sub keywords, respectively. VBScript Sub procedures can accept arguments but do not return any output values.
Example – Here we will write a small vbscript sub procedure which accept an argument as alert messages and display it in a popup message box.
‘Call the vbscript sub procedure
Call displayAlert(“This is an example of vbscript sub procedure”)
Sub displayAlert(alertMessage)
\tMsgbox alertMessage
End Sub
VBScript Function:
If we want to execute a block of statements with returning any output values, we need to use VBScript functions. At the beginning of the VBScript functions, we need to use “Function” keyword to define the function name and at the end the “End Function” keyword is used. VBScript Functions can accept arguments as well as return values. To return value from a function, the value has to be assigned to the function name before closing the function.
Example – In this example, we will calculate the circle area using a vbscript function. Here, the radius will be passed as an argument to the VBScript function and return the area as output.
Dim calcArea
'Call the vbscript function
calcArea = calcCircleArea(7)
msgbox "The area of the circle is " & calcArea
Function calcCircleArea(radius)
\tdim pi, a
\tpi = 22/7
\ta = pi*radius*radius
\tcalcCircleArea = a
End Function
Output(Message Box): The area of the circle is 154
ByRef and ByVal Arguments in VBScript Procedures:
ByRef Argument – To keep the changes made in the argument even after the VBScript procedure is called, then we have to send the argument by reference(ByRef). If there is nothing is specified when passing arguments into the VBScript procedures, by default it’s treated as passed by reference. The keyword ByRef is used to pass the argument by reference.
Example of ByRef – Refer below code, here argument Counter has been passed by reference into the procedure. Initially, it’s defined with value four, and in the procedure, it’s incremented by 1. As the argument has been passed by reference, the value of the argument will be five after the function call.
Function incrementCounter(ByRef Counter)
Counter = Counter +1
incrementCounter = Counter
End Function
Dim x
myCounter=4
call incrementCounter(myCounter)
msgbox myCounter
Output => 5
ByVal Argument – When an argument is passed by value(ByVal), any modification, done on the argument’s value in the VBScript functions, will not persist after the function call. The keyword ByVal is used to pass the argument by value.
Example of ByVal – Refer below code, here argument Counter has been passed by value into the procedure. Initially, it’s defined with value four, and in the procedure, it’s incremented by 1. As the argument has been passed by value, the value of the argument will remain four after the function call.
Function incrementCounter(ByVal Counter)
Counter = Counter +1
incrementCounter = Counter
End Function
Dim x
myCounter=4
call incrementCounter(myCounter)
msgbox myCounter
Output => 4
VBScript errors are nothing but unhandled events which is not handled through the code. In vb scripting, if any events are encountered which are not handled through the codes, they are treated as VBScript errors.
Types of VBScript Errors:
The different types of VBScript errors are mentioned below –
Syntax Errors – The primary reasons for this type of VBScript errors are the incorrect structure of the script, typographical errors, incorrect spelling of keywords, syntactical errors. If the syntax errors exist, the script will not be executed at all. It appears during the compilation time of the script.
Logical Errors – This type of VBScript errors are appeared due to some unexpected events such as number, or date conversion failed due to inappropriate data. It appears while the test scripts are getting executed.
VBScript Error Handling:
It is not possible to handle all the unexpected VBScript errors through coding. So, it’s the first priority to handle VBScript errors. Primarily, there is one approach to handle the VBScript error in the scripts. This approach is the combination of using “On Error Resume Next” statements and Err Object’s property.
On Error Resume Next statements:
It was using the On-Error- Resume-Next statements; the exception can be handled partially. In this approach, the test script block should be started with “On Error Resume Next” statements. It signifies that in case of any error, execution will be skipped the current step and proceed with next step. After that, by checking the Error, we can handle the exceptions. Important keywords are –
· On Error Resume Next – In case of Error, VBScript will not raise an error message; instead of that, execution will move to the next step.
· On Error Goto 0 – It will work in reverse procedure with comparison to the above keyword. So, after execution of this step, VBScript will throw errors in case of any exceptions.
· Error.Description – It stores the error description.
· Error.Number – It holds the error number. For success, the value is zero.
· Error.Clear – It reset the Error object.
On Error Resume Next
\t'Vbscript statement 1
\t'Vbscript statement 1
\t. . . . .
\tIf error.number <> 0 then 'Checking for error
\t\t'..Handle the error
\tElse 'Success condition no need to handle anything
\t\tError.Clear
\tEnd If
On Error Goto 0
Approach to Execute VBScript:
There are different ways that are available to execute VBScripts. The most used approaches are –
Execute VBScript through .vbs file
Execute VBScript as a part of HTML web development
Execute VBScript through .vbs file: The steps to execute vbscript through .vbs file are –
Write VBScript codes in a simple flat file. Any editor such as, note pad, Note Pad++, Edit Plus, etc can be used to create the file.
Save the file with .vbs extension.
Execute the file by double-clicking on it.
Same file can be executed through the command prompt using the full file path. Command to execute vbs file is WScript “<file_name_with_path>”.
Through out this vbscript tutorial, we are using this approach to run all the demo vbscripts.
Execute VBScript as a part of the web page: In this approach, we need to write the VBScript codes with in tag <script> in the web page. The syntax will be looks like below –
This approach is used while developing web pages using the classic ASP. Also same can be used in other technologies like PHP, JSP etc.
Tools Uses VBScript: The major tools which supports vbscripts are – UFT, Excel Macro, Visual Basic, Classic ASP (client side scripting)
Conclusion:
In this VBScript article, we have learned about the learn about VBScript Procedures and VBScript Error Handling through this tutorial. We hope this tutorial has helped a lot to brush up on your basics of VB Scripting. To get more information on VBScripting, please click here.
The scope of software testing is leading the IT industries now to ensure the quality of the product. Apart from regular web application testing, the scope for mobile testing is also rapidly increasing. The mobile devices can be tested either manually or through the mobile automation tools. Many mobile test automation tools are available in the market which provides mobile labs and the automation capabilities as well. The well known tools are Perfecto, SeeTest, Mobile Lab, etc.
Perfecto Selenium Integration for Mobile Automation
In this section, we will explain the step by step approach to execute selenium webdriver test cases using the Perfecto mobile lab and automation capabilities. The pre-requisites assumptions to start with this article, are mentioned below –
Basic knowledge in Selenium WebDriver.
Developed a Selenium test case which will be used here.
New to the Perfecto.
Configuration details for Perfecto Automation:
Here we will update the pom.xml file with the necessary Perfecto dependencies and edit the codes from Step 1 to add them in the security data, the Perfecto cloud name, driver details, smart test data update.
The modified code is called PerfectoSelenium.java. The below process walks the users through the configuration.
Copy the dependencies
Supply the security token
Select a device
Supply the URL to connect to the Perfecto cloud
Create an instance of the reporting client
Execute the test
Step1# Accessing Perfecto Cloud:
Register for the first time user for two weeks of the free trial from the perfecto trial license web.
Log in with the Perfecto cloud using the above free trial user.
Step2# Capture Security Token from Perfecto Cloud:
The security token is an encrypted version of long string which will be used later to connect the Perfecto mobile lab from third-party tools like Selenium WebDriver. Steps to capture the security token are mentioned below –
First, click on user name which is displayed in the right top corner and click on “My Security Token” link from user menu to open “My Security Token” popup.
Here, we need to click on “GENERATE SECURITY TOKEN” button and copy the generated security token.
Step3# Select a Device and get the Capabilities:
Capabilities are used to define the mobile devices which will be accessed from the Perfecto cloud. The structure for defining the capabilities are look like below –
DesiredCapabilities capabilitiesSample = new DesiredCapabilities(webBrowserName, “”, Platform.ANY);
Here, “platformName” capability is used to define the platform of the mobile OS. To find the source code for the desire capabilities of the mobile android devices, we need to open the Perfecto Cloud UI with Manual Testing view. The source code of capabilities, can be copied to our selenium test case. The steps to follow for capturing the desire capabilities through the perfecto mobile cloud are mentioned below –
Click on Open Device option which is available under the Manual Testing section. This section is located in Perfecto Landing page.
On the Manual Testing view, select a device to proceed next.
Now click to open the Capabilities tab which is available in the details pane. The details pan will be available after selection of the device only.
All the capabilities will be displayed here. We can copy either all or selected capabilities based on the requirement.
Step4# URL to Connect Perfecto as Appium Server:
The structure of the URL for perfecto cloud will be looks like below –
If the URL to access the Perfecto cloud manually is “https://testingcloud.app.perfectomobile.com/lab/devices” then the cloud name will be testingcloud.
Step5# Reporting Client Instance Creation:
The best way to run our test in Perfecto, the first step is to crate an instance with the reference of ReportingClient class i.e., the smart reporting client. It will help us to analyze the report after the test execution. The reporting client is used to collect the basic information of the test. Later, this information will be send to the Smart Reporting system.
In the sample project(Utils.java), we have shown about the usage of the ReportiumClientFactoryclass’ createPerfectoReportiumClient() method. The instance of PerfectoExecutionContext class provides the link to the factory class.
withWebDriver() – With the help of this method, the link for the driver instance are supplied.
build() – This method is used to create the instance of the context object which will be supplied to the createPerfectoReportiumClient() method for ReportiumClient instance creation.
The main purpose of this reporting is to analyze the test result from the Perfecto Cloud.
Sample Project to Demonstrate the Perfecto Automation Approach in Mobile Devices
Manual Test Scenario:
Login to the perfecto mobile cloud with valid user credential.
Select any available device.
Open the setting app.
Click on sub-menu contains text as “data usage”.
Verify that “Data Saver” submenu will be displayed.
Basic Information Collected: As pert of test automation, we have collected the Information such as cloud name, security token, capabilities, app package/activity name, captures the object’s property, etc.
Download codes for a sample project: Please click here to download codes for Sample Project. In this sample project, the basic codes are available for Local Appium, Local Selenium, Perfecto Appium and Perfecto Selenium. In this article, we will execute the java test code for Perfecto Appium.
Steps to Prepare the Test for Execution:
Step 1# Import the Sample Project into Eclipse Workspace, which was downloaded previously. This project can be imported through navigation “File->Open Projects from File System” available in Eclipse IDE.
Step 2# After importing the sample project, we need to update the file PerfectoAppium.java to modify basic details such as cloud name, security token, capabilities, app package/activity name, object’s property, etc. which are captured previously.
Step 3# Once the selenium test is ready for execution; we need to the right click on “PerfectoAppium.java” class to run the test as “Run As-> TestNG Test”.
Step 4# After successful execution, the test result can be viewed from Eclipse and Perfect Analyze tab as well.
Sample Project to Demonstrate the Perfecto Automation Approach in Web Application:
At the starting point, LocalSelenium.java, a small Javascript with Maven dependencies can be configured to understand the basics on test automation using Selenium build tool Maven. The pom.xml file is institutional here as it contains all configurations setup and dependencies.
Note: Intentionally, the simple script has been written for better understanding. The purpose of the script to show the approach to connect Perfecto from Selenium. After connecting the Perfecto website, the script will check the title.
To start:
Copy by cloning the sample project which is available in GitHub. The clone URL is – https://github.com/PerfectoMobileSA/PerfectoSampleProject
Launch the IDE and check out the project from GitHub or Import in Eclipse.
Need to download the appropriate Chrome driver as per the Chrome version which is installed in the device.
Execute the LocalSelenium.java project as TestNG Test.
Conclusion:
Through this, “Selenium for Perfecto” article, we have discussed about complete and detailed overview of Perfecto Selenium Integration using Selenium WebDriver (Java). Also, we have learned to execute a sample project for Perfecto automation with the help of Perfecto mobile lab and automation capabilities. To learn more on Perfecto Automation, please click here.
Testing is now the most important part of the software development life cycle to ensure the quality of the product. Also, without testing, we can’t ensure the fulfilment of all the requirements. With the usage of mobile apps, the mobile testing opportunities are getting increased proportionally. There are several mobile testing tools, and labs are available in the market, such as Perfecto, SeeTest etc.
This Selenium for Perfecto Tutorial by Lambda Geeks is written to provide acomplete and exhaustive overview of Installation of Selenium Perfecto using WebDriver (Java) framework and basic coding for web automation.
The Perfecto Automation tool is an entirely web-based SaaS i.e. Software as a Service platform which provides mobile labs with mobile automation capabilities. that allows mobile application designers and QA professionals both work with services The Perfecto can be used by mobile application developers or the QA testers as it allows the services such as manage apps, monitoring, testing services, etc.
The devices available in Perfecto mobile lab, can be accessible by multiple users irrespective of geographical locations for development, testing or monitoring purposes.
The perfecto allows the test automation activities through a web based interface which is designed for automation purposes. This interface enables to design simple test cases with out implementing the complex logics. For complex logical test cases, we can integrate the perfecto with Selenium tool.
The commands i.e. the keywords to perform the different actions for mobile test automation, are available in the Perfecto cloud as widgets. Perfecto only allows the test developer to create test cases, add the keywords with definition of different properties in the user interface as it follows keyword-based scripting approach. The Perfecto as a testing tool is compatible with text and image recognition.
The Perfecto Mobile cloud is compatible with third party tools like Selenium, UFT, TOSCA, etc. So, by integration with those tools, it will be very easy to identify objects (using the object Finder/scan mechanism of the third party tools) and develop the complex test cases. Through out this Perfecto Tutorial, we are going to learn on perfecto selenium integration.
Prerequisites for Perfecto Automation with Selenium:
Here we will discuss the process to execute the Selenium scripts with Java using Eclipse IDE; We consider that the readers
Are hands-on Selenium
Have existing scripts for work
There is some mandatory setup need to complete before you get started, make sure you have installed the following:
Java Development Kit – It is required to create the java environment which is required for Perfecto Selenium Integration.
Selenium WebDriver – It’s required to enable the selenium. Click here to download the corresponding jar files.
Chrome Driver – The corresponding Crome Driver has to be downloaded from here, as per the version of chrome installed in mobile device.
IDE – An IDE is required to develop the test cases. The available IDEs are Eclipse or IntelliJ IDEA etc. To work with Eclipse, which a popular IDE, TestNG and Maven plugins are also required.
Selenium for Perfecto Automation
Selenium is free(Open source) test automation tool which is primarily used for automation testing of the web application. But, with the help of third party mobile testing tools, it has the capability to test mobile apps as well. Selenium is supporting programming languages such as Java, C#, Python, etc. Different selenium frameworks available in the market are,
Install Java: The Selenium WebDriver runs in the Java environment. So, the first step is to install the appropriate JDK from the internet. We can download the JDK from here. After the installation, the system restart is required.
Install Eclipse IDE: This IDE is required to create workspace and develop the test cases with the help of Selenium. To download the Eclipse IDE, please click here. It should be downloaded based on the operating system’s version. It’s required to write, compile and run the selenium program.
Download Selenium Java Client Driver: Java Client for Selenium WebDriver can be downloaded from here.
Step2# Configure Eclipse IDE with Selenium:
Launch the eclipse.exe from the Eclipse folder to open the IDE.
Select the workspace for the Selenium IDE to start with and click OK.
Now create a Java project from the menu navigation ”File->New->Project” and then select “Java Project” option. We need provide the project related information after clicking on “Next” button. The required details are –
Project Name – It refers the name of the project. An project folder will be created in the workspace based on the name.
Use default location – Either we can accept the default location in workspace or save the project in different place.
Select an execution JRE – If multiple JREs are available, we need to select the correct version.
Project Layout – We can define the project layout (folder structure) based on this option.
Click on Finish button to create a new project as name “androidProject”.
4. Now we need to create a new package as an android package and a new class as an android class within the newly created package. The packages can be created by right-clicking on the root folder for the newly created project.
5. Now we need to refer the external selenium Jar files within the project. It can be done by following the navigation – “Right-Click on Project Folder -> Properties -> Java Build Root -> Libraries -> Click on Add External JARs -> Select the selenium Jar Files”. Here we need to select all the jar files available in the “selenium-xxxxx” folder and “selenium-xxxxx\\libs” folders.
Once all the external jar files are selected, we need to click on the Apply button and then OK to close the window.
6. Download and install compatible ChromeDriver version from the web. This is required from mobile web testing using Perfecto.
Step3# Configure testNG in Selenium:
Install testNG from eclipse marketplace(Help->Eclipse Marketplace->search testNG and install).
Add the External library for TestNG. It can be done by following the navigation – “Right-Click on Project Folder -> Properties -> Java Build Root -> Libraries -> Click on Add Library -> Select TestNG option and proceed next to add this library”.
Step4# Create TestNG Class:
Creat TestNG class is a very simple, easy process to perform. We need to follow the below steps to create TestNG class –
Convert Java project as TestNG Project – Right-click on the src folder under the project root and click on option Convert to TestNG from the navigation “TestNG->Convert to TestNG”. After deletion of “Convert to TestNG” option, a new window will be appeared where we need to lick on “Finish” button to complete the conversion.
Create TestNG Class – Right-click on the src folder under the project root and click on option Create TestNG Class from the navigation “TestNG->Create TestNG Class”. A new window will appear. Here, we need to provide basic details such as Source Folder, PackageName, Class Name and Annotations as per below diagram to create TestNG Class. Now, click on FINISH button to create the class.
Step5# First Selenium Test Case using TestNG:
Test Scenario: We will write a basic test case to open google in a chrome session. To automate this scenario, we need to copy the below sample programme into androidTestNGClass.java file.
package androidPackage;
import org.testng.annotations.Test;
import org.testng.annotations.BeforeMethod;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
public class androidTestNGClass { \t
WebDriver driverChrome; \t
@Test
public void f() {
\t //set the chrome driver and location where we store the chromedriver.exe
System.setProperty("webdriver.chrome.driver", "C:\\\\Drivers\\\\chromedriver.exe");
\t
\t //Uppdare driverChrome with chrome driver
\t driverChrome = new ChromeDriver();
\t String url = "https://www.google.com";
\t driverChrome.get(url);
\t //Capturing the title
\t String expectedTitle = "Google";
\t String actualTitle = driverChrome.getTitle();
\t //Validate the title
\t Assert.assertEquals(actualTitle, expectedTitle);
}
@BeforeMethod
public void beforeMethod() {
\t System.out.println("Starting the browser session");
}
@AfterMethod
public void afterMethod() {
\t System.out.println("Closing the browser session");
\t driverChrome.quit();
}
}
We can execute the above test case by clicking on option – “Right-Click on project-> Run As -> TestNG Test”. During the execution, the google website will open in a chrome browser, and the test will verify the title of the web page. At the end of execution, execution log is available in Eclipse Console section.
Step6# Install Maven in Eclipse IDE:
Install Maven plugin from eclipse marketplace(Help->Eclipse Marketplace-> search m2e connector for maven dependency plugin and install). Maven plugin is required while the selenium project is created using Maven Build Tool.
In this VBScript Tutorial, we are going to learn about different kinds of VBScript Conditional Statements (vbscript if else statement & vbscript select case statement) and VBScript Loop Statements (for loop, do while loop & while loop).
VBScript Tutorial #1:VBScript Conditional Statements and VBScript Loop
VBScript Conditional Statements:
Conditions are nothing but some criteria or comparison, based on which we can perform a certain task. VBScript conditional statements are the most important features in VBScript as a programming language. VBScript conditional statements perform different computations or actions based on certain ones or comparisons or conditions. Through the VBScript conditional statements, we can develop functional logic.
In this section, we are going to learn about different VBScript conditional statements, which are frequently used during programming. The frequently used conditional statements are –
· VBScript If Statement
· VBScript Case Statement
VBScript If Statement:
The VBScript If the statement is used to validate one or more conditions through the program. Multiple conditions can be added using logical boolean operators such as AND, OR, NOT, etc. Here, the conditions are the expressions that compare one value or variable with another with the help of comparison operators like equal(=), not equal(!=), Not (!), etc. Based on the verification result, we can perform a specific task.
The conditions should be kept between “If” and “Then” keywords. If there is any task need to be performed based on the false condition, the task has to be performed after the “Else” statement. At the end of the if statement block, we need to close the VBScript if statement by using the keyword “End If.” Structure of VBScript If Statement –
If <Condition1> AND <Condition2> AND .. <Condition3> Then
actions for success case
Else
actions for failure case
End If
VBScript ElseIf Statement:
Through the VBScript ElseIf Statement, we can add multiple VBScript If statements based on the result of the previous conditional result. Nested VBScript ElseIf statements are used while different actions or tasks need to be performed based on each of the conditions. Structure of VBScript If Statement –
If <Condition1> Then
actions for condition 1
ElseIF<Condition2> Then
actions for condition 2
ElseIF<Condition3> Then
actions for condition 3
Else
actions for else condition
End If
Example: Identify Saturday, Sunday, and Business Working Days using VBScript IF statement and VBScript ElseIf statement. Here, we will use more than one ElseIf statements to fulfill our requirements. Also, we can put multiple conditions along with the If statement with the help of ‘AND’ or ‘OR’ operators.
VBScript Select Case Statement:
A VBScript Select Case Statement is an alternative approach to using multiple VBScript IfElse statements. VBScript Select Case statements are used while we have different logics/statements based on the different values against any variable. It’s also known as a switch-case statement. It helps us to write code more efficiently and readable.
A VBScript Select Case statement works with a single test expression that is executed once, at the beginning. The result of the expression will be compared in each case statement. For the match, the block of statements associated with that case will be executed. VBScript Select Case block always should end with the keyword “End Select.” Structure of VBScript Select Case Statement –
Select <Expression> // This Expression can have any value between 1-3
Case1
actions for expression value 1
Case 2
actions for expression value 2
Case 3
actions for expression value 3
Case Else
actions else condition
End Select
For example: Identify Saturday, Sunday, and Business Working Days using if conditions.
VBScript Loop:
When similar kinds of statements need to be executed repeatedly, it’s advisable to write looping statements to make the code more readable and efficient. The VBScript loop works repeatedly based on conditions or the iteration counter. Every VBScript loop has three parts –
· Loop Iterations – It’s basically the loop counter based on these statements that are getting executed.
· Loop Condition – Based on this loop will be executed, and once the condition meets, loop iteration will be completed.
· Loop Statements – it’s basically the repeated activities that are executed based on the condition.
Below VBScript Looping statements are frequently used during the coding –
VBScript For Loop
VBScript While Loop
VBScript Do While Loop
VBScript For Loop:
VBScript For Loop statements is used to execute repeated statements based on the predefined iteration counter. In this structure, the loop will continue until the iteration is reached to the predefined counter value as a condition. The VBScript For Loop should always start with the “For” keyword and end with the keyword “Next.”
While defining the counter in the after “For” keyword, we can specify the increment or decrement of the counter using the keyword “Step.” By default, if we do not use this keyword, VBScript For loop defined the increment by 1. Also, we can use the VBScript Exit For the statement to exit from the loop, which can be placed within any VBScript conditional statements within this looping structure. Structure for “VBScript For Loop” –
For nIteration = <start> to <end> Step <incremet/decrement by>
— Repeatative Statement 1
— Repeatative Statement 2
If <Condition> Then
Exit For
End If
Next
Example – here loop will be executed until the counter value has been reached to 10,
For nIteration = 1 to 10 Step 1
Msgbox “Current Iteration – “ & nIteration
Next
VBScript While Loop:
VBScript While Loop statements are used to execute repeated statements based on one or more conditions. In this structure, conditions are checked at the beginning of the loop. So, if the conditions are not met, the loop will not be executed. The keyword “While” is used to check the condition. We can use the “Exit While” statement to exit from VBScript while loop, which can be used in an IF statement within this looping structure. Structure for “VBScript While Loop” –
While <Loop Condition>
— Repeatative Statement 1
— Repeatative Statement 2
If <Exit Condition> Then
Exit While
End If
Wend
Example – here loop will be executed until the counter value has been reached to 10,
VBScript Do While Loop:
VBScript Do While Loop statements are used to execute repeated statements based on one or more conditions. This loop will be ontinued untill the loop conditions return False. VBScript Do While Loop structure, conditions are checked at the end of the loop. So, irrespective of the conditions are meet or not; the loop statements are always executed for the first iteration. We can use the “Exit Do” statement to exit from this loop, which can be placed in any conditional statement within this looping structure.
The keyword “While” is used to check the condition. The main difference between VBScript Do While Loop and VBScript While Loop statement is the position of the conditional statement. Structure for VBScript “Do While Loop” –
Do
— Repeatative Statement 1
— Repeatative Statement 2
If <Exit Condition> Then
Exit Do
End If
Loop While <Loop Condition>
Example – here loop will be executed until the counter value has been reached to 10,
Conclusion:
In this VBScript article, we have learned about the VBScript Conditional Statements (vbscript if else statement & vbscript select case statement) and VBScript Loop Statements (for loop, do while loop & while loop).. We hope this tutorial has helped a lot to brush up on your basics of VB Scripting. If you want to learn more about VBScript, please click here.
Arrays are an essential data structure in programming that allow us to store and organize multiple values under a single variable name. They are a fundamental concept in many programming languages, including Python, Java, and C++. In this section, we will explore what arrays are, how they are used, their properties, advantages, indexing types, array types, and the time complexity associated with arrays.
What are Arrays?
An array is a collection of elements of the same type, grouped together under a single variable name. Each element in an array is assigned a unique index, starting from 0 for the first element. This index allows us to access and manipulate individual elements within the array. Arrays provide a convenient way to store and retrieve multiple values efficiently.
Example of Array
To better understand arrays, let’s consider an example. Suppose we want to store the temperatures of a week. We can create an array called “temperatures” and assign each day‘s temperature to a specific index. For instance, temperatures[0] can represent Monday’s temperature, temperatures[1] can represent Tuesday’s temperature, and so on. By using arrays, we can easily access and modify the temperatures for each day of the week.
Usages of Array
Arrays have various applications in programming. They are commonly used for tasks such as:
Storing and manipulating collections of data
Implementing data structures like stacks, queues, and matrices
Sorting and searching algorithms
Representing images, sound, and other multimedia data
Arrays provide a flexible and efficient way to handle large amounts of data, making them an indispensable tool for programmers.
Array Properties
Arrays have several important properties that make them useful in programming:
Fixed Size: Arrays have a fixed size, meaning the number of elements they can hold is predetermined at the time of creation. Once an array is created, its size cannot be changed.
Homogeneous Elements: Arrays can only store elements of the same type. For example, an array of integers can only hold integer values, and an array of strings can only hold string values.
Random Access: Elements in an array can be accessed directly using their index. This allows for efficient retrieval and modification of specific elements.
Array Advantages
Arrays offer several advantages that make them a popular choice for storing and manipulating data:
Efficient Access: Since elements in an array are stored in contiguous memory locations, accessing elements by their index is fast and efficient.
Easy Manipulation: Arrays provide simple and intuitive ways to add, remove, and modify elements. This makes it easy to perform operations on the entire collection of data.
Memory Efficiency: Arrays use a fixed amount of memory, which is determined by the size and type of elements they store. This makes them memory-efficient compared to other data structures.
Types of Indexing Available in Array
Arrays support two types of indexing:
Zero-based Indexing: In zero-based indexing, the first element of an array is assigned an index of 0. Subsequent elements are assigned sequential indices. For example, in an array with five elements, the indices would be 0, 1, 2, 3, and 4.
One-based Indexing: In one-based indexing, the first element of an array is assigned an index of 1. Subsequent elements are assigned sequential indices. One-based indexing is less common than zero-based indexing but is used in some programming languages.
Types of Arrays
There are several types of arrays, each with its own characteristics and use cases. Some common types of arrays include:
One-dimensional Array: A one-dimensional array is the simplest form of an array. It consists of a single row of elements and is often used to represent lists or sequences of data.
Two-dimensional Array: A two-dimensional array is an array of arrays. It is used to represent tables or matrices, where elements are organized in rows and columns.
Multi-dimensional Array: A multi-dimensional array is an array with more than two dimensions. It can be used to represent complex data structures, such as three-dimensional graphics or multi-dimensional datasets.
Time Complexity of Array
The time complexity of array operations is an important consideration when working with arrays. The time complexity refers to the amount of time it takes to perform an operation on an array, and it is typically expressed in terms of the number of elements in the array.
Accessing an element in an array using its index has a time complexity of O(1), which means it takes constant time regardless of the size of the array.
Inserting or deleting an element at the beginning or middle of an array has a time complexity of O(n), where n is the number of elements in the array. This is because shifting elements after the insertion or deletion point is required.
Inserting or deleting an element at the end of an array has a time complexity of O(1), as it does not require shifting elements.
Understanding the time complexity of array operations is crucial for writing efficient and optimized code.
In the next sections, we will dive deeper into each type of array and explore their syntax, manipulation techniques, and examples. Stay tuned to expand your knowledge of arrays!
How to Declare Arrays
Arrays are an essential data structure in programming that allow you to store multiple values of the same type in a single variable. They provide a convenient way to organize and manipulate data. In this section, we will explore how to declare arrays in different programming languages.
How to Declare Arrays in Java
In Java, declaring an array involves specifying the type of the elements it will hold, followed by the name of the array variable and square brackets. Here’s the syntax:
java
dataType[] arrayName;
For example, to declare an array of integers called numbers, you would write:
java
int[] numbers;
You can also declare and initialize an array in one line by providing the values inside curly braces:
java
int[] numbers = {1, 2, 3, 4, 5};
It’s important to note that arrays in Java have a fixed size, meaning you need to specify the number of elements the array can hold when declaring it. Once the size is defined, it cannot be changed.
How to Declare Arrays in Python
Python provides a more flexible approach to declaring arrays, known as lists. Lists in Python can hold elements of different types and can grow or shrink dynamically. To declare a list, you simply assign values to a variable using square brackets:
python
listName = [value1, value2, value3]
For example, to declare a list of strings called fruits, you would write:
python
fruits = ["apple", "banana", "orange"]
Unlike Java, you don’t need to specify the type of elements in a Python list. Python automatically determines the type based on the values you assign.
How to Declare Arrays in C
In C, declaring an array is similar to Java, where you specify the type of elements followed by the name of the array variable and square brackets. Here’s the syntax:
c
dataType arrayName[size];
For example, to declare an array of integers called numbers with a size of 5, you would write:
c
int numbers[5];
You can also declare and initialize an array in one line by providing the values inside curly braces:
c
int numbers[] = {1, 2, 3, 4, 5};
Similar to Java, arrays in C have a fixed size that cannot be changed once declared.
Summary
In this section, we learned how to declare arrays in Java, Python, and C. Java requires you to specify the type of elements and the size of the array, while Python allows for dynamic resizing and doesn’t require type specification. C, like Java, requires you to specify the type and size of the array. Understanding how to declare arrays is fundamental to working with arrays and manipulating data efficiently in different programming languages.
How to Access Array Elements
How to Access Array Elements in Java
In Java, arrays are a fundamental data structure that allows you to store and manipulate multiple values of the same type. Accessing array elements in Java is straightforward and can be done using the index of the element within the array.
To access an array element in Java, you need to specify the index of the element you want to retrieve. The index starts from 0 for the first element and increments by 1 for each subsequent element. For example, if you have an array called numbers with 5 elements, you can access the third element using numbers[2].
Here’s an example that demonstrates how to access array elements in Java:
java
int[] numbers = {1, 2, 3, 4, 5};
int thirdElement = numbers[2]; // Accessing the third element
System.out.println(thirdElement); // Output: 3
In the example above, we have an array numbers with 5 elements. We access the third element by using the index 2 within square brackets. The value of the third element, which is 3, is then assigned to the variable thirdElement. Finally, we print the value of thirdElement, which outputs 3.
How to Access Array Elements in Python
Python also provides a simple and intuitive way to access array elements. In Python, arrays are called lists, and you can access list elements using the same indexing approach as in Java.
To access an element in a Python list, you need to specify the index of the element within square brackets. Similar to Java, the index starts from 0 for the first element. For example, if you have a list called fruits with 4 elements, you can access the second element using fruits[1].
Let’s take a look at an example of accessing array elements in Python:
python
fruits = ["apple", "banana", "orange", "grape"]
second_element = fruits[1] # Accessing the second element
print(second_element) # Output: banana
In the example above, we have a list fruits with 4 elements. We access the second element by using the index 1 within square brackets. The value of the second element, which is "banana", is then assigned to the variable second_element. Finally, we print the value of second_element, which outputs "banana".
How to Access Array Elements in C
In C, accessing array elements follows a similar indexing approach as in Java and Python. C arrays are zero-indexed, meaning the first element has an index of 0, the second element has an index of 1, and so on.
To access an element in a C array, you need to specify the index of the element within square brackets. For example, if you have an array called scores with 3 elements, you can access the third element using scores[2].
Here’s an example of accessing array elements in C:
c
int scores[] = {85, 90, 95};
int third_element = scores[2]; // Accessing the third element
printf("%d\n", third_element); // Output: 95
In the example above, we have an array scores with 3 elements. We access the third element by using the index 2 within square brackets. The value of the third element, which is 95, is then assigned to the variable third_element. Finally, we print the value of third_element, which outputs 95.
Accessing array elements is a fundamental operation when working with arrays in any programming language. By understanding how to access array elements, you can retrieve and manipulate specific values within an array to perform various tasks in your programs.
Using Array Length
Arrays are a fundamental data structure in programming that allow us to store multiple values of the same type in a single variable. One important aspect of working with arrays is determining their length, which refers to the number of elements they contain. In this section, we will explore how to use array length in different programming languages such as Java, Python, and C.
How to Use Array Length in Java
In Java, arrays are objects that have a built-in property called length which returns the number of elements in the array. To access the length of an array, you simply append .length to the array variable. Let’s take a look at an example:
java
int[] numbers = {1, 2, 3, 4, 5};
int length = numbers.length;
System.out.println("The length of the array is: " + length);
In this example, we have an array called numbers that contains five elements. By calling numbers.length, we retrieve the length of the array and store it in the variable length. Finally, we print out the length using System.out.println().
How to Use Array Length in Python
Python also provides a way to determine the length of an array. However, in Python, arrays are called lists. To get the length of a list, we can use the len() function. Here’s an example:
python
numbers = [1, 2, 3, 4, 5]
length = len(numbers)
print("The length of the list is:", length)
In this Python example, we have a list called numbers that contains the same elements as the Java array. By calling len(numbers), we obtain the length of the list and assign it to the variable length. Finally, we print out the length using the print() function.
How to Use Array Length in C
In C, arrays do not have a built-in property or function to directly retrieve their length. However, we can calculate the length of an array by dividing the total size of the array by the size of each element. Let’s see an example:
“`c
include
int main() {
int numbers[] = {1, 2, 3, 4, 5};
int length = sizeof(numbers) / sizeof(numbers[0]); printf(“The length of the array is: %d\n”, length);
return 0;
}
“`
In this C example, we declare an array called numbers and initialize it with five elements. To calculate the length, we use the sizeof() operator to get the total size of the array and divide it by the size of each element (sizeof(numbers[0])). Finally, we print out the length using printf().
By understanding how to use array length in different programming languages, you can effectively manipulate arrays and perform various operations based on the number of elements they contain. Whether you’re working with Java, Python, or C, the ability to determine array length is a valuable skill that will enhance your programming capabilities.
Looping through Arrays
Arrays are a fundamental data structure used in programming to store multiple values of the same type. Once we have created an array and populated it with elements, we often need to perform operations on each element. This is where looping through arrays becomes essential. In this section, we will explore how to use loops to iterate through arrays in different programming languages.
How to Use a Loop in Array in Java
Java provides several ways to loop through an array. One common approach is to use a for loop. Here’s an example:
“`java
int[] numbers = {1, 2, 3, 4, 5};
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}
“`
In this code snippet, we declare an array called numbers and initialize it with some values. Then, we use a for loop to iterate through the array. The loop starts at index 0 and continues until it reaches the last index (numbers.length - 1). Inside the loop, we access each element of the array using the index i and perform the desired operation.
Another way to loop through an array in Java is by using a for-each loop. This type of loop simplifies the syntax and makes the code more readable. Here’s an example:
“`java
int[] numbers = {1, 2, 3, 4, 5};
for (int number : numbers) {
System.out.println(number);
}
“`
In this code snippet, we declare an array called numbers and initialize it with some values. Then, we use a for-each loop to iterate through the array. The loop automatically assigns each element of the array to the variable number, allowing us to directly access and manipulate the elements without worrying about indices.
How to Use a Loop in Array in Python
Python offers various ways to loop through an array. One common approach is to use a for loop. Here’s an example:
“`python
numbers = [1, 2, 3, 4, 5]
for number in numbers:
print(number)
“`
In this code snippet, we define a list called numbers and populate it with some values. Then, we use a for loop to iterate through the list. The loop assigns each element of the list to the variable number, allowing us to perform operations on each element.
Another way to loop through an array-like structure in Python is by using the range() function and a for loop. Here’s an example:
“`python
numbers = [1, 2, 3, 4, 5]
for i in range(len(numbers)):
print(numbers[i])
“`
In this code snippet, we use the range() function to generate a sequence of indices that correspond to the elements in the numbers list. We then use a for loop to iterate through these indices and access the elements of the list using the index i.
How to Use a Loop in Array in C
C provides different ways to loop through an array. One common approach is to use a for loop. Here’s an example:
“`c
include
int main() {
int numbers[] = {1, 2, 3, 4, 5};
int length = sizeof(numbers) / sizeof(numbers[0]);
for (int i = 0; i < length; i++) {
printf("%d\n", numbers[i]);
}
return 0;
}
“`
In this code snippet, we declare an array called numbers and initialize it with some values. We also calculate the length of the array using the formula sizeof(numbers) / sizeof(numbers[0]). Then, we use a for loop to iterate through the array. The loop starts at index 0 and continues until it reaches the last index (length - 1). Inside the loop, we access each element of the array using the index i and perform the desired operation.
Another way to loop through an array in C is by using a while loop. Here’s an example:
“`c
include
int main() {
int numbers[] = {1, 2, 3, 4, 5};
int length = sizeof(numbers) / sizeof(numbers[0]);
int i = 0;
while (i < length) {
printf("%d\n", numbers[i]);
i++;
}
return 0;
}
“`
In this code snippet, we declare an array called numbers and initialize it with some values. We also calculate the length of the array using the formula sizeof(numbers) / sizeof(numbers[0]). Then, we use a while loop to iterate through the array. The loop continues as long as the conditioni < length is true. Inside the loop, we access each element of the array using the index i and perform the desired operation.
By using loops, we can efficiently iterate through arrays and perform operations on each element. Whether you’re working with Java, Python, or C, understanding how to loop through arrays is a crucial skill in programming.
Important Questions on Arrays
Qn 1: Can we change the Array size in Java?
In Java, the size of an array is fixed once it is declared. This means that once you create an array with a specific size, you cannot change its size later on. The size of an array is determined at the time of its creation and cannot be modified dynamically. If you need to store more elements in an array than its initial size allows, you would need to create a new array with a larger size and copy the elements from the old array to the new one.
Qn 2: What is ArrayStoreException?
An ArrayStoreException is a type of exception that is thrown when you try to store an element of an incompatible type in an array. In Java, arrays are homogeneous, which means that they can only store elements of the same type. If you attempt to store an element of a different type in an array, the JVM will throw an ArrayStoreException. For example, if you have an array of integers and you try to store a string in it, an ArrayStoreException will be thrown.
Qn 3: What is ArrayIndexOutOfBoundsException?
An ArrayIndexOutOfBoundsException is a type of exception that is thrown when you try to access an array element using an invalid index. In Java, array indices start from 0 and go up to array.length - 1. If you try to access an element using an index that is outside this range, the JVM will throw an ArrayIndexOutOfBoundsException. For example, if you have an array of size 5 and you try to access the element at index 6, an ArrayIndexOutOfBoundsException will be thrown.
Qn 4: What is the difference between ArrayStoreException and ArrayIndexOutOfBoundsException?
The main difference between an ArrayStoreException and an ArrayIndexOutOfBoundsException is the cause of the exception.
ArrayStoreException is thrown when you try to store an element of an incompatible type in an array.
ArrayIndexOutOfBoundsException is thrown when you try to access an array element using an invalid index.
In other words, ArrayStoreException occurs during the assignment of values to an array, while ArrayIndexOutOfBoundsException occurs during the retrieval of values from an array. Both exceptions indicate that there is an issue with the array operation being performed.
Qn 5: How to initialize an array with array size in Java?
To initialize an array with a specific size in Java, you can use the array declaration syntax and specify the desired size within square brackets. Here’s an example:
java
int[] numbers = new int[5];
In this example, we declare an integer array named numbers with a size of 5. This means that the array can store 5 integer values. The elements of the array are automatically initialized to their default values (0 in the case of integers). You can then assign values to individual elements of the array using their indices.
Qn 6: How to initialize an array with predefined values?
To initialize an array with predefined values in Java, you can use the array initializer syntax. Here’s an example:
java
int[] numbers = {1, 2, 3, 4, 5};
In this example, we declare an integer array named numbers and initialize it with the values 1, 2, 3, 4, and 5. The size of the array is automatically determined based on the number of elements specified within the curly braces. You can access individual elements of the array using their indices, starting from 0.
Qn 7: How to sort an array in Java?
To sort an array in Java, you can use the Arrays.sort() method from the java.util package. Here’s an example:
In this example, we have an integer array named numbers with the values 5, 2, 8, 1, and 9. By calling Arrays.sort(numbers), the elements of the array will be rearranged in ascending order. After sorting, the numbers array will contain the values 1, 2, 5, 8, and 9.
Qn 8: How to convert an array to a String?
To convert an array to a string representation in Java, you can use the Arrays.toString() method from the java.util package. Here’s an example:
In this example, we have an integer array named numbers with the values 1, 2, 3, 4, and 5. By calling Arrays.toString(numbers), the array is converted to a string representation. The resulting string will be “[1, 2, 3, 4, 5]”. This can be useful when you need to display the contents of an array as a string or when you want to concatenate the array with other strings.
Qn 9: How to copy an array?
Copying an array is a common operation in programming, and it allows you to create a new array with the same elements as an existing array. This can be useful when you want to manipulate the elements of an array without modifying the original array. In this section, we will explore different methods to copy an array in various programming languages.
Method 1: Using a loop
One way to copy an array is by using a loop. This method is straightforward and can be implemented in most programming languages. Here’s an example in Python:
“`python
Original array
original_array = [1, 2, 3, 4, 5]
Create a new array
copied_array = []
Copy the elements using a loop
for element in original_array:
copied_array.append(element)
Print the copied array
print(copied_array)
“`
In the above example, we iterate over each element in the original array and append it to the new array. This creates a copy of the original array.
Method 2: Using the slice operator
Another method to copy an array is by using the slice operator. The slice operator allows you to extract a portion of an array, and by specifying the entire array, you can create a copy of it. Here’s an example in JavaScript:
// Copy the array using the slice operator
const copiedArray = originalArray.slice();
// Print the copied array
console.log(copiedArray);
“`
In the above example, we use the slice() method without specifying any arguments. This creates a copy of the original array.
Method 3: Using library functions
Many programming languages provide library functions or methods specifically designed for copying arrays. These functions can simplify the process and make the code more concise. Here’s an example in Java:
“`java
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
// Original array
int[] originalArray = {1, 2, 3, 4, 5};
// Copy the array using the copyOf() method
int[] copiedArray = Arrays.copyOf(originalArray, originalArray.length);
// Print the copied array
System.out.println(Arrays.toString(copiedArray));
}
}
“`
In the above example, we use the copyOf() method from the Arrays class in Java to copy the array. This method takes the original array and the length of the array as arguments and returns a new array with the same elements.
Method 4: Using built-in functions
Some programming languages have built-in functions that allow you to copy arrays directly. These functions are often optimized for performance and can be more efficient than other methods. Here’s an example in C++:
“`cpp
include
include
int main() {
// Original array
std::vector originalArray = {1, 2, 3, 4, 5};
// Copy the array using the assignment operator
std::vector<int> copiedArray = originalArray;
// Print the copied array
for (int element : copiedArray) {
std::cout << element << " ";
}
return 0;
}
“`
In the above example, we use the assignment operator (=) to copy the array. This creates a new vector with the same elements as the original vector.
Copying an array is a fundamental operation in programming, and understanding different methods to accomplish this task can be beneficial. Whether you choose to use a loop, the slice operator, library functions, or built-in functions, the goal remains the same – creating a new array with the same elements as the original array. Experiment with these methods in your preferred programming language to gain a better understanding of how arrays can be copied. Conclusion
In conclusion, arrays are a fundamental concept in programming that allow us to store and manipulate multiple values of the same data type. They provide a convenient way to organize and access data efficiently. In this tutorial, we have learned the basics of arrays, including how to declare and initialize them, how to access and modify elements, and how to perform common operations such as sorting and searching. We have also explored some advanced topics like multidimensional arrays and arrays of objects. By understanding arrays and practicing their usage, we can become more proficient in solving problems and writing efficient code. Arrays are an essential tool in any programmer’s toolkit, and mastering them will greatly enhance our ability to write robust and efficient programs.
Frequently Asked Questions
Q1: When should I use arrays?
A1: Arrays are useful when you need to store and access multiple values of the same type. They provide a convenient way to organize and manipulate data efficiently.
Q2: How can I learn arrays?
A2: To learn arrays, you can start by understanding the basics of array concepts and syntax. Then, you can explore array manipulation, operations, and indexing. There are various tutorials and resources available online to help you learn arrays in different programming languages like JavaScript and Java.
Q3: What are the basics of arrays?
A3: Array basics involve understanding the array data structure, its implementation, and the various functions and methods available for working with arrays. It is essential to grasp concepts like array elements, array indexing, and how to perform common operations on arrays.
Q4: Are there any array tutorials for beginners?
A4: Yes, there are many array tutorials available for beginners. These tutorials provide step-by-step guidance on understanding arrays, their syntax, and how to work with them effectively. They often include examples and exercises to reinforce your learning.
Q5: How can I learn arrays in JavaScript?
A5: To learn arrays in JavaScript, you can start with online resources that offer tutorials specifically focused on JavaScript arrays. These tutorials cover array basics, array methods, and provide examples to help you understand and practice working with arrays in JavaScript.
Q6: Can you provide some examples of array exercises?
A6: Sure! Here are a few examples of array exercises you can try:
– Write a program to find the sum of all elements in an array.
– Sort an array in ascending order.
– Remove duplicate elements from an array.
– Find the maximum and minimum values in an array.
– Reverse the order of elements in an array.
Q7: What is the difference between array fundamentals and array introduction?
A7: Array fundamentals refer to the core concepts and principles of arrays, such as their structure, indexing, and operations. Array introduction, on the other hand, provides a basic overview and introduction to arrays, including their purpose and usage.
Q8: Are there any specific array functions or methods?
A8: Yes, arrays come with built-in functions and methods that allow you to perform various operations on them. Some common array functions include length, push, pop, slice, and concat. These functions help you manipulate and work with arrays more efficiently.
Q9: How can I understand arrays better?
A9: To understand arrays better, it is recommended to practice working with them through examples and exercises. Additionally, studying array concepts, syntax, and exploring different array manipulation techniques will help you gain a deeper understanding of arrays.
Q10: Are arrays used in basic algebra?
A10: Arrays are not typically used in basic algebra. Basic algebra focuses on mathematical equations and formulas rather than data structures like arrays. However, arrays can be used in programming to solve algebraic problems or store algebraic expressions if needed.
In this VBScript Tutorial, we are going to learn VBScript Variables, VBScript Array, VBScript Constants, and Dictionary Object in VBScript.
VBScript Tutorial #1:VBScript Variables
VBScript is the shorter form of Visual Basic Scripting which follows the Visual Basic language. The VBScripting was introduced by Microsoft. It’s a very simple languages to learn which allows to develop server-side as well as client-side scriptings.
VBScript Features:
· It is a simple scripting language.
· It is case insensitive and easy to learn for any entry-level programmer.
· It is an object-based programming language and does not follow the OOPS concept.
· It supports the COM which is a shorter form of Component Object Model (COM) structure. It allows to manage the elements from the environment where it is getting executed.
· The VBScripting which executed in server side, is compatible with hosting platform such as Internet Explorer web browser, Internet Information Services (IIS) as web server and Windows Scripting Host (WSH).
· It can be used to develop both server-side(Classic ASP) and client-side scripting.
· VB Scripts are supported in internet explorer only. The web browsers which are well known in market like Mozila Firefox, google Chrome etc., are not compatible with VBScript.
· It is platform-dependent i.e., only supported by windows environment.
· The debugging of VBScript is challenging as there is non availability of proper development area.
VBScript Comment:
The purpose of the VBScript comment is to educate the compiler to skip the particular line or lines of code from the execution. Basically, VBScript comments are used to document or write the descriptions/objectives during the scripting. It will help to increase the readability of the code block by writing the description, change the log using the commenting. Two types of VBScript comments are available –
Single line VBScript comment: It’s done by using the single quote ( ‘ ) at the beginning of each line. Example of single-line comment in VBScript –
‘ Single line comment example
Multiple lines VBScript comment: Multiple lines VBScript comment is used to comment on more than one line. This type of VBScript comment can be achieved by putting more lines between “/*” and “*/” symbols. Example of multiple lines VBScript comment –
/*
VB Statement 1
VB Statement 2
….. and so on
*/
VBScript Variables:
The VBScript variables are one kind of placeholders which refer memory locations to store data. During the execution, VBScript allows to modify the variables. The declared name of VBScript variables are used to access the variables for reading or writing purposes. The variables have the ability to interact with any data types such as string, char, number, date, etc. As per the data types, the vbscript variables are changed accordingly. For an example – if we assign a number within double quote, it will be treated as string value.
We can declare VBScript variables in three ways which are explained below –
VBScript dim
VBScript public
VBScript private
VBScript Dim:
Dim stands for declare immediate. It means, VBScript dim allows to declare a variable immediately for any kinds of data types. We can declare multiple variables which are separated by comma, with a single VBScript dim statement. The scope of which are declared using VBScript dim statement, are restricted with in the code block such as functions, sub-procedures, local scripts etc., where it was declared. Below examples has shown the syntax of VBScript dim statement for variable declaration – ,
Dim var1
Dim var1, var2, var3
Using the keyword dim, we can declare the variables immediately with specifying the logical name of the variables. It is mandatory to declare the each of the variables if we specifying the statement “Option Explicit” at the starting of the script. So, if the statement does not specified, the variable declaration is an optional step. In this case, the variables are auto declared while defining the variables.
VBScript Public:
When variables are declared with the keyword public, the variables are accessible from through out the entire script. Basically, public keyword is used to define a variable as global variable.
VBScript Private:
When variables are declared with the keyword private, the scope of the variables are restricted to with in the code block.
Assigning Values to VBScript Variables:
In the below example, we will declare (using VBScript dim satement) assign values such as number and string to the variables with the help of equal(=) symbol,
'''''declare variables using VBScript dim statement
dim numVar
dim strVar
'''''define the variables - number and string
numbVar = 12345667788
strVar = "This is sample variable"
While assigning values to the variable, we need to keep the variable name in the left side of equal symbol and value has to be kept in the right side. For strings or characters, we need to keep the value with in double quote.
Scalar Variables – Defining a variable with single value, is known as scalar variable.
Array Variables –Conceptually an array represents a list of values. In VBScript, when a variable is assigned with multiple same type of values, is know as an array. Array can be declared with parenthesis after the variable name. It can be declared in same way how we declare a variable. The structure to declare an array is shown below –
Dim myArrayName(max index)
Here the index is used to refer the each elements of an array which start from zero. So, the max index denotes the length of array minus one. Values can be assigned to the each array element using the array indexes. In the below example, we will define an array which holds 3 student names –
' Declare an array with VBScript dim statement
Dim arrStudentName(2)
' Assigning the student names using the index
arrStudentName(0) = "Tom"
arrStudentName(1) = "Jack"
arrStudentName(2) = "Jerry"
VBScript Variables – Naming Convention:
Syntactically, there is no specific naming conventions are available. But it advisable to follow the below guidelines for better readability of scripts,
· The starting character of a variable should be alphabetic.
· Any embedded period should not be kept.
The name of the variable should be logical as per the usage.
Length should not cross the limit of 255 characters.
VBScript Constants:
The value of VBScript constant variable can not be modified after definition. So, the constant variable is basically a read-only variable. It has to defined during the declaration. The VBScript provides default constant variable which can be used during scripts. The example of default constants are – vbOK, vbCancel, vbTrue, vbFalse, etc. The Const keyord is used to declare a constant in VBScripting. Below example, we will see how to define constant variables for number and strings –
Const strConstant= “This is my string.”
Const numConstant = 123
VBScript Array:
Conceptually an array represents a list of values. In VBScript, when a variable is assigned with multiple same type of values such as string, integer, etc., is know as an array. The VBScripts allows to keep the list of same type values in the same memory location(VBScript array). The each array elements can be accessed using the reference numbers which is known as array index. The index is always starts from zero.
Structure wise, VBScript Array has two sections – the logical name of array name and the array subscript that denotes the highest index value. The array subscript is equals to the length of array minus one.
The VBScript array has to be declared first, otherwise it will throw errors. Similar to the variable declaration, we can declare the VBScript array using the dim statement. By considering usage or scope, VBScript two type of arrays –
· Local VBScript Array – The scope of this type arrays are restricted to the code block (functions or sub procedures) where it was declared.
· Global VBScript Array – We can use this type of arrays throughout the scripts. This type of arrays should be declare at the beginning of the script.
Static and Dynamic Arrays:
Also, we can declare the VBScript array as static or dynamic while creating the scripts.
A static VBScript array – It has a fixed number of array elements which can not be altered during the script execution.
A dynamic VBScript array – The number of array element can be changed at anytime. When the number of elements are not fixed or pre-defined, we can use this array.
Working with VBScript Arrays:
Syntax for array declaration – Dim myArray(subscript value)
In the below example, we will create an VBScript array of marks of 3 students and store the calculated average marks into a variable –
'Declaration of array and value assignment for three students
dim arrMarks(2)
arrMarks(0) = 10
arrMarks(1) = 15
arrMarks(2) = 20
'Calculate the average and store it in a variable
Dim avgMarks
avgMarks = (arrMarks(0)+arrMarks(1)+arrMarks(2))/3
Dictionary Object in VBScript:
The dictionary object in VBScripts, has the similarity with the VBScript array. Which means, it’s also allowing to store a list of values. But the primary differences of dictionary object in VBScript, are that it can holds different types of data and a key has to be assigned for each data instead of indexes.
The dictionary object in VBScript can be declared for usages with the reference of “Scripting.Dictionary” class.
Advantages of Dictionary Object in VBScript:
· Different types of data can be stored in a single variable.
· With the help of key, we can access the corresponding elements easily.
· This concept is very flexibles as there is predefined methods are available to manipulate the dictionary object in vbscript.
Example – Dictionary Object in vbscript:
In the below example, we will see the codes for different operations on dictionary objects –
' **** Create a Dictionary Object in VBScript ****
'Create a variable.
Dim dict
Set dict = CreateObject("Scripting.Dictionary")
'Adding keys and items.
dict.Add "Name", "VBScript"
dict.Add "Id", "1"
dict.Add "Trainer", "K Mondal"
'**** Checking the availability of a Key from the dictionary object in VBScript ****
If dict.Exists("Name") Then
msg = "The name key exists"
Else
msg = "The name key does not exists"
End If
'Read an item
dim sName
sName = dict.Item("Name")
'get the count of element
dim nCount
nCount = dict.count
'Delete single item
dict.Remove("Name")
'Delete All item
dict.RemoveAll
Conclusion:
In this VBScript article, we have learned about the Overview of VBScript Variables, VBscript Array, VBScript Constants, and Dictionary Object in VBScript. For more details on VBScript, please click here.
In this tutorial, we will discuss about data structures from the basics. We will understand the different types of data structures and their uses and how we can implement them.
What is data structure?
A data structure is a collection of data that can be stored in an organised manner so that the data can be accessed, modified efficiently.
Data Structures usages
Data structures are used in different kinds of applications like relational databases, which use B-tree indexes to retrieve the data.
Hash table is used in compiler design.
These are used in different algorithms like searching, sorting.
Internet indexing service uses data structures.
Types of the Data structures
Types of DS
Sub type
Linear
Array
Linked List
Stack
Queue
Tree
Binary Tree
Binary Search Tree
Heap
Hashing
Hash Table
Hash Tree
Graph
Decision Graph
Directed graph
Matrix
What is Linear data structure ?
A linear data structure is a type of data structure where data can be traversed sequentially. Array, Linked list, stack, queue are examples of linear data structure. Please go through below image for the details:
What is Tree Data Structure
A tree data structure is a hierarchical data structure. It has nodes that are connected by edges.Please go through below image for the details:
What is hashing
Hashing is a data structure which uses a hash function to map the data in a key-value pair to retrieve the data faster. Examples of Hashing are Hash table, Hash tree. Please go through below image for the details:
What is graph
A Graph is a non-linear, pictorial representation of data consisting of edges and vertices. Please go through below image for the details:
Difference between linear and non-linear data structure
Sl No
Key points
Linear data structure
Non-linear data structure
1
Data alignment
Data gets stored sequentially
Data gets stored in hierarchy form
2
Levels
Single level involved
Multiple level involved
3
Complexity
Easy to implement
Implementation is complex
4
Traversal
Data can be traversed in single run
Data cannot be traversed in a single run rather need multiple runs
5
Utilisation of memory
Not efficient
Efficient
6
Examples
Array, Linked list, stack, queue
Graph, tree
7
Application
Used in software development
Used in Image Processing, Voice Processing, Artificial Intelligence
Some import Questions and Answers on Data Structure
Qn 1. What do you mean by ADT in Data structure?
Ans: ADT means Abstract Data type. Class or Objects are an example of ADT. When We use and Class or Object, we define the behavior by a set of values and a set of operations. ADT only tells us what operation has to perform. It does not tell us how the operation has been internally implemented.
For Example :
List
size() -> Size gives us the number of elements, but it does not show how internally it calculates to give the result.
insert(x) -> insert helps us to insert the element but does not tell how the logic is written.
remove(x) -> Similarly remove method is used to remove the elements without telling the implementation.
get(i) -> get is used to access the elements.
Qn 2. What are the advantages of data structure?
Ans:
Using Data Structure, we can efficiently store data in a storage device.
Data structure gives an easy option to retrieve the data from a storage device.
It can process small as well as large numbers of data efficiently
Using data structures like graph we can solve real-life problems
Database systems uses indexing using a hash table and array to retrieve the data efficiently.
Qn 3. What is primitive data structure?
Ans: Primitive data structures are system-defined data types supported by different programming languages. Example: int, double, float, boolean, character.
Qn 4. What is a Complex Data structure?
Ans: Data structures like Hash table, Tree, Heap, Graph are called a complex data structure. The implementation of these data structures is complex in nature.
Qn 5. What are the two main types of data structure?
Ans: Mainly, data structures are divided into two parts:
Linear Data structure: Stack, Queue, Array, Linked List
Non-linear Data Structure: Tree, Graph
Conclusion
Till now, We have covered the basics of Data Structure. In the next topic, we will write about the Array. For more details for this section, please refer to this link.
Tosca is now become one of the leading test automation tool which follows the script less methodology. Through out the entire Tosca tutorial, we have already learned about the different Tosca components and test automation approach. Now we are going to explain the concepts of API Testing in TOSCA.
In this “API Testing in TOSCA” article, we will explain the overview of API and the detailed steps of automated API Testing in TOSCA.
API Testing in Tosca
What is API?
API is the shorter form of Application Program Interface. It’s working as an interface which allows two applications to communicate with each other through common message formats such as, XML, JSON, etc. Let’s consider the below figure to understand more on API–
Assume, we have four different applications – SAP App, Mobile Apps, Web Portal and Billing System, which are integrated by common interface as API. Here API is working as an interpreter. Each of the system interacting with each other by sending an API request and receiving the API response. Basically, each system is communicating with API and based on the request, API routes the messages to the target system.
Purposes of API:
Communicate between different applications.
It’s platform-independent.
Development of one system is not dependant with another.
Fast and secure communication.
Easy to integrate many applications.
Different Types of API:
REST API (Representational State Transfer): It’s a web service API which is now an essential part of modern web-based applications such as, Facebook, Netflix, etc. REST API should comply with below standards –
Stateless – It does not allow to store the data they received from a requestor.
Client-Server Architecture – Client and Server’s REST APIs should be independent with each other.
Cache – The cache is storing the browsing data for a specific period of time.
Uniform Interface – Communication should be HTTP requests using URL, CRUD(Create, Read, Update, Delete) and JSON.
Layered System – REST APIs should use different architecture layers which contributes towards a clear hierarchy.
Code on demand – It’s an optional rule to transmit code within the application through the API.
RPC API (Remote Procedure Call): These are the simplest API which is used from old days. The aim of RPC is to execute code on the server system. It was easier for application developers to develop applications involving more programs or services in the RPC API.
There are two types of RPC APIs – XML-RPC and JSON-RPC.
SOAP API (Simple Object Access Protocol): It is also one kind of web API. SOAP is the first to define the process about the applications to use a network connection to manage services. It’s a special protocol which is defined by the World Wide Web Consortium (W3C).
API Testing in TOSCA:
Before understanding the API Testing in TOSCA, first, we need to understand the “What is API Testing?”.
What is API Testing?
The API Testing is an approach to test the API components of any software product in efficient way. To perform API testing, we need to validate the API response received based on the API request. The main moto of API testing is to test the core functionality, reliability, performance and security through the API. API Testing is ideal for testing the core functionality of the application when the all the application is partially developed. So, it allows us to start the testing before the integration of the software components.
For more information on API Testing, please click here.
API Testing in TOSCA:
The goal of API testing is to ensure that the core functionalities of the application work as expected without interacting in the UI layer. To perform the API Testing, always, we need to take help from any third party tools like Postman, UFT, TOSCA, etc.
Here, TOSCA is one of the best automation tools for API Testing.
Benefits API Testing in TOSCA:
API testing can be used to validate the core functionalities even when the UI hasn’t been developed/modified. Hence testing can be initiated much before actual functional testing (UI based) is done.
Frequent application changes can be tested quickly.
It is easy to maintain test cases in TOSCA.
The API testing in TOSCA can be done much faster.
Standalone Tosca API Scanning Wizard is available to scan the API in the easiest way.
Step2# Identify Scenarios and data formats for the API Request.
Test Scenario – After logging into the sample swagger application, need to add a new coffee brand and verify.
Data Format – Data need to be passed through JSON format.
Step3# Manually Verify the scenario using tools like Postman (Optional). Please go through the article on Postman to understand the process to test the API.
Step4#Scan the API with the endpoint reference. Scanning steps are mentioned below –
1) Open the API Scan wizard from “API Testing” tab available in TOSCA Header section.
2) Click on URI button and enter the endpoint address. Now click on OK to start scanning.
3) After a few moments, API scan will be completed, and scanned API modules are displayed in the API Scan Wizard.
Step5# Create modules and test cases – Selecting the root folder, i.e. “Swagger Demo CoffeeShop V2”, click on “API Test Case” to generate modules and test cases in the TOSCA. For every transaction, there are two parts – one for request and another for the response.
Step6#Cleanup scenarios: Auto-generated test cases can be used as a base suite which needs to be cleaned by removing the unwanted folders, create module attributes to parametrize the response values such as, authentication token which will be required to perform any transaction.
Post Coffee (Modules for API Request) –
After assigning the parameters, the API Test Case will look like below,
Step7# Execute API Test Case in TOSCA – First of all, we need to add the newly created test case into the execution list. Now, the execution can be initiated by clicking on “Run” button. As it’s an API Testing, no application UI will be visible through out the execution. After completion of execution, Report will look like below,
Conclusion:
In this “API Testing in TOSCA” article, we have learned about API and API Testing in TOSCA. To know more on API testing in Tosca from Tricenties support portal, please click here.
Testing is now an essential phase of the software development life cycle to secure the product’s quality. Also, without having testing, we can’t ensure the fulfillment of all the requirements. Here automation is playing an essential role in the testing cycle to reduce the efforts and time. In the market, there are multiple testing tools available to automate the testing process. The most used automation testing tool is UFT.
In this UFT Tutorial, we are going to learn the below topics –
Automation recording in uft is an option to record the manual navigation in the test application through the UFT tool to generate the linear test scripts. All the data in the recoded scripts are hardcoded. The record and play approach is ideal for one-time execution. But for the longer run, we need to modify the recoded test cases to implement data parameters, reusables proper test framework, etc. Recording in UFT can be initiated by pressing the F6 key or Record button under the Record tab.
Limitations of recording in UFT:
· All the data are hardcoded.
· Recorded scripts are not stable and difficult to use for the longer run.
· Required high maintenance efforts.
· Redandant duplicate object hierarchy can be created.
Different options for recording in UFT:
· Normal mode/ UI Automation Recording – It’s also known as Contextual, which is the default recording behavior that uses the full features of the UFT object recognization approach. It’s used to record UFT compatible applications.
· Low-level recording mode – If the application is not compatible with UFT, i.e., the entire screen is identified as a single Win Object. In this case, the low-level recording mode can be used to record the steps based on the application co-ordinates.
· Analog Recording – It’s used to record mouse movements and keyboard operation.
· Insight Recording – Insight objects can be inserted on any AUT. Once we press the Record button, Insight Recording appears under the Record menu and recording toolbar.
Different recording options can be chosen by selecting the recording mode from the recording wizard.
Step by step Guide for Recording in UFT:
Recording Scenario: Search the keywords “Automation Testing” on google.
Step1# Open internet explorer and navigate to www.google.com.
Step2# Start the recording by pressing the “F6” button or selecting the menu “Recording-> Record F6”.
Step3# For the first time below “Record and Run Settings” wizard appears to configure the recording settings such as URL, Record, and run on any open browser, etc. Same configurations are also available for mobile or Windows Applications. Here, we will select the “Record and run on any open browser” option and proceed.
Step4# Now the recording wizard appears, and we can manually navigate the scenario in the web browser. UFT will capture the steps which are performed manually and store in the test case.
Step5# After completion of manual navigation, click on the stop button to end the recording. The recorded script will look like below.
Checkpoints in UFT:
Checkpoints in UFT are used to verify the specified properties of objects between actual values and expected values. These verification points are performed at the run time. If the expected values are matched with actual, UFT will generate PASS statue; else, it will be FAIL status. Checkpoints are used based on functional specifications.
Types of Checkpoints in UFT:
There are different types of checkpoints available in UFT. Those are –
· Standard checkpoints in UFT: It validates the expected values of the object, which are captured during recording with the actual values of the object during the execution time.
· Page Checkpoints in UFT: When a standard checkpoint is created for a web page is called a page checkpoint. Page checkpoints in UFT are used to validate the different types of object count, such as links, images, etc. Also, it can be used to check the time taken to load the web page.
· Bitmap Checkpoints in UFT: It is used to check the bitmap of an image or the entire webpage. It performs a pixel to pixel comparison of the test image.
· Image Checkpoints in UFT: It helps us to check properties like the source file of the image. We can not use it to check the bitmap or pixel of the images.
· Text Checkpoints in UFT: It checks the text available in a webpage or application. This text can be available in a small portion or section of the application.
· Accessibility Checkpoints in UFT: It verifies standards as per W3C instructions and guidelines for Web-based technology and information systems.
· Database Checkpoints in UFT: It’s used to verify the database. It creates a query to store database values as expected values during recording time. During the execution, the same query is used to capture current values from the database, which will be compared with expected values.
· Table Checkpoints in UFT: In Table Checkpoint, we can check the contents of the table during the run time. Initially, these checkpoints store the contents of a table as an expected value, which will be verified with the actual table value during execution.
· XML Checkpoints in UFT: It’s used to verify XML files.
Step by Step Guide to Create Checkpoints in UFT:
Now, we will learn how to create standard checkpoints in UFT based on the below example. By following the same guide, we can create different types of checkpoints.
Checkpoint Scenario: Create standard checkpoints in UFT during the recording in the web-browser.
Step1# Open internet explorer and navigate to www.google.com.
Step2# Start the recording by pressing the “F6” button or selecting the menu “Recording-> Record F6”.
Step3# Search the keywords “Automation Testing” on google to record the corresponding automated scripts.
Step4# Now select Standard checkpoint from the menu navigation “Design->Checkpoint->Standard Checkpoint F12” or pressing the “F12” key.
Step5# Select the desired object in the application for which a standard checkpoint needs to be created. Here, we are selecting the web element to verify the text “Test Automation Software.”
Step6# Review the Checkpoint properties and click OK to add the checkpoint step into the test case.
Step7# Checkpoint step is now added in the script. Also, the same is available in the object repository as well. In this scenario, the inner text property of the test object will be validated during the execution.
Step8# Checkpoint verification status can be seen in the UFT execution report.
Dictionary Object in UFT:
The dictionary object in UFT is similar to the array. But the primary difference with the array is that there is a key associated with each element in the dictionary object.
The dictionary object in UFT can be defined by referring to the Scripting.Dictionary class.
Advantages of Dictionary Object in UFT:
· It stores items in an organized way.
· Easy to access any items using the key string.
· It is more flexible to handle with pre-defined methods.
Example of Dictionary Object in UFT:
Create a Dictionary Object:
Dim dict’ Create a variable.
Set dict = CreateObject(“Scripting.Dictionary”)
dict.Add “Company”, “Microfocus” ‘Adding keys and items.
dict.Add “Tool”, “UFT”
dict.Add “Trainer”, “LambdaGeeks”
Checking the Existence of Specific Keys:
If dict.Exists(“Company”) Then
msg = “Key exists”
Else
msg = “key doesn’t exist”
End If
Read Any Item: dict.Item(“Company”)
Get The Count: dict.count
Delete Any Item: dict.Remove(“Company”)
Delete All Item: dict.RemoveAll
Test Execution in UFT:
Steps for Test Execution in UFT are shown below –
Step1# Open the test case in UFT.
Step2# Click on the Run button or press the “F5” key to initiate test execution in UFT.
Step3# Now, we need to select the Result Location. If there are any ALM test sets are available or need to execute from a specific folder, we need to select the first option, i.e., “New run result folder.” For any temporary run to check the script, we need to select the second option. Once the selection is done, please click on the Run button to start the execution.
Step4# After completion of the execution, we can view the default UFT result from the menu navigation “View->Last Run Result.”
Test Debugging options in UFT:
The different debugging options are mentioned below –
Debug Point: By pressing on the “F9” key, the debug point can be added to the selected line of code. It’s required to pause the execution pointer at this particular line. Using the same key, we can also remove the selected breakpoint.
Run From Step: By pressing on the “Ctrl+F5” keys, execution can be started from the selected step.
Step Over (F10): If we want to perform line-by-line debugging, we need to keep on clicking on the “F10” key.
Step Into (F11): If we want to perform line by line execution, including child components as well, we need to keep on pressing the key “F11”.
Clear All Breakpoints: We need to press on keys “Ctrl+Shify+F9”.
Conclusion:
In this “Advance UFT Features” article, we have learned about important advanced UFT concepts such as Recording, Checkpoint, Dictionary Object, Test Execution in UFT, etc. Click here to understand more from the Microfocus support
portal. Also, if you want to prepare for UFT Interview Questions, please click here.