0% found this document useful (0 votes)
16 views30 pages

Untitled Document

My handbook to kattha manufacturing
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views30 pages

Untitled Document

My handbook to kattha manufacturing
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

Unified Functional Testing (UFT), formerly known as QTP (Quick Test Professional), is an automation testing tool developed by Micro

Focus. It is widely used for functional and regression testing of applications

Key Features:

●​ Automates GUI and API tests


●​ Uses VBScript as the scripting language
●​ Supports a wide range of applications (Web, Windows, Java, SAP, etc.)
●​ Integrates with ALM/QC for test management
●​ Provides built-in record and playback features

UFT vs Selenium

Feature UFT Selenium

License Paid (commercial) Free (open-source)

Language VBScript Java, Python, C#, etc.

App Support Web, Desktop, SAP, Java, etc. Web applications only

Ease of Use Easy (record-playback, UI interface) Requires programming knowledge

Integration ALM, Jenkins Jenkins, Maven, TestNG, etc.

Object Repository Built-in (OR) No built-in OR

Support & Updates Micro Focus support Community support

UFT is best for enterprises needing full test lifecycle support for desktop, legacy, and complex apps. Selenium is better for web
automation, especially when cost or language flexibility is a concern.

UFT Architecture

UFT has a modular layered architecture:

1. Test Execution Engine


Reads and runs scripts (written in VBScript)
Handles test flow, action calls, functions, etc.​

2. Object Recognition Engine


Identifies and interacts with objects in the application (buttons, text boxes, etc.)​
Uses Object Repository or Descriptive Programming​

3. Test Interface
GUI with Keyword View and Expert View​
Data Table and Debugging tools

4. Add-in Layer
Plug-ins for specific technologies (Web, Java, SAP, .NET, etc.)
Must be selected at UFT launch

5. Integration Layer
Connects with ALM, Jenkins, test management, CI/CD tools.

UFT Add-ins

Add-in Purpose

Web For automating web browsers (Chrome, Edge, Firefox)

Java For Java desktop applications


SAP For SAP GUI-based applications

.NET For .NET applications (WinForms, WPF)

ActiveX For legacy ActiveX controls

Oracle For Oracle Forms

Flex For Adobe Flex applications

Terminal Emulator For mainframe or terminal-based apps

UFT IDE Overview


The UFT IDE (Integrated Development Environment) is where you create, edit, run, and debug your automated tests.
It includes:
Menus and toolbars for quick access to commands
Menu Bars Located at the top, it provides access to all UFT features:
●​ File: Create, open, save tests
●​ Edit: Cut, copy, paste steps
●​ View: Show/hide panes (Data Table, OR, etc.)
●​ Test: Run, record, insert checkpoints
●​ Resources: Manage actions and repositories
●​ Tools: Options, Object Spy, Recovery Scenarios
●​ Help: UFT documentation and support

Toolbars contain icons for commonly used commands:


●​ Run, Stop, Record
●​ Add steps, Insert checkpoints
●​ Toggle between Keyword View and Expert View

Panes in UFT
●​ Test Pane: Where your test is built (main workspace
●​ Object Repository Pane: Lists all objects used in the test
●​ Data Table Pane: Holds test data (similar to Excel)
●​ Debug Viewer Pane: Helps during test debugging
●​ Output Pane: Shows results of print/log commands
●​ Active Screen Pane: Snapshot of the app for reference

Test Pane: Keyword View vs Expert View.


UFT provides two ways to view and edit your test steps:
Keyword View -
Table-like view (no need for coding)
Each row = one step​
Columns: Item (object), Operation (method), Value, Output, etc.​
Useful for beginners

Item Operation Value

Browser("Gmail") Navigate "https://gmail.com"

Expert View -
●​ Shows the VBScript code behind each step
●​ Gives full control over logic, loops, and error handling.
●​ You can switch between the two views.
Browser("Gmail").Navigate "https://gmail.com".

Editors for writing and organizing test steps


Windows for object repositories, data tables, and results

Action Pane
Organizes the test into Actions
Each action is like a mini-test with its own steps and logic
You can create:
●​ Reusable Actions (called in multiple tests)
●​ Non-reusable Actions (used only once)
Helps structure large tests into logical parts (e.g., Login, Search, Logout)

Data Table
Embedded spreadsheet (like Excel)
Used for data-driven testing
Has two types:
●​ Global Sheet: Shared by all actions
●​ Local Sheet: Specific to one action
You can use parameters like DataTable("Username", dtGlobalSheet)

Record and Playback Module


Purpose: Automate test script creation by recording user interactions.​
Types of Recording Modes:
●​ Normal Recording: Default mode, records standard GUI interactions.
●​ Analog Recording: Captures continuous mouse movements (useful for drawing, signatures, etc.).
●​ Low-Level Recording: Captures precise object coordinates (useful when UFT cannot recognize objects).

Step 1: Open UFT One and Create a New Test


Launch UFT One.
Go to File → New → Test and choose GUI Test.
Click Create to start a new test case.
Playback Once the recording is done:
1.​ Click Run (green arrow)
2.​ Choose Run Settings if needed
3.​ UFT will replay the exact same steps on the application​
After execution, it shows a detailed Test Results Report

1.​ Normal Recording (Standard Mode)

Use Case: Automate login functionality for a web application.

Steps: Click Record (Red button on the toolbar). Open a web


browser and navigate to https://example.com/login.​
Enter Username: testuser.​
Enter Password: password123.​
Click the Login button.​
Stop recording.​
Auto-Generated UFT Code (VBScript) Browser("title:=Login
Page").Page("title:=Login Page").WebEdit("name:=username").Set "testuser"
Browser("title:=Login Page").Page("title:=Login Page").WebEdit("name:=password").SetSecure
"password123"
Browser("title:=Login Page").Page("title:=Login Page").WebButton("name:=Login").Click

✅ Playback: Run the test, and UFT will automatically enter credentials and click login.
2.​ Analog Recording

Use Case: Capture mouse movements & drawing actions (e.g., signing on a digital pad).

Steps:
Select Record → Analog Recording.
Choose Record relative to screen or window.
Perform drawing or signature on the application.
Stop recording.​
Auto-Generated UFT Code

Window("Signature Pad").AnalogRecording "Track1"

✅ Playback: UFT will repeat your exact mouse movements.


9. Low-Level Recording
Use Case: UFT cannot recognize objects, so we capture exact screen coordinates.
Steps:
Select Record → Low-Level Recording.​
Click on application elements that UFT fails to detect.​
Stop recording.​
Auto-Generated UFT Code
Window("Notepad").Click 100, 200
Window("Notepad").Type "Hello UFT!"

✅ Playback: UFT will click on the exact coordinates.


Recording Mode Use Case Example
Normal Standard UI automation Login Page Testing
Analog Mouse movements, signatures Digital Signature Pad
Low-Level Click-based automation (when UFT cannot detect objects) Clicking on Notepad

Additional Steps:

1.​ UFT uses an Object Repository to store the objects it interacts with during recording.
2.​ Active Screen: UFT takes a snapshot of each step so you can insert more steps later.
3.​ You can edit or delete recorded steps as needed.
4.​ Recording is great for beginners, but descriptive programming and modular scripting are better for long-term
automation.

Keyword View:

Item Operation Value

Browser("Gmail") Navigate "https://gmail.com"

WebEdit("Email") Set "[email protected]"

WebButton("Next") Click

Expert View (Code):


Browser("Gmail").Navigate "https://gmail.com"
Browser("Gmail").Page("Gmail").WebEdit("Email").Set "[email protected]"
Browser("Gmail").Page("Gmail").WebButton("Next").Click

2. Object Repository (OR module)


Purpose: Stores properties of objects in the application to identify them during test execution. The Object Repository (OR) is
where UFT stores information about the objects it interacts with in the application under test (AUT). Each object (like a
button, textbox, dropdown) is identified by its properties.
Think of it like a contact list:
●​ Object name: "LoginButton"
●​ Object type: "WebButton"
●​ Properties: name = 'Login', html id = 'btnLogin'

Types of Repositories:
Local Object Repository: Specific to one test, stored within the test script. Automatically created for each action. Stored
inside the test. Simple and automatic
Shared Object Repository: Can be reused across multiple tests (stored as .tsr files). Better for large projects, reusable, easy
to maintain
Object Spy: A tool used to inspect object properties and methods.

Type Description Usage Scenario

Local Object Repository (LOR) Stores objects only for a specific test When objects are unique to a test case

Shared Object Repository (SOR) A common object repository that can be used in When multiple test cases need to interact with
multiple tests the same objects
Step 1: Open the Object Repository
Open UFT One.​
Go to Resources → Object Repository (Shortcut: Ctrl + R).​
Here, you can see all objects stored for your test.

Step 2: Add Objects to the Object Repository

You can add objects manually or by recording. Using Normal Recording (Automatically Captures Objects)

1.​ Click Record (Red button in UFT).


2.​ Perform actions (e.g., click buttons, enter text).
3.​ Stop recording.
4.​ Go to Object Repository (Ctrl + R) → You will see the captured objects.

Using Object Spy (Manually Add Objects). Object Spy allows you to inspect object properties & methods.
Steps to Use Object Spy
1.​ Open UFT and click Tools → Object Spy (Shortcut: Alt + F12).
2.​ Click the "Hand Icon" (Drag & Drop) over the object.
3.​ UFT will display object properties like:
○​ Name (e.g., "LoginButton")
○​ Class (e.g., "WebButton")
○​ Properties (e.g., html id, inner text, xpath)
4.​ Click "Add to Repository" to store it.​

5.​ ✅
Example: Inspecting a Login Button
Browser("title:=Login Page").Page("title:=Login Page").WebButton("name:=Login").Click

Step 3: Local vs. Shared Object Repository


Local Object Repository (LOR)
●​ Objects are stored inside the test itself.
●​ Each test has its own Object Repository.​
Cannot be shared between tests.
Browser("Login Page").Page("Login Page").WebEdit("username").Set "testuser"
How to View Local OR?
Open UFT → Ctrl + R (Object Repository).

Shared Object Repository (SOR)


Objects are stored in a separate file (.tsr) and can be reused across multiple tests.
Helps in modular automation when multiple test cases use the same objects.
How to Create a Shared Object Repository?
Open Object Repository (Ctrl + R).​
Click File → Export Local Objects.​
Save as MyRepository.tsr.​
In a new test, import the .tsr file:​
Resources → Associate Repositories → Add .tsr file.​
Example: Using a Shared Repository
Browser("Login Page").Page("Login Page").WebEdit("username").Set "testuser"
(Here, the object is coming from the Shared Repository)

Step 4: Managing Object Repositories

Task Steps
View Object Repository Ctrl + R

Add Objects Manually Object Spy (Alt + F12) → Click "Add to Repository"

Convert Local to Shared OR File → Export Local Objects (.tsr)

Associate a Shared OR Resources → Associate Repositories → Add .tsr


Summary
Feature Local OR Shared OR

Scope Only for a specific test Can be used across multiple tests

File Type Stored inside test .tsr file

Editing Can be modified within the test Needs Object Repository Manager

Use Case Small tests Large projects with reusable objects

How Objects Are Identified


UFT uses an object’s properties to recognize it: html tag, name, id, class, index, etc.
Uses Object Spy to capture object details
If main properties fail, UFT can use Smart Identification (backup search method)
Regularly clean unused objects

3. Action Mode:
An Action in UFT is like a mini-test or a block of steps that performs a specific task
Purpose: Breaks test scripts into smaller, reusable units for modular scripting.
Types of Actions:
Reusable Action: Can be called multiple times within or across tests.
Non-Reusable Action: Used only within the test where it is created.
External Action: Reusable actions stored in other test scripts.

This makes test scripts:​


Easier to manage​
More reusable​
More structured
You can create, call, and pass data between actions
Use Input/Output parameters to share data

Action Type Description Usage Scenario


Reusable Action Can be called multiple times within the same or different tests. Login functionality used in multiple tests.
Non-Reusable Action Used only within the test where it was created. A one-time action specific to a test case.
External Action A reusable action stored in another test script. Common actions shared across test cases.

Step 1: Creating a New Action

Open UFT One.​


Click File → New → Test → GUI Test.​
Go to Design → Call to New Action.​
Give the action a name (e.g., LoginAction).​
Choose Reusable or Non-Reusable.​
Click OK.

Browser("title:=Example").Page("title:=Login").WebEdit("name:=username").Set "testuser"
Browser("title:=Example").Page("title:=Login").WebEdit("name:=password").SetSecure "password123"
Browser("title:=Example").Page("title:=Login").WebButton("name:=Login").Click

Example - Login Test Using Actions


We will create a test script that:
1.​ Opens a browser.
2.​ Logs into a website (LoginAction).
3.​ Logs out (LogoutAction).

' Open Browser


SystemUtil.Run "chrome.exe", "https://example.com"
' Call Login Action
RunAction "LoginAction", oneIteration

' Call Logout Action


RunAction "LogoutAction", oneIteration

' Close Browser


Browser("title:=Example").Close

Creating a External Action

Sometimes, you want to reuse actions from another test.


Steps: Click Design → Call to Existing Action.​
Select a test script that contains the action.​
Choose Call to Copy (creates a copy) or Call to External (keeps it linked).​
Click OK.​
Now, you can call actions from other tests!

Feature Reusable Action Non-Reusable Action External Action

Reusability Yes, across multiple tests No, only in the same test Yes, from another test

Editing Allowed? Yes Yes No (unless copied)

Use Case Login, Navigation, Common Workflows One-time test steps Shared Test Actions

Passing Parameters Between Actions


Sometimes you need to send data between actions (like passing a username).

UFT supports 2 types of parameters:

Parameter Type Description Used In

Input Sends data to the action E.g., username, password

Output Sends data from the action back E.g., result from a DB query
Steps to Add Parameters:
Open the action​
Go to Edit → Action → Action Properties​
Click on the Parameters tab​
Add Input or Output parameters

Passing an Input Parameter:

Step 1: Define an input parameter


In Action Properties:
1.​ Name: Username
2.​ Type: Input​

Step 2: Use in the action


Browser("App").Page("Login").WebEdit("txtUsername").Set Parameter("Username")

Step 3: Call the action with a value


In the main test:
RunAction "Login", oneIteration, "admin"
UFT will pass "admin" to the Username parameter in the Login action.
4. Checkpoints Module
Purpose: Verifies expected outcomes in an application during test execution by comparing actual and expected values. They
help in automated validation of UI elements, text, databases, images, and XML files.
Types of Checkpoints:
Standard Checkpoint: Verifies object properties (text, value, etc.). Example: Verify Login Button Text

1.​ Record or manually add the step where UFT clicks the login button.
2.​ In UFT, go to Design → Checkpoint → Standard Checkpoint.
3.​ Click the Login button in the application.
4.​ Select the "Text" property and set the expected value as "Login".
5.​ UFT inserts this checkpoint into the script.
6.​ Browser("title:=Login Page").Page("title:=Login Page").WebButton("name:=Login").Check CheckPoint("Login")
7.​ UFT will compare the actual button text with "Login" and report if they match.

Text Checkpoint: Validates static text on the application. (headings, labels, etc.).
Verify Error Message on Login Failure
Try logging in with incorrect credentials.
Go to Design → Checkpoint → Text Checkpoint.
Click on the error message displayed.
Set the expected value as "Invalid username or password".
UFT will insert the checkpoint.
Browser("title:=Login Page").Page("title:=Login Page").Check CheckPoint("Invalid Login Message")
If the error message matches "Invalid username or password", the test passes; otherwise, it fails.

Bitmap Checkpoint: Compares screenshots to detect visual differences.


Adding a Bitmap Checkpoint. Purpose: Compares screenshots to detect visual differences.
Ex. Verify if the Logo Appears Correctly
Navigate to the application’s home page.​
Go to Design → Checkpoint → Bitmap Checkpoint.​
Select the company logo.​
Save the expected bitmap.​
UFT will capture the expected image and compare it at runtime.
Browser("title:=Home Page").Page("title:=Home Page").Image("Logo").Check CheckPoint("Company Logo")
If the logo looks different (e.g., wrong color, distorted, missing), the test fails.

Database Checkpoint: Validates database values.
Adding a Database Checkpoint. Purpose: Verifies database values by running SQL queries.
Example: Verify User Record in Database.
Go to Design → Checkpoint → Database Checkpoint.​
Enter the database connection details (server, username, password).​
Write a SQL query like: SELECT username FROM users WHERE username = 'testuser';
UFT will verify if "testuser" exists in the database.
dbCheckpoint("User Exists Check")
If "testuser" is present, the test passes; otherwise, it fails.

XML Checkpoint: Verifies XML content.
Adding an XML Checkpoint. Purpose: Validates XML structure and values in API responses or configurations.
Example: Verify API Response XML.
Open an API response in XML format.​
Go to Design → Checkpoint → XML Checkpoint.​
Select the XML file or URL.​
UFT will store the expected XML and compare it at runtime.
XMLCheckpoint("API Response Check")
If the XML response matches the expected structure, the test passes.

Checkpoint Type Description Use Case

Standard Checkpoint Verifies object properties (text, value, visibility, etc.) Checking button label or text in a field

Text Checkpoint Validates static text displayed on the application Checking error messages or page headings
Welcome John" appears within a certain
Text Area Similar to Text, but checks text in a specific area screen zone

Bitmap Checkpoint Compares screenshots (pixel by pixel) Verifying UI layout, images, and logos

Database Checkpoint Verifies database values by querying Checking if a user record is created in the
tables database

XML Checkpoint Validates XML content (structure & values) Checking API response XML files

Best Practices
Use Checkpoints to validate only critical features (avoid overuse)​
Use Descriptive Programming for flexible checking​
For dynamic content, use regular expressions or custom checks​
Use Database Checkpoints to ensure backend data is correct

5. Parameterization Module
Purpose: Enables running test cases with multiple data sets (data-driven testing). Parameterization allows running a single
test script with multiple sets of data, eliminating the need for hardcoded values. This is crucial for data-driven testing where
the test needs to be executed multiple times with different inputs.​
Methods of Parameterization:

Method Description Use Case

Data Table Uses built-in Excel-like Data Table for parameterization Testing login with multiple usernames & passwords

Environment Variables Uses global/system variables to store values Storing URLs, credentials, or global settings

Random Number Generation Generates dynamic numbers during test execution Creating unique order IDs, random usernames

Database Connectivity Fetches test data from SQL, Oracle, etc. Validating data-driven workflows

Data Table (Excel-based input)


Example: Test Login with Multiple Users. Suppose we have multiple usernames and passwords in UFT’s Data Table, and we
want UFT to test all combinations.
Open UFT → Go to Data Table (bottom panel).​
Enter test data in columns like:
Username Password
testuser1 pass123
testuser2 pass456
testuser3 pass789
Modify the script to read values dynamically.
' Retrieve row count from the data table
RowCount = DataTable.GetRowCount

' Loop through each row and execute test


For i = 1 To RowCount
DataTable.SetCurrentRow(i)

' Fetch username & password from Data Table


userName = DataTable.Value("Username", dtGlobalSheet)
password = DataTable.Value("Password", dtGlobalSheet)
' Perform login action
Browser("Login Page").Page("Login Page").WebEdit("username").Set userName
Browser("Login Page").Page("Login Page").WebEdit("password").Set password
Browser("Login Page").Page("Login Page").WebButton("Login").Click
Next
UFT will iterate over each row, fetch data, enter it into the login fields, and click Login.
Environment Variables
Store and Use Application URL. Instead of hardcoding values like URLs or credentials, store them in environment variables.

Steps to Use Environment Variables.


Go to File → Settings → Environment.​
Add a new variable:​
Name: AppURL​
Value: http://example.com/login​
Access it in the script.
' Retrieve value from environment variables
URL = Environment.Value("AppURL")
' Launch the browser with stored URL
SystemUtil.Run "iexplore.exe", URL. “UFT will fetch the URL from the environment variable and launch the browser with it.

Random Number Generation. Generate Unique Order IDs


When testing order placement, you may need to generate a random order ID every time.
' Generate a random number between 1000 and 9999
randomOrderID = Int(1000 + Rnd() * 9000)
' Use the random order ID in a test
Browser("Orders").Page("Orders").WebEdit("OrderID").Set randomOrderID
UFT generates a unique 4-digit order ID every time the script runs.

Database Connectivity (Fetching data from DBs like SQL, Oracle, etc.)
Fetch User Credentials from SQL Database. Instead of using Excel, you can directly fetch test data from a database.
Steps to Use Database Parameterization
Connect UFT to the database.​
Run a SQL query to fetch test data.​
Store the result in a variable and use it in the script. UFT will fetch active users from the database, log them in one by one,
and test the login process.

' Create a database connection


Set conn = CreateObject("ADODB.Connection")
conn.Open "DSN=MyDB; UID=user; PWD=pass" ' Replace with actual DB credentials

' Execute SQL query


Set rs = conn.Execute("SELECT Username, Password FROM Users WHERE Active = 1")

' Loop through fetched data


Do While Not rs.EOF
userName = rs.Fields("Username").Value
password = rs.Fields("Password").Value

' Perform login action


Browser("Login Page").Page("Login Page").WebEdit("username").Set userName
Browser("Login Page").Page("Login Page").WebEdit("password").Set password
Browser("Login Page").Page("Login Page").WebButton("Login").Click

rs.MoveNext
Loop

' Close connection


rs.Close
conn.Close
Set rs = Nothing
Set conn = Nothing

6. Synchronization Module

Purpose: Ensures the test execution waits for the application to be ready before performing actions. When automating tests,
sometimes UFT executes steps faster than the application responds, causing test failures. Synchronization ensures that
UFT waits until the application is ready before performing actions.​
Methods of Synchronization:

1.​ Wait Statement: Wait (seconds) – Pauses execution for a fixed time.
Wait(5) ' Pauses the script for 5 seconds
Drawback: Not efficient—wastes time if the application loads faster.

2.​ Sync Method: Waits for the application to load (used for web apps). UFT waits until the browser has fully loaded
before clicking the Login button. Works only for web-based applications.
' Open browser
SystemUtil.Run "iexplore.exe", "http://example.com"
' Wait until the page loads completely
Browser("Example").Sync
' Now perform an action
Browser("Example").Page("Example Page").WebButton("Login").Click

3.​ Exist Method: object.Exist(timeout) – Waits until the object appears.


Wait Until a Login Button Appears (Timeout = 10 sec)
UFT checks every second (up to 10 sec) if the Login button exists.
If found, it clicks. If not found after 10 sec, it reports a test failure.
Best For: Applications where elements load at different speeds.
Set btnLogin = Browser("Example").Page("Example Page").WebButton("Login")
' Wait for the login button to appear (max 10 seconds)
If btnLogin.Exist(10) Then
btnLogin.Click
Else
Reporter.ReportEvent micFail, "Login Button", "Button not found within timeout"
End If

4.​ Implicit/Smart Wait: Configurable wait time for object detection.


UFT provides a global timeout setting where it waits for objects before throwing an error.
Go to UFT → File → Settings → Run.​
Set "Object Synchronization Timeout" (default is 20 sec).​
This ensures UFT waits for objects dynamically.
Code (No need to write explicitly)
' UFT automatically waits for objects up to the timeout set in settings
Browser("Example").Page("Example Page").WebButton("Login").Click
What Happens? If the Login button appears within the timeout, UFT proceeds.​
If not, UFT throws an error after the timeout.

Method Description Best Use Case

Wait Statement Pauses execution for a fixed time When an application always takes a specific time to load

Sync Method Waits until the browser is completely loaded Used for web applications

Exist Method Waits for an object to appear before interacting with it When elements take variable time to load

Implicit (Smart) Wait Configures default wait time for object recognition When objects load at different speeds

Scenario Best Method

Web app page loading Sync Method

Waiting for a specific element Exist Method

Fixed time delays (last resort) Wait Statement

Overall object wait time Implicit Wait (Global Timeout)

Recovery Scenarios
A Recovery Scenario is a way to tell UFT what to do when unexpected events or errors occur during test execution. Think of it
as a safety net to keep your test from failing unexpectedly like:
●​ Application crashes
●​ Unexpected pop ups
●​ Missing windows
●​ Object not found errors​
A Recovery Scenario is made up of 4 parts:
Step Description
Trigger Event What event/error should UFT detect? (e.g., popup, crash)
Recovery Operation What should UFT do to recover? (e.g., close popup, restart app)
Post-Recovery Test Run Option What to do after recovery? (repeat, next step, stop)
Name & Save Save and reuse across tests

Step-by-Step: Creating a Recovery Scenario

1. Open the Recovery Scenario Manager


In UFT: Resources → Recovery Scenario Manager

2. Add New Scenario

1.​ Trigger Event – Choose:


○​ Popup Window (most common)
○​ Object State​
Test Run Error
○​ Application Crash
2.​ Recovery Operation – Choose:
○​ Click button
○​ Close window
○​ Call a function
○​ Send keystrokes
3.​ Post-Recovery Options:
○​ Repeat current step
○​ Proceed to next step
○​ Stop test
4.​ Save the Recovery Scenario

Example: Handling a Login Popup

Let’s say a popup appears if login fails.

Step Value
Trigger Popup Window: "Login Error"
Operation Click OK button
Post-Recovery Continue with next step

Enabling/Disabling Recovery Scenarios


Go to: File → Settings → Recovery
You can add or remove recovery scenarios here
Enable/disable them for a particular test

Calling Recovery Manually in Code


You can manually trigger a recovery scenario like this:
Recovery.Activate "MyPopupRecovery"

Tips and Best Practices

●​ Use Recovery Scenarios sparingly — prefer handling errors in code if possible


●​ Use for unexpected situations only (like system popups)
●​ Combine with On Error Resume Next for better control
Summary
Component Description
Trigger Event What triggers the recovery (popup, crash, etc.)
Recovery Operation What UFT should do to fix the issue
Post-Recovery Whether to continue, stop, or repeat
Best Used For Pop Ups, alerts, crashes, unexpected behaviors

7. VBScript (Scripting) Module - xStr


Purpose: UFT uses VBScript as its scripting language to automate complex tasks. It helps in decision-making, looping, file
handling, and object manipulation.​
Key VBScript Concepts:
Variables & Data Types (Dim, Set, Array)
In VBScript, variables are declared using Dim or Set (for objects).
Dim name, age
name = "Nawfan"
age = 24
MsgBox "My name is " & name & " and I am " & age & " years old."
Displays a message box: "My name is Nawfan and I am 24 years old."

Conditional Statements (If-Else, Select Case)

If-Else Condition
Dim score
score = 75
If score >= 50 Then
MsgBox "Pass"
Else
MsgBox "Fail"
End If
If score is 50 or above, it displays "Pass"; otherwise, "Fail"

Select Case Condition.


Dim grade
grade = "B"
Select Case grade
Case "A"
MsgBox "Excellent"
Case "B"
MsgBox "Good"
Case "C"
MsgBox "Average"
Case Else
MsgBox "Fail"
End Select

If grade is "B", it displays "Good".

Loops (For, While, Do-While)


For Loop
Dim i
For i = 1 To 5
MsgBox "Iteration: " & i
Next
Displays message boxes with "Iteration: 1" to "Iteration: 5".

While Loop
Dim count
count = 1

While count <= 5


MsgBox "Count: " & count
count = count + 1
Wend
Runs until count reaches 5, displaying "Count: 1" to "Count: 5".

Do-While Loop
Dim num
num = 1

Do While num <= 3


MsgBox "Number: " & num
num = num + 1
Loop
Runs while num ≤ 3, displaying "Number: 1" to "Number: 3".

Functions & Procedures
Functions in VBScript allow reusability.
Function with Return Value.
Function AddNumbers(a, b)
AddNumbers = a + b
End Function

Dim result
result = AddNumbers(10, 20)
MsgBox "Sum: " & result ‘Displays "Sum: 30".

File Handling (CreateObject("Scripting.FileSystemObject"))


Used to read and write files dynamically.
Writing to a File - Creates C:\testfile.txt with "Hello, this is UFT automation!".
Dim fso, file
Set fso = CreateObject("Scripting.FileSystemObject")
Set file = fso.CreateTextFile("C:\testfile.txt", True)
file.WriteLine "Hello, this is UFT automation!"
file.Close
MsgBox "File created successfully!"

Reading from a File - Reads and displays "Hello, this is UFT automation!".
Dim fso, file, content
Set fso = CreateObject("Scripting.FileSystemObject")
Set file = fso.OpenTextFile("C:\testfile.txt", 1)
content = file.ReadAll
file.Close
MsgBox "File Content: " & content

Regular Expressions (RegExp) for dynamic object handling. Used for pattern matching.
Validate Email Using Regex. If email = "[email protected]", it displays "Valid Email".
Dim regex, email
Set regex = New RegExp
regex.Pattern = "^\w+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$"
regex.IgnoreCase = True
regex.Global = True

email = "[email protected]"

If regex.Test(email) Then
MsgBox "Valid Email"
Else
MsgBox "Invalid Email"
End If
Arrays and Dictionaries in UFT (VBScript)

1. Arrays - Arrays are used to store multiple values in one variable.


How to Declare an Array:
Dim fruits(2) ' fixed-size array with 3 elements: 0, 1, 2
fruits(0) = "Apple"
fruits(1) = "Banana"
fruits(2) = "Mango"

2. Looping Through an Array:


For i = 0 To UBound(fruits)
MsgBox fruits(i)
Next

3. Dynamic Arrays: Use ReDim to resize an array at runtime.


ReDim fruits(1)
fruits(0) = "Orange"
fruits(1) = "Grapes"
To preserve existing values while resizing:
ReDim Preserve fruits(2)
fruits(2) = "Pineapple"

2. Dictionaries in VBScript - A Dictionary is like a key-value pair store (similar to a Map or Hashtable).

Create a Dictionary:
Set dict = CreateObject("Scripting.Dictionary")
dict.Add "Name", "John"
dict.Add "Age", 30

Access or Modify:
MsgBox dict.Item("Name") ' Outputs: John
dict.Item("Age") = 31 ' Update value

Remove Items:
dict.Remove "Age"
Loop Through Dictionary:
For Each key In dict.Keys
MsgBox key & ": " & dict.Item(key)
Next

Working with Files and Folders in UFT (VBScript) to read/write files and manage folders.

Create the FileSystemObject:


Set fso = CreateObject("Scripting.FileSystemObject")

Working with Text Files


1. Create or Write to a File:
Set file = fso.CreateTextFile("C:\Test\log.txt", True)
file.WriteLine "Test started"
file.WriteLine "Login successful"
file.Close

2. Read from a File:


Set file = fso.OpenTextFile("C:\Test\log.txt", 1)
Do Until file.AtEndOfStream
line = file.ReadLine
MsgBox line
Loop
file.Close

1 = ForReading, 2 = ForWriting, 8 = ForAppending


Working with Folders
1. Create Folder:
If Not fso.FolderExists("C:\Test\Results") Then
fso.CreateFolder "C:\Test\Results"
End If

2. Delete Folder:
fso.DeleteFolder "C:\Test\Results", True
3. List Files in a Folder:
Set folder = fso.GetFolder("C:\Test")
For Each file In folder.Files
MsgBox file.Name
Next

Arrays:
●​ Store multiple values
●​ Use UBound to loop through
●​ Use ReDim Preserve to resize​

Dictionaries:
●​ Key-value pairs
●​ Great for structured data (e.g., login info)​

File/Folder Operations:
●​ Use FileSystemObject
●​ Create, read, write files
●​ Create/delete folders
●​ Loop through files and folders

8. Descriptive Programming Module

Purpose: Allows object identification without using the Object Repository. This makes scripts more dynamic and flexible.
(DP) lets you bypass the Object Repository and identify objects directly in your script using their properties.

This is useful when:


●​ You don’t want to use Object Repository
●​ Objects are dynamic or not stored
●​ You're creating data-driven or reusable scripts

Types of Descriptive Programming:


Static: Defining object properties directly in the script using a property-value pair
Browser("title:=Google").Page("title:=Google").WebEdit("name:=q").Set "UFT Testing"
Multiple properties:
Browser("name:=Google", "version:=.*").Page("title:=.*Google.*").WebEdit("type:=text", "name:=q").Set "ChatGPT"
Dynamic: Here, we create an object with properties and then use it in the script. ​
Using a dictionary of object properties. ​
Set obj = Description.Create ​ ​
obj("micclass").Value = "WebButton" ​ ​ ​ ​ ​ ​ ​ ​ ​
obj("html tag").Value = "INPUT"
Benefits:
1.​ Cleaner
2.​ Easier to add/remove properties​
Great for loops or reusable components​

Identifying a Web Button Dynamically. - Finds Google Search button dynamically and clicks it.
Dim objDesc
Set objDesc = Description.Create
' Define object properties dynamically
objDesc("micclass").Value = "WebButton"
objDesc("html tag").Value = "INPUT"
objDesc("name").Value = "Google Search"
' Click the button dynamically​
Browser("title:=Google").Page("title:=Google").WebButton(objDesc).Click
Advanced Example
Get All Links on a Page Dynamically. Retrieves all links on the Google page and displays their names.
Dim objDesc, links, i
' Define description for all links
Set objDesc = Description.Create
objDesc("micclass").Value = "Link"
' Get all link objects on the page
Set links = Browser("title:=Google").Page("title:=Google").ChildObjects(objDesc)
' Print the number of links
MsgBox "Total links: " & links.Count
' Print all link names
For i = 0 To links.Count - 1
MsgBox links(i).GetROProperty("text")
Next

When to Use Descriptive Programming?


Scenario Why Use DP?

No Object Repository No need to add objects manually

Dynamic Objects Handles objects with changing properties

Faster Execution Reduces reliance on Object Repository

Creating and Using Object Hierarchies


UFT always uses a parent → child structure:
1.​ Browser → Page → WebEdit
2.​ Window → Dialog → WinButton​
When using DP, you must define the full hierarchy in code.

Button inside a browser:


Browser("name:=FlightApp").Page("title:=Login").WebButton("name:=Login").Click
Using Dynamic Description in Hierarchy
Set btnDesc = Description.Create
btnDesc("micclass").Value = "WebButton"
btnDesc("name").Value = "Submit"
Browser("name:=FlightApp").Page("title:=Login").WebButton(btnDesc).Click
Example: Loop through all Edit Fields
Set editDesc = Description.Create
editDesc("micclass").Value = "WebEdit"
Set edits = Browser("B").Page("P").ChildObjects(editDesc)
For i = 0 To edits.Count - 1
edits(i).Set "Test" & i
Next

Combine DP with Functions


Function EnterText(objName, text)
Set desc = Description.Create
desc("micclass").Value = "WebEdit"
desc("name").Value = objName
Browser("name:=App").Page("title:=Login").WebEdit(desc).Set text
End Function

EnterText "username", "admin"


EnterText "password", "1234"

9. Test Batch Runner Module

Purpose: Allows execution of multiple test scripts in a batch.​


Features:
Automates multiple test executions without manual intervention.
Generates consolidated reports for batch execution.
How to Use Test Batch Runner in UFT?
Open Test Batch Runner (Go to Start > UFT One > Tools > Test Batch Runner).​
Click "Add" to add multiple test scripts.​
Click "Run" to execute all tests in sequence.
Runs Test1, Test2, and Test3 automatically in sequence.

Dim qtApp, qtBatchRun


Set qtApp = CreateObject("QuickTest.Application")

' Launch UFT if not already open


If Not qtApp.Launched Then
qtApp.Launch
End If
qtApp.Visible = True

' Load the Test Batch Runner


Set qtBatchRun = qtApp.TestBatchRunner
qtBatchRun.AddTest "C:\UFT_Tests\Test1"
qtBatchRun.AddTest "C:\UFT_Tests\Test2"
qtBatchRun.AddTest "C:\UFT_Tests\Test3"

' Run all tests in batch mode


qtBatchRun.Run

' Close the application


qtApp.Quit
Set qtApp = Nothing
Set qtBatchRun = Nothing

10. Debugging & Reporting Module


Purpose: Helps in error handling and generating test reports.
Debugging helps to find errors in scripts.
Reporting generates logs & test reports for analysis.​
Debugging Tools:
Breakpoints – Pause test execution for debugging.
Step Into/Over/Out – Helps analyze step-by-step execution.​
Output Debug Window (Print statement) – Displays messages during runtime.

1. Breakpoints
Add breakpoints to pause execution at a specific step.​
Use F9 to toggle breakpoints.​

2. Step Into / Step Over / Step Out


Step Into (F11) – Executes code line by line.​
Step Over (F10) – Skips functions but executes them.​
Step Out (Shift+F11) – Exits the current function.​

3. Output Debug Window


Use Print statements to display messages.
Print "Test execution started"

4. Watch Variables
Add variables to the "Watch" window to track their values.

Reporting Tools:
Reporter Utility: Generates custom test reports.​
Reporter.ReportEvent micPass, "Login Test", "Login was successful"
Generates pass/fail logs in the test results.
Reporter.ReportEvent micPass, "Login Test", "Login was successful"
Reporter.ReportEvent micFail, "Login Test", "Login failed - Invalid credentials"
11. HP ALM (Application Lifecycle Management): Integrates UFT for test management and defect
tracking.
HP ALM (formerly Quality Center) is used for:
1.​ Test Management – Organizing test cases, test plans, and execution history.
2.​ Defect Tracking – Logging and tracking bugs found during test execution.
3.​ Test Execution – Running UFT scripts directly from ALM.
4.​ Report Generation – Generating test reports and analyzing test coverage.
5.​ Steps to Integrate UFT with HP ALM
6.​ Before starting, ensure:
7.​ HP ALM is installed & running.
8.​ UFT has the ALM Add-in installed.

Step 1: Connect UFT to HP ALM


Open UFT​
Go to Tools > ALM Connection​
Enter ALM Server URL (Example: http://yourALMserver/qcbin/)​
Enter Username, Password, Domain, and Project​
Click "Connect"

Step 2: Save and Upload UFT Test to ALM


Create a test script in UFT.​
Go to File > Save As > ALM Test Plan.​
Choose a folder in ALM to store the test.​
Click "OK" to upload the test to ALM.

Step 3: Execute UFT Tests from HP ALM


Open HP ALM and navigate to Test Lab.​
Select the UFT test case stored in ALM.​
Click "Run" to execute the test.​
UFT will launch automatically and execute the test.​
Results will be stored in ALM.

You can also launch UFT tests stored in ALM using a VBScript.
The script connects UFT to ALM, retrieves the test, and runs it automatically.

Dim qtApp, qtTest


Set qtApp = CreateObject("QuickTest.Application")

' Connect to ALM


qtApp.Launch
qtApp.Visible = True
qtApp.Open "[ALM\Subject\UFT_Tests\LoginTest]", False

' Run the test


Set qtTest = qtApp.Test
qtTest.Run
qtTest.Close

' Disconnect and cleanup


qtApp.Quit
Set qtTest = Nothing
Set qtApp = Nothing

If the UFT test fails, you can log a defect in HP ALM. This script automatically logs a defect in ALM when a test fails.

Dim QCConnection, Defect


Set QCConnection = CreateObject("TDApiOle80.TDConnection")
' Connect to ALM
QCConnection.InitConnectionEx "http://yourALMserver/qcbin/"
QCConnection.Login "username", "password"
QCConnection.Connect "Domain", "Project"
' Create a new defect
Set Defect = QCConnection.BugFactory.AddItem(Nothing)
Defect.Field("BG_SUMMARY") = "Login Page Not Loading"
Defect.Field("BG_DESCRIPTION") = "Application is not responding"
Defect.Field("BG_STATUS") = "New"
Defect.Post
' Close connection
QCConnection.Disconnect
Set QCConnection = Nothing
Set Defect = Nothing

After running tests in ALM, you can:


View test results in the Test Lab.
Generate reports on test execution, defects, and progress.
Analyze test coverage to ensure all scenarios are tested.

Full Example: Debugging & Reporting in UFT


Dim username, password
username = "admin"
password = "12345"

' Start debugging


Print "Starting Login Test"

If username = "admin" And password = "12345" Then


Reporter.ReportEvent micPass, "Login Test", "Login was successful"
Else
Reporter.ReportEvent micFail, "Login Test", "Login failed"
End If

Print "Login Test Completed”

12. A Regular Expression is a special sequence of characters that helps match patterns in text — especially useful
when object properties or values change dynamically (like session IDs, timestamps, or control names).
UFT allows using RegEx in:
●​ Object Repository
●​ Descriptive Programming​
Checkpoints and output values
1: Match a dynamic title: Browser("title:=Flight Reservation.*").Page("title:=Flight Reservation.*").Sync

2: Match a changing button name: If a button’s label changes like "Submit Now", "Submit Form", etc., use:
WebButton("name:=Submit.*").Click

Symbol Meaning Example

.* Any number of any characters title:=.*Login.*

^ Start of string ^Flight → starts with "Flight"

$ End of string Flight$ → ends with "Flight"

\d Any digit (0–9) \d\d\d → matches 3 digits

\w Any word character (A–Z, a–z, 0–9, _) \w+ → one or more word characters

[] Character set [Mm]onday → Monday or monday

` ` OR condition

You can also use RegEx inside a description object.


Set desc = Description.Create
desc("micclass").Value = "WebEdit"
desc("name").Value = "user.*" ' matches user123, username, etc.
Browser("name:=.*App.*").Page("title:=.*Login.*").WebEdit(desc).Set "admin"

UFT checkpoints can be configured to verify dynamic values using RegEx.


If a page header is: Welcome John, your session ID is 12345
You can use a text checkpoint with expected value: Welcome .*, your session ID is \d+
Best Practices
Always test your regex pattern using sample values
Use .* carefully (it can match too much)
Prefer more specific patterns when possible​
For numeric IDs: use \d+, not .*

Topic Example

Use RegEx in Object Props title:=Flight.*


Use in Descriptive Programming name:=Submit.*
Use for Dynamic Matching \d+, .*, `Login
Use in Checkpoints Match changing values in outputs

13. API Testing Module

Purpose: Allows testing of REST/SOAP web services.​


Features:

●​ Supports JSON and XML requests.


●​ Validates API responses using checkpoints.
●​ Integration with external tools (Postman, SOAP UI).

14. CI/CD Integration Module

Purpose: Enables UFT to work with DevOps tools.​


Supported Tools:

●​ Jenkins
●​ Git
●​ Azure DevOps
●​ ALM/QC Integration

In UFT (Unified Functional Testing), you can capture error numbers using the Err object in VBScript.

15. Error Handling - The Err object provides details about runtime errors, including:

1.​ Err.Number → Returns the error number. captures the error and reports it in UFT’s result window.
2.​ Err.Description → Returns the error message.
3.​ Err.Source → Returns the source of the error.

On Error Resume Next ' Enable error handling


Dim a, b, result
a = 10
b=0
result = a / b ' This will cause a division by zero error
If Err.Number <> 0 Then
Reporter.ReportEvent micFail, "Error Encountered", "Error Number: " & Err.Number & " - " & Err.Description
Err.Clear ' Clear the error
End If

Example 2: Handling File Not Found Error


On Error Resume Next
Dim objFSO, objFile
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("C:\InvalidPath\test.txt", 1) ' Invalid path
If Err.Number <> 0 Then
Reporter.ReportEvent micFail, "File Error", "Error Number: " & Err.Number & " - " & Err.Description
Err.Clear
End If
Set objFSO = Nothing

The script attempts to open a non-existent file. Err.Number captures the "File Not Found" error and reports it.

Example 3: Handling Object Identification Error.


On Error Resume Next
Dim objBtn
Set objBtn = Browser("title:=Google").Page("title:=Google").WebButton("name:=Search123") ' Incorrect object
If Err.Number <> 0 Then
Reporter.ReportEvent micFail, "Object Not Found", "Error Number: " & Err.Number & " - " & Err.Description
Err.Clear
End If

16. Object Identification Techniques in UFT


UFT uses different techniques to identify and interact with objects in the application.
Understanding these techniques helps you build more stable and reliable test scripts.

1. Ordinal Identifiers - Ordinal Identifiers help UFT differentiate between similar objects when their properties alone are
not enough. Browser("creationtime:=1").Page("title:=Google").WebEdit("index:=0").Set "ChatGPT"

Type Description

Index Order of appearance (0-based index)

Location Position on screen (top to bottom, left to right)

CreationTime For browser objects, based on the time the browser was opened

2. Smart Identification - Used when UFT can’t find an object using normal properties.
It uses a backup strategy:
●​ Base filter properties (essential) and Optional filter properties (additional)
When used:
●​ Object is not found or multiple matches
●​ If enabled in Object Repository > Object Identification settings

Example (behind the scenes):


UFT might try:
●​ html tag=button, name=Submit
●​ If fails, uses optional like class, html id
●​ Smart Identification makes tests more robust, but avoid overreliance. It’s better to use unique properties.

3. Virtual Objects
Some UI elements (like custom buttons or shapes) are not recognized as standard objects by UFT.Virtual Objects allow you to
map areas on the screen and treat them like standard objects (like buttons). Use When:
●​ UFT doesn’t recognize an object
●​ It's not in the Object Repository

Steps:
1.​ Go to Tools → Virtual Object → New Virtual Object
2.​ Select the screen area (click and drag)
3.​ Assign it a type (Button, List, etc.)
4.​ Save it

Later, use it like: Window("MyApp").VirtualButton("CustomLogin").Click

Limitations:
●​ Screen resolution and layout must not change
●​ Doesn’t work well with dynamic UIs

4. ChildObjects and Dynamic Descriptions:


ChildObjects let you find multiple matching elements under a parent object.
This is helpful when:
●​ Working with tables, lists, or dynamic UIs
●​ You want to interact with multiple similar elements
Example: Find all links on a page
Set desc = Description.Create
desc("micclass").Value = "Link"
Set links = Browser("G").Page("P").ChildObjects(desc)
For i = 0 To links.Count - 1
MsgBox links(i).GetROProperty("innertext")
Next

You can also use dynamic descriptions to avoid using the Object Repository.

Example: Browser("name:=Google").Page("title:=.*Google.*").WebEdit("name:=q").Set "UFT"

Technique Purpose

Ordinal Identifier Differentiates similar objects using index, location, etc.

Smart Identification Backup object recognition mechanism when main fails

Virtual Objects Treat unrecognized screen areas as standard objects

ChildObjects Loop through multiple similar objects (e.g., all links)

Dynamic Descriptions Identify objects in code using property-value pairs

17. Working with External Files in UFT


UFT allows interaction with external files to read test data, write logs, and verify content.
This makes your tests data-driven and more flexible.

1. Working with Excel Files using Excel.Application

Read data from Excel


Set xlApp = CreateObject("Excel.Application")
Set xlBook = xlApp.Workbooks.Open("C:\TestData\data.xlsx")
Set xlSheet = xlBook.Sheets("Sheet1")
value = xlSheet.Cells(2, 1).Value ' Read cell A2
MsgBox value
xlBook.Close False
xlApp.Quit
Set xlSheet = Nothing
Set xlBook = Nothing
Set xlApp = Nothing

Write data to Excel


Set xlApp = CreateObject("Excel.Application")
Set xlBook = xlApp.Workbooks.Open("C:\TestData\data.xlsx")
Set xlSheet = xlBook.Sheets("Sheet1")
xlSheet.Cells(2, 2).Value = "Passed" ' Write to cell B2
xlBook.Save
xlBook.Close
xlApp.Quit

Tips:
1.​ You can make Excel visible with xlApp.Visible = True
2.​ Always release objects to avoid memory issues​

Reading and Writing Text Files


Use the FileSystemObject (FSO) to handle .txt or .log files.

Read a text file line by line


Set fso = CreateObject("Scripting.FileSystemObject")
Set file = fso.OpenTextFile("C:\TestData\info.txt", 1)
Do Until file.AtEndOfStream
line = file.ReadLine
MsgBox line
Loop
file.Close

Write to a text file


Set fso = CreateObject("Scripting.FileSystemObject")
Set file = fso.CreateTextFile("C:\TestData\log.txt", True)
file.WriteLine "Test started at: " & Now
file.WriteLine "Login successful"
file.Close

Modes:
●​ 1 → Read
●​ 2 → Write​
8 → Append

3. XML File Handling


XML is common for configs, test data, or API responses.
Use the MSXML DOM Parser to read/write XML.

Read XML nodes:


<Users>
<User>
<Name>John</Name>
<Role>Admin</Role>
</User>
</Users>

Set xml = CreateObject("Microsoft.XMLDOM")


xml.Load("C:\TestData\users.xml")
Set user = xml.SelectSingleNode("//User/Name")
MsgBox user.Text ' Output: John

Write/Update XML node


Set xml = CreateObject("Microsoft.XMLDOM")
xml.Load("C:\TestData\users.xml")
Set node = xml.SelectSingleNode("//User/Role")
node.Text = "Tester"
xml.Save "C:\TestData\users.xml"

Task Method

Read/Write Excel Excel.Application object

Read/Write Text Scripting.FileSystemObject (FSO)

Read/Update XML Microsoft.XMLDOM parser

To take a screenshot on error in UFT, save it in a custom folder, and use a timestamp as the file name, follow this
structured approach:

1. Create Folder for Screenshots (if not exists)


Dim fso, folderPath
Set fso = CreateObject("Scripting.FileSystemObject")

folderPath = "C:\UFT_Screenshots"

If Not fso.FolderExists(folderPath) Then


fso.CreateFolder folderPath
End If
2. Create Timestamp Function
Function GetTimeStamp()
Dim dt
dt = Now
GetTimeStamp = Replace(Replace(Replace(CStr(dt), ":", "-"), "/", "-"), " ", "_")
End Function

3. Capture Screenshot Function


Function CaptureScreenshotOnError()
Dim timestamp, fileName
timestamp = GetTimeStamp()
fileName = "C:\UFT_Screenshots\Error_" & timestamp & ".png"
Desktop.CaptureBitmap fileName, True
End Function

4. Use Inside Error Handling Block


On Error Resume Next
' Example: action that might fail
Browser("Google").Page("Google").WebEdit("q").Set "UFT"
If Err.Number <> 0 Then
CaptureScreenshotOnError()
Reporter.ReportEvent micFail, "Error Occurred", "Screenshot saved"
Err.Clear
End If
On Error GoTo 0

In UFT (Unified Functional Testing), both functions and subroutines are reusable code blocks used to modularize test scripts.
However, they differ mainly in how they handle return values.

18. Functions

●​ A function performs a task and returns a value.


●​ It is defined using the Function keyword.
●​ You can pass arguments to a function.
●​ Use a FunctionName = value syntax to return a value.

Function Add(a, b)
Add = a + b
End Function
result = Add(5, 3) ' result will be 8

19. Subroutines (Subs)


A subroutine performs a task but does not return a value directly.
It is defined using the Sub keyword.
Used mainly for performing actions like clicking buttons, navigating pages, etc.
If you need output, you’d modify a passed variable (by reference).
Sub ShowMessage(msg)
MsgBox msg
End Sub
ShowMessage "Hello, UFT!"

Feature Function Subroutine (Sub)

Return Value Yes No

Syntax Function...End Function Sub...End Sub

Usage Calculations, logic Actions, navigation

Call Statement result = Func() Call SubName() (optional)

20. In UFT (Unified Functional Testing), GetROProperty, GetTOProperty, and SetTOProperty are methods used to
work with object properties. Here's a clear breakdown of what each does:
1. GetROProperty (Get Runtime Object Property)

●​ Retrieves the actual property value of an object at runtime, i.e., what UFT sees when the test runs.
●​ Useful when the UI changes dynamically.
●​ value = Browser("Browser").Page("Page").WebEdit("Username").GetROProperty("value")
●​ Example use case: To check the current text entered in a textbox during test execution.

2. GetTOProperty (Get Test Object Property)

●​ Returns the property value stored in the object repository or in the Descriptive Programming (DP) at the time the
script was written.
●​ It doesn't consider runtime changes.
●​ value = Browser("Browser").Page("Page").WebEdit("Username").GetTOProperty("name")
●​ To verify what UFT is using to identify the object.

3. SetTOProperty (Set Test Object Property)


●​ Temporarily changes the test object's property during runtime, which can influence how UFT identifies it.
●​ Only affects the current test run, not the Object Repository.
●​ Browser("Browser").Page("Page").WebEdit("Username").SetTOProperty "name", "user_name"
●​ Example use case:
●​ If a web element’s name attribute changes dynamically, you can adjust the property UFT uses to locate it.

Summary Table:
Method Description Scope

GetROProperty Gets actual value during runtime Runtime

GetTOProperty Gets property value from the object repository Design-time

SetTOProperty Sets test object property temporarily at runtime Runtime only

Framework Type Data Separation Reusability Ease of Maintenance Non-Technical Friendly

Linear No Low Very Low Yes

Modular No Medium Medium Somewhat

Data-Driven Yes High High No

Keyword-Driven Yes Very High Very High Yes

Hybrid Yes Very High Very High Yes

BDD Yes High High Very High

21. Frameworks are structured ways to design, develop, and execute automated test scripts. They improve reusability,
scalability, maintainability, and readability of test scripts.

What is a Test Automation Framework?


A framework is a combination of guidelines, coding standards, processes, practices, and tools that help in:
●​ Designing test scripts efficiently
●​ Organizing test cases and test data
●​ Ensuring reusability and consistency
●​ Simplifying maintenance and reporting

Major Types of Frameworks in UFT

1. Linear (Record and Playback) Framework


Description: Basic framework where test steps are recorded and played back.
Best For: Beginners or very simple test cases.
Pros: Quick to implement.​
Cons: No reusability or scalability; hard to maintain.
Browser("Google").Page("Google").WebEdit("q").Set "UFT"
Browser("Google").Page("Google").WebButton("Google Search").Click

2. Modular Framework
Description: Breaks the application under test into small, independent functions or modules.​
Approach: Each module is tested with its own script.​
Best For: Medium complexity apps.
Call Login()
Call SearchItem()
Call Logout()
Function Login()
' Code to login
End Function

3. Data-Driven Framework
Description: Test data is separated from test scripts and stored in external files (Excel, CSV, database).
Approach: One script runs with multiple data sets using parameterization.​
Best For: Scenarios requiring multiple inputs.
For i = 1 To DataTable.GetRowCount
username = DataTable("User", dtGlobalSheet)
password = DataTable("Pass", dtGlobalSheet)
Call Login(username, password)
DataTable.SetNextRow
Next

4. Keyword-Driven Framework
Description: Uses keywords to represent actions in test scripts. Testers don’t write VBScript, just define
keywords and data.
Approach: Keywords (like Click, Set, Verify) are mapped to functions.
Best For: Teams with non-technical testers.

Action Object Value


OpenApp browser
SetText usernameField John123
Click loginButton

Select Case Keyword


Case "SetText"
SetText ObjectName, Value
Case "Click"
ClickButton ObjectName
End Select

5. Hybrid Framework
Description: Combines two or more frameworks (usually keyword + data-driven + modular).​
Approach: Most real-world UFT frameworks are hybrid for flexibility and power.​
Best For: Complex applications and enterprise-level projects.
Ex. Structure
Modules: Login.vbs, Search.vbs
Data: Excel sheet
Keywords: Stored in data
Main Script: Calls functions based on keywords and data

6. BDD Framework (Behavior Driven Development)


Not natively supported in UFT but possible with integration.
Tool: Integration with Gherkin language or tools like LeanFT (now part of UFT Developer).​
Format:
Given user is on login page
When user enters valid credentials
Then homepage is displayed
This framework bridges the gap between business analysts and testers by using natural language.
Project Type Recommended Framework

Simple UI Automation Linear or Modular


Repeated Data Scenarios Data-Driven
Inexperienced Testers Keyword-Driven
Complex Application Hybrid
Agile/BDD Development BDD (via UFT Developer/LeanFT)

Tools and Resources Used in UFT Frameworks.


Excel: For test data or keyword input​
Function Libraries (.vbs): For modular and reusable code
Object Repositories: For object recognition​
Environment Variables: For configurations
UFT Test Batches / ALM: For execution​
Custom Logs & Reporter Utility: For reporting

Benefits of Using a Framework.


Promotes code reusability
Easy maintenance
Improves test execution speed
Makes non-technical users contribute (keyword-driven)​
Enables collaboration across teams
Better scalability

A step-by-step guide to build a Hybrid Framework in UFT for automating invoice generation on taxtech.com
using different credentials from Excel. This hybrid framework combines modular, data-driven, and
keyword-driven elements.

OVERVIEW OF THE FRAMEWORK STRUCTURE


Test Case Flow:
Launch browser → Login (from Excel)
Navigate to invoice section → Enter details: Product Name, HSN Code, Weight, Rate/kg​
Calculate GST → Click Print
Close Browser

Components:
Driver Script (Main.vbs): Controls the execution
Function Library (Functions.vbs): Stores reusable functions
Excel Files:​
LoginData.xlsx: Stores usernames & passwords​
InvoiceData.xlsx: Stores product details​
Object Repository (OR.tsr): Stores UI objects (optional if using Descriptive Programming)

1. Prepare Excel Files - LoginData.xlsx


Username Password
[email protected] pass123
[email protected] Pass456

-​ InvoiceData.xlsx
Product Weight RatePerKg
Cement 50 12
Steel Rods 100 20
2: Create Function Library (Functions.vbs)

Function LaunchApp()
SystemUtil.Run "chrome.exe", "https://www.taxtech.com"
Browser("creationtime:=0").Page("title:=.*").Sync
End Function
Function Login(username, password)
With Browser("creationtime:=0").Page("title:=.*")
.WebEdit("name:=username").Set username
.WebEdit("name:=password").SetSecure password
.WebButton("name:=Login").Click
End With
End Function

Function EnterInvoiceDetails(product, weight, rate)


Dim hsnCode : hsnCode = Int((9999 - 1000 + 1) * Rnd + 1000) ' Random HSN

With Browser("creationtime:=0").Page("title:=.*")
.WebEdit("name:=product").Set product
.WebEdit("name:=hsn").Set hsnCode
.WebEdit("name:=weight").Set weight
.WebEdit("name:=rate").Set rate

Dim gst : gst = (weight * rate) * 0.18


.WebEdit("name:=gst").Set gst

.WebButton("name:=Print").Click
End With
End Function

Function CloseBrowser()
Browser("creationtime:=0").Close
End Function

3: Driver Script (Main.vbs)


' Load Function Library
ExecuteFile "C:\UFT_Framework\Functions.vbs"

' Load Excel Sheets


Dim oLogin, oInvoice, i
Set oLogin = CreateObject("Excel.Application")
oLogin.Visible = False
Set oWBLogin = oLogin.Workbooks.Open("C:\UFT_Framework\LoginData.xlsx")
Set oSheetLogin = oWBLogin.Sheets(1)

Set oInvoice = CreateObject("Excel.Application")


oInvoice.Visible = False
Set oWBInvoice = oInvoice.Workbooks.Open("C:\UFT_Framework\InvoiceData.xlsx")
Set oSheetInvoice = oWBInvoice.Sheets(1)

' Loop through login data


For i = 2 To oSheetLogin.UsedRange.Rows.Count
username = oSheetLogin.Cells(i, 1).Value
password = oSheetLogin.Cells(i, 2).Value

LaunchApp()
Login username, password

product = oSheetInvoice.Cells(i, 1).Value


weight = oSheetInvoice.Cells(i, 2).Value
rate = oSheetInvoice.Cells(i, 3).Value

EnterInvoiceDetails product, weight, rate


CloseBrowser()
Next

' Cleanup
oWBLogin.Close False
oLogin.Quit
Set oSheetLogin = Nothing
Set oWBLogin = Nothing
Set oLogin = Nothing

oWBInvoice.Close False
oInvoice.Quit
Set oSheetInvoice = Nothing
Set oWBInvoice = Nothing
Set oInvoice = Nothing

4: Object Repository (Optional) If not using Descriptive Programming, create an Object Repository:
Add fields: username, password, Login, product, hsn, weight, rate, gst, Print
Associate the OR with the test.
5: Run the Test:
Open UFT​
Create a Test → Associate the .vbs files
Ensure Excel files are in the right location
Click Run

OPTIONAL ENHANCEMENTS:
Add Reporter logs: Reporter.ReportEvent micPass, "Login", "Logged in successfully"
Add Error Handling with On Error Resume Next and custom log files
Use Environment Variables for dynamic settings.
Integrate with ALM or Jenkins for CI/CD

You might also like