Your SlideShare is downloading. ×
QTP Presentation2
QTP Presentation2
QTP Presentation2
QTP Presentation2
QTP Presentation2
QTP Presentation2
QTP Presentation2
QTP Presentation2
QTP Presentation2
QTP Presentation2
QTP Presentation2
QTP Presentation2
QTP Presentation2
QTP Presentation2
QTP Presentation2
QTP Presentation2
QTP Presentation2
QTP Presentation2
QTP Presentation2
QTP Presentation2
QTP Presentation2
QTP Presentation2
QTP Presentation2
QTP Presentation2
QTP Presentation2
QTP Presentation2
QTP Presentation2
QTP Presentation2
QTP Presentation2
QTP Presentation2
QTP Presentation2
QTP Presentation2
QTP Presentation2
QTP Presentation2
QTP Presentation2
QTP Presentation2
QTP Presentation2
QTP Presentation2
QTP Presentation2
QTP Presentation2
QTP Presentation2
QTP Presentation2
QTP Presentation2
QTP Presentation2
QTP Presentation2
QTP Presentation2
QTP Presentation2
QTP Presentation2
QTP Presentation2
QTP Presentation2
QTP Presentation2
QTP Presentation2
QTP Presentation2
QTP Presentation2
QTP Presentation2
QTP Presentation2
QTP Presentation2
QTP Presentation2
QTP Presentation2
QTP Presentation2
QTP Presentation2
QTP Presentation2
QTP Presentation2
QTP Presentation2
QTP Presentation2
QTP Presentation2
QTP Presentation2
QTP Presentation2
QTP Presentation2
QTP Presentation2
QTP Presentation2
QTP Presentation2
QTP Presentation2
QTP Presentation2
QTP Presentation2
QTP Presentation2
QTP Presentation2
QTP Presentation2
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×
Saving this for later? Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime – even offline.
Text the download link to your phone
Standard text messaging rates apply

QTP Presentation2

2,425

Published on

How to developt VBScripts without recording

How to developt VBScripts without recording

1 Comment
6 Likes
Statistics
Notes
No Downloads
Views
Total Views
2,425
On Slideshare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
0
Comments
1
Likes
6
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide

Transcript

  • 1. Working with Expert View in QTP
  • 2. Understanding and Using the Expert View
  • 3.
    • Understanding Basic VBScript Syntax
    • Control Test Report
    • Create Automation Test with VB Script
    • Working with MS Excel
    • Using Log File
    • Connect to Database
    • Running DOS Commands and Shell
    • Using VB function library
    • Standardized Automation Script
    • Defining and Using Recovery Scenarios
    • Code Debugging
  • 4. Understanding Basic VBScript Syntax
    • VBScript is an easy-to-learn, yet powerful scripting language. You can use VBScript to develop scripts to perform both simple and complex object-based tasks, even if you have no previous programming experience.
    • This section provides some basic guidelines to help you use VBScript statements to enhance your QuickTest test or function library. For more detailed information about using VBScript, you can view the VBScript documentation from the QuickTest Help menu (Help > QuickTest Professional Help > VBScript Reference).
  • 5. Using Variables Set UserEditBox = Browser("Mercury Tours").Page("Mercury Tours"). WebEdit("username") UserEditBox.Set "John" MyVar = Browser("Mercury Tours").Page("Mercury Tours"). WebEdit("username").GetTOProperty("type") Dim passengers passengers = Browser("Mercury Tours").Page("Find Flights"). WebEdit("numpassengers").GetROProperty("value") Understanding Basic VBScript Syntax
  • 6. Functions
    • Conversion Functions
    • String Functions
    • Numerical Functions
    • Date and Time Functions
    Understanding Basic VBScript Syntax
  • 7. Conversion Functions 1. CDate Function CDate(date) Convert to Date data type. MyDate = "October 19, 1962" ' Define date. MyShortDate = CDate(MyDate) ' Convert to Date data type. MyTime = "4:35:47 PM" ' Define time. MyShortTime = CDate(MyTime) ' Convert to Date data type. 2. CInt Function CInt(expression) Returns an expression that has been converted to a Variant of subtype Integer. Dim MyDouble, MyInt MyDouble = 2345.5678 ' MyDouble is a Double. MyInt = CInt(MyDouble) ' MyInt contains 2346. Understanding Basic VBScript Syntax
  • 8. Conversion Functions 3. CLng Function CLng(expression) Returns an expression that has been converted to a Variant of subtype Long. Dim MyVal1, MyVal2, MyLong1, MyLong2 MyVal1 = 25427.45: MyVal2 = 25427.55 ' MyVal1, MyVal2 are Doubles. MyLong1 = CLng(MyVal1) ' MyLong1 contains 25427. MyLong2 = CLng(MyVal2) ' MyLong2 contains 25428. 4. CStr Function CStr(expression) Returns an expression that has been converted to a Variant of subtype String. Dim MyDouble, MyString MyDouble = 437.324 ' MyDouble is a Double. MyString = CStr(MyDouble) ' MyString contains "437.324". Understanding Basic VBScript Syntax
  • 9. String Functions 1. UCase Function UCase(string) Returns a string that has been converted to uppercase. Dim MyWord MyWord = UCase("Hello World") ' Returns "HELLO WORLD". 2. LCase Function LCase(string) Returns a string that has been converted to lowercase. Dim MyString Dim LCaseString MyString = "VBSCript" LCaseString = LCase(MyString) ' LCaseString contains "vbscript". Understanding Basic VBScript Syntax
  • 10. String Functions 3. Replace Function Replace(expression, find, replacewith[, start[, count[, compare]]]) Returns a string in which a specified substring has been replaced with another substring a specified number of times. Dim MyString ' A binary comparison starting at the beginning of the string. MyString = Replace("XXpXXPXXp", "p", "Y") ' Returns "XXYXXPXXY". ' A textual comparison starting at position 3. MyString = Replace("XXpXXPXXp", "p", "Y", 3, -1, 1) ' Returns "YXXYXXY". 4. Right Function Right(string, length) Returns a specified number of characters from the right side of a string. Dim AnyString, MyStr AnyString = "Hello World" ' Define string. MyStr = Right(AnyString, 1) ' Returns "d". MyStr = Right(AnyString, 6) ' Returns " World". MyStr = Right(AnyString, 20) ' Returns "Hello World". Understanding Basic VBScript Syntax
  • 11. String Functions 5. Left Function Left(string, length) Returns a specified number of characters from the left side of a string. Dim MyString, LeftString MyString = "VBSCript" LeftString = Left(MyString, 3) ' LeftString contains "VBS". 6. Len Function Len(string | varname) Returns the number of characters in a string or the number of bytes required to store a variable. Dim MyString MyString = Len("VBSCRIPT") ' MyString contains 8. Understanding Basic VBScript Syntax
  • 12. String Functions 7. LTrim; RTrim; and Trim Functions LTrim(string) RTrim(string) Trim(string) Returns a copy of a string without leading spaces (LTrim), trailing spaces (RTrim), or both leading and trailing spaces (Trim). Dim MyVar MyVar = LTrim(" vbscript ") ' MyVar contains "vbscript ". MyVar = RTrim(" vbscript ") ' MyVar contains " vbscript". MyVar = Trim(" vbscript ") ' MyVar contains "vbscript". 8. InStr Function InStr([start, ]string1, string2[, compare]) Returns the position of the first occurrence of one string within another. Dim SearchString, SearchChar, MyPos SearchString ="XXpXXpXXPXXP" ' String to search in. SearchChar = "P" ' Search for "P". MyPos = Instr(4, SearchString, SearchChar, 1) ' A textual comparison starting at position 4. Returns 6. MyPos = Instr(1, SearchString, SearchChar, 0) ' A binary comparison starting at position 1. Returns 9. MyPos = Instr(SearchString, SearchChar) ' Comparison is binary by default (last argument is omitted). Returns 9. MyPos = Instr(1, SearchString, "W") ' A binary comparison starting at position 1. Returns 0 ("W" is not found). Understanding Basic VBScript Syntax
  • 13. String Functions 9. Mid Function Mid(string, start[, length]) Returns a specified number of characters from a string. Dim MyVar MyVar = Mid("VBScript is fun!", 3, 6) ' MyVar contains "Script". 10. Split Function Split(expression[, delimiter[, count[, compare]]]) Returns a zero-based, one-dimensional array containing a specified number of substrings. Dim MyString, MyArray, Msg MyString = "VBScriptXisXfun!" MyArray = Split(MyString, "x", -1, 1) ' MyArray(0) contains "VBScript". ' MyArray(1) contains "is". ' MyArray(2) contains "fun!". Msg = MyArray(0) & " " & MyArray(1) Msg = Msg & " " & MyArray(2) MsgBox Msg Understanding Basic VBScript Syntax
  • 14. Numerical Functions 1. Round Function Round(expression[, numdecimalplaces]) Returns a number rounded to a specified number of decimal places. Dim MyVar, pi pi = 3.14159 MyVar = Round(pi, 2) ' MyVar contains 3.14. 2. FormatPercent Function FormatPercent(Expression[,NumDigitsAfterDecimal [,IncludeLeadingDigit [,UseParensForNegativeNumbers [,GroupDigits]]]]) Returns an expression formatted as a percentage (multiplied by 100) with a trailing % character. Dim MyPercent MyPercent = FormatPercent(2/32) ' MyPercent contains 6.25%. Understanding Basic VBScript Syntax
  • 15. Numerical Functions 3. Rnd Function Rnd[(number)] Returns a random number. Int((upperbound - lowerbound + 1) * Rnd + lowerbound) 4. Sqr Function Sqr(number) Returns the square root of a number. Dim MySqr MySqr = Sqr(4) ' Returns 2. MySqr = Sqr(23) ' Returns 4.79583152331272. MySqr = Sqr(0) ' Returns 0. MySqr = Sqr(-4) ' Generates a run-time error. Understanding Basic VBScript Syntax
  • 16. Date and Time Functions 1. Date Function Date Returns the current system date. Dim MyDate MyDate = Date ' MyDate contains the current system date. 2. DateAdd Function DateAdd(interval, number, date) Returns a date to which a specified time interval has been added. NewDate = DateAdd("m", 1, "31-Jan-95") 'In this case, DateAdd returns 28-Feb-95, not 31-Feb-95. If date is 31-Jan-96, it returns 29-Feb-96 because 1996 is a leap year. Understanding Basic VBScript Syntax
  • 17. Date and Time Functions 3. DateDiff Function DateDiff(interval, date1, date2 [,firstdayofweek[, firstweekofyear]]) Returns the number of intervals between two dates. Function DiffADate(theDate) DiffADate = "Days from today: " & DateDiff("d", Now, theDate) End Function 4. Day Function Day(date) Returns a whole number between 1 and 31, inclusive, representing the day of the month. Dim MyDay MyDay = Day("October 19, 1962") ' MyDay contains 19. Understanding Basic VBScript Syntax
  • 18. Date and Time Functions 5. Month Function Month(date) Returns a whole number between 1 and 12, inclusive, representing the month of the year. Dim MyVar MyVar = Month(Now) ' MyVar contains the number corresponding to ' the current month. 6. MonthName Function MonthName(month[, abbreviate]) Returns a string indicating the specified month. Dim MyVar MyVar = MonthName(10, True) ' MyVar contains "Oct". Understanding Basic VBScript Syntax
  • 19. Date and Time Functions 7. Now Function Now Returns the current date and time according to the setting of your computer's system date and time. Dim MyVar MyVar = Now ' MyVar contains the current date and time. 8. Minute Function (VBScript) Minute(time) Returns a whole number between 0 and 59, inclusive, representing the minute of the hour. Dim MyVar MyVar = Minute(Now) 9. Time Function Time Returns a Variant of subtype Date indicating the current system time. Dim MyTime MyTime = Time ' Return current system time. Understanding Basic VBScript Syntax
  • 20. Date and Time Functions 10. Weekday Function Weekday(date, [firstdayofweek]) Returns a whole number representing the day of the week (Starts from Sunday). Dim MyDate, MyWeekDay MyDate = #October 19, 1962# ' Assign a date. MyWeekDay = Weekday(MyDate) ' MyWeekDay contains 6 because MyDate represents a Friday. 11. WeekdayName Function WeekdayName(weekday, abbreviate, firstdayofweek) Returns a string indicating the specified day of the week. Dim MyDate MyDate = WeekDayName(6, True) ' MyDate contains Fri. 12. Year Function Year(date) Returns a whole number representing the year. Dim MyDate, MyYear MyDate = #October 19, 1962# ' Assign a date. MyYear = Year(MyDate) ' MyYear contains 1962. Understanding Basic VBScript Syntax
  • 21. Statements
    • For...Next Statement
    • For...Each Statement
    • Do...Loop Statement
    • While...Wend Statement
    • If...Then...Else Statement
    • With Statement
    • Select Case Statement
    • Execute Statement
    • On Error Statement
    Understanding Basic VBScript Syntax
  • 22. For...Next Statement Repeats a group of statements a specified number of times. For counter = start To end [Step step] [statements] [Exit For] [statements] Next For I = 1 To 10 For J = 1 To 10 For K = 1 To 10 . . . Next Next Next Understanding Basic VBScript Syntax
  • 23. For...Each Statement Repeats a group of statements for each element in an array or collection. For Each item In array statement Next MyArray = Array("one","two","three","four","five") For Each element In MyArray msgbox element Next Understanding Basic VBScript Syntax
  • 24. Do...Loop Statement Repeats a block of statements while a condition is True or until a condition becomes True. Do [{While | Until} condition] [statements] [Exit Do] [statements] Loop Or, you can use this syntax: Do [statements] [Exit Do] [statements] Loop [{While | Until} condition] Do Until DefResp = vbNo MyNum = Int (6 * Rnd + 1) ' Generate a random integer between 1 and 6. DefResp = MsgBox (MyNum & &quot; Do you want another number?&quot;, vbYesNo) Loop Dim Check, Counter Check = True: Counter = 0 ' Initialize variables. Do ' Outer loop. Do While Counter < 20 ' Inner loop. Counter = Counter + 1 ' Increment Counter. If Counter = 10 Then ' If condition is True... Check = False ' set value of flag to False. Exit Do ' Exit inner loop. End If Loop Loop Until Check = False ' Exit outer loop immediately. Understanding Basic VBScript Syntax
  • 25. While...Wend Statement Executes a series of statements as long as a given condition is True. While condition Version [statements] Wend Dim Counter Counter = 0 ' Initialize variable. While Counter < 20 ' Test value of Counter. Counter = Counter + 1 ' Increment Counter. Alert Counter Wend ' End While loop when Counter > 19. Understanding Basic VBScript Syntax
  • 26. If...Then...Else Statement Conditionally executes a group of statements, depending on the value of an expression. If condition Then statements [Else elsestatements ] Or, you can use the block form syntax: If condition Then [statements] [ElseIf condition-n Then [elseifstatements]] . . . [Else [elsestatements]] End If passengers = Browser(&quot;Mercury Tours&quot;).Page(&quot;Find Flights&quot;). WebEdit(&quot;numpassengers&quot;).GetROProperty(&quot;value&quot;) If (passengers < 4) Then Browser(&quot;Mercury Tours&quot;).Close Else Browser(&quot;Mercury Tours&quot;).Page(&quot;Find Flights&quot;).Image(&quot;continue&quot;).Click 69,5 End If Understanding Basic VBScript Syntax
  • 27. With Statement Executes a series of statements on a single object. With object statements End With With MyLabel .Height = 2000 .Width = 2000 .Caption = &quot;This is MyLabel&quot; End With Understanding Basic VBScript Syntax
  • 28. Select Case Statement Executes one of several groups of statements, depending on the value of an expression. Select Case testexpression [Case expressionlist-n [statements-n]] . . . [Case Else expressionlist-n [elsestatements-n]] End Select Dim Color, MyVar Sub ChangeBackground (Color) MyVar = lcase (Color) Select Case MyVar Case &quot;red&quot; document.bgColor = &quot;red&quot; Case &quot;green&quot; document.bgColor = &quot;green&quot; Case &quot;blue&quot; document.bgColor = &quot;blue&quot; Case Else MsgBox &quot;pick another color&quot; End Select End Sub Understanding Basic VBScript Syntax
  • 29. Execute Statement Executes one or more specified statements. Execute statement Dim X ' Declare X in global scope. X = &quot;Global&quot; ' Assign global X a value. Sub Proc1 ' Declare procedure. Dim X ' Declare X in local scope. X = &quot;Local&quot; ' Assign local X a value. ' The Execute statement here creates a ' procedure that, when invoked, prints X. ' It print the global X because Proc2 ' inherits everything in global scope. Execute &quot;Sub Proc2: Print X: End Sub&quot; Print Eval(&quot;X&quot;) ' Print local X. Proc2 ' Invoke Proc2 in Proc1's scope. End Sub Proc2 ' This line causes an error since ' Proc2 is unavailable outside Proc1. Proc1 ' Invoke Proc1. Execute &quot;Sub Proc2: Print X: End Sub&quot; Proc2 ' This invocation succeeds because Proc2 ' is now available globally. Understanding Basic VBScript Syntax
  • 30. On Error Statement Enables or disables error-handling. On Error Resume Next On Error GoTo 0 On Error Resume Next Err.Raise 6 ' Raise an overflow error. MsgBox &quot;Error # &quot; & CStr(Err.Number) & &quot; &quot; & Err.Description Err.Clear ' Clear the error. Understanding Basic VBScript Syntax
  • 31. Create Automation Test with VB Script
  • 32. Control DataTable
    • AddSheet
    • DeleteSheet
    • Export
    • ExportSheet
    • GetCurrentRow
    • GetRowCount
    • GetSheet
    • GetSheetCount
    • Import
    • ImportSheet
    • SetCurrentRow
    Create Automation Test with VB Script
  • 33. Control DataTable 1. AddSheet DataTable.AddSheet(SheetName) Dim Variable Variable=DataTable.AddSheet (&quot;MySheet&quot;).AddParameter(&quot;Time&quot;, &quot;8:00&quot;) 2. DeleteSheet DataTable.DeleteSheet SheetID DataTable.DeleteSheet &quot;MySheet&quot; 3. Export DataTable.Export(FileName) DataTable.Export (&quot;C:flights.xls&quot;) 4. ExportSheet DataTable.ExportSheet(FileName, DTSheet) DataTable.ExportSheet &quot;C: ame.xls”, 1 DataTable.ExportSheet &quot;C: ame.xls”, &quot;MySheet&quot; Create Automation Test with VB Script
  • 34. Control DataTable 5. GetCurrentRow DataTable.GetCurrentRow row = DataTable.GetCurrentRow Reporter.ReportEvent 1, &quot;Item&quot;, row 6. GetRowCount DataTable.GetRowCount rowcount = DataTable.GetSheet(&quot;MySheet&quot;).GetRowCount Reporter.ReportEvent 2, &quot;Total &quot; &rowcount, &quot; rows.&quot; 7. GetSheet DataTable.GetSheet(SheetID) MyParam=DataTable.GetSheet (&quot;MySheet&quot;).AddParameter(&quot;Time&quot;, &quot;8:00&quot;) DataTable.GetSheet (&quot;MySheet&quot;).AddParameter &quot;Time&quot;, &quot;8:00&quot; Create Automation Test with VB Script
  • 35. Control DataTable 8. GetSheetCount DataTable.GetSheetCount sheetcount = DataTable.GetSheetCount Reporter.ReportEvent 0, &quot;WorkSheet Number&quot;, &quot;There are total &quot; & sheetcount & &quot; WorkSheets.&quot; 9. Import DataTable.Import(FileName) DataTable.Import (&quot;C:flights.xls&quot;) 10. ImportSheet DataTable.ImportSheet(FileName, SheetSource, SheetDest) DataTable.ImportSheet &quot;C: ame.xls”, 1,&quot; Action1&quot; Don't use Global Table!! DataTable.ImportSheet &quot;C: ame.xls”, 1,&quot; Global&quot; 11. SetCurrentRow DataTable.SetCurrentRow(RowNumber) Create Automation Test with VB Script
  • 36. Control Test Report Choosing Which Steps to Report During the Run Session You can use the Report.Filter method to determine which steps or types of steps are included in the Test Results. You can completely disable or enable reporting of steps following the statement, or you can indicate that you only want subsequent failed or failed and warning steps to be included in the report. You can also use the Report.Filter method to retrieve the current report mode.
  • 37. Control Test Report To disable reporting of subsequent steps, enter the following statement: Reporter.Filter = rfDisableAll To re-enable reporting of subsequent steps, enter: Reporter.Filter = rfEnableAll To instruct QuickTest to include only subsequent failed steps in the Test Results, enter: Reporter.Filter = rfEnableErrorsOnly To instruct QuickTest to include only subsequent failed or warning steps in the Test Results, enter: Reporter.Filter = rfEnableErrorsAndWarnings To retrieve the current report mode, enter: MyVar=Reporter.Filter For more information, refer to the QuickTest Professional Object Model Reference.
  • 38. Sample Code Reporter.ReportEvent 0, a, &quot;Exist in the table“ ‘ Reporter.ReportEvent <Result (Pass=0 or Fail =1)>, <Object>, <Details> Control Test Report
  • 39. Create Automation Test with VB Script Example and Exercise
  • 40. Working with MS Excel
  • 41. Sample Code I Working with MS Excel Dim DataInFile DataInFile=&quot;C:QTPAcctno.xls&quot; 'Import Excel file to get account numbers DataTable.Import (DataInFile) A=1 Do Until AcctNo = &quot;&quot; ...... 'Update Excel file DataTable.GetSheet(&quot;Sheet1&quot;).GetParameter(&quot;TestInfo&quot;).ValueByRow(A) = &quot;Pass“ 'Export Excel file DataTable.Export(DataInFile) A=A+1 'Read Excel file AcctNo=DataTable.GetSheet(&quot;Sheet1&quot;).GetParameter(&quot;AccountNumber&quot;).ValueByRow(A) AcctNo=Trim(AcctNo) Loop
  • 42. Sample Code II Working with MS Excel arrRange = ReadFile(&quot;D:QTPMyWorkReadExcelFileTest1ObjectTree.xls&quot;,&quot;Tree&quot;) ' Read a value in Excel File Msgbox arrRange(3,1) ' sFileName: Excel file name, sSheetName: Data Sheet name Function ReadFile(sFileName,sSheetName) Dim oExcel Dim oSheet Dim oRange Dim arrRange On Error Resume Next ' Create Excel Object Set oExcel = CreateObject(&quot;Excel.Application&quot;) If err.Number <> 0 Then MsgBox “Cannot read Excel&quot; & vbCrLf & _ “ Please conform Excel has been installed&quot;, vbCritical Exit Function End If On Error Goto 0
  • 43. Sample Code II (continue) Working with MS Excel On Error Resume Next ' Open Excel File oExcel.Workbooks.Open(sFileName) If err.Number <> 0 Then MsgBox “Cannot open Excel file&quot; & vbCrLf & _ “ Please conform the file directory is correct&quot;, vbCritical Exit Function End If On Error Goto 0 ' Get Date Sheet Range Set oSheet = oExcel.Worksheets(sSheetName).UsedRange ' Reading from Column A to Column Z, from Row 1 to Row 1000 Set oRange = oSheet.Range(&quot;A1:Z1000&quot;) arrRange = oRange.Value ' Close Excel oExcel.WorkBooks.Item(1).Close ' Exist Excel oExcel.Quit Set oExcel = Nothing ' Return the value ReadFile = arrRange End Function
  • 44. Using Log File
  • 45. Sample Code Using Log File Dim LOGFile, fso, MyFile LOGFile=&quot;D:Log.txt&quot; Set fso = CreateObject(&quot;Scripting.FileSystemObject&quot;) If fso.FileExists(LOGFile) = False Then Set MyFile = fso.CreateTextFile(LOGFile, True) MyFile.Close end if Set MyFile = fso.OpenTextFile(LOGFile, 8, True) MyFile.WriteLine(&quot;&quot;) MyFile.WriteLine(&quot; &quot; & Cstr(Now) & &quot; ---------------------------------------------------------&quot;) MyFile.Close ' Write Log file Set MyFile = fso.OpenTextFile(LOGFile, 8, True) MyFile.WriteLine(&quot;&quot;) For I = 1 To 10 MyFile.WriteLine(I & “ Test Passed!&quot;) Next MyFile.Close
  • 46. Connect to Database
  • 47. Sample Code (MS SQL Server) Connect to Database Dim res,cmd,sql Dim MyFile Set Res=createobject(&quot;adodb.recordset&quot;) Set Cmd=createobject(&quot;adodb.command&quot;) Cmd.activeconnection=&quot;Provider=SQLOLEDB.1;Password= password ;Persist Security Info=True;User ID= User ;Initial Catalog= northwind ;Data Source= 192.168.1.22 &quot; Cmd.CommandType = 1 'sql=&quot;Select count(*) from customers&quot; sql=&quot;select FirstName, LastName from Employees order by FirstName&quot; Cmd.CommandText = sql Set res = Cmd.Execute() a = 1 Do until res.EOF MyFile.WriteLine(a & &quot;. &quot; &res.Fields(0).Value &&quot; &quot;&res.Fields(1).Value) res.MoveNext a = a+1 Loop MyFile.Close Set res = nothing Set cmd.ActiveConnection = nothing Set Cmd= nothing
  • 48. Exercise (20 minuets) Requirement: Create a QTP automation script to verify the customer names from customer table in Northwind instance and export the test result to a Excel file. This test requests log file to tracing unexpected failure.
  • 49. Running DOS Commands
  • 50. Sample Code Running DOS Commands and Shell Dim oShell Set oShell = CreateObject (&quot;WSCript.shell&quot;) oShell.run &quot;cmd /K CD C: & Dir&quot; Set oShell = Nothing Dim UserName UserName = “TestUser” set WshShell =CreateObject(&quot;WScript.Shell&quot;) WshShell.Sendkeys(UserName) Wscript.sleep 100 ‘Wait WshShell.SendKeys &quot;{TAB}“ ‘Use TAB Key WshShell.Sendkeys &quot;{Enter}“ ‘Type Enter WshShell.AppActivate &quot;Calculator&quot; ‘Run Calculator
  • 51. Standardized Automation Script
  • 52. ‘ Use Comments ‘ Sets the word &quot;mercury&quot; into the &quot;username&quot; edit box. Browser(&quot;Mercury Tours&quot;).Page(&quot;Mercury Tours&quot;).WebEdit(&quot;username&quot;). Set &quot;mercury“ Indenting Statements You can indent your statements by selecting the statements and clicking the Indent button. Alternatively, you can select text and choose Edit > Advanced > Indent or press the TAB key. Use Action Template Create a VBS template and name it as “ActionTemplate.mst”. Save it into “Dat” folder which is under the QTP installation directory. Standardized Automation Script
  • 53. Defining and Using Recovery Scenarios
  • 54. Defining and Using Recovery Scenarios A recovery scenario consists of the following: ➤ Trigger Event —The event that interrupts your run session. For example, a window that may pop up on screen, or a QuickTest run error. ➤ Recovery Operation(s) —The operation(s) that need to be performed in order to continue running the test. For example, clicking an OK button in a pop-up window, or restarting Microsoft Windows. ➤ Post-Recovery Test Run Option —The instructions on how QuickTest should proceed once the recovery operations have been performed, and from which point in the test QuickTest should continue, if at all. For example, you may want to restart a test from the beginning, or skip a step entirely and continue with the next step in the test.
  • 55. Defining and Using Recovery Scenarios 1. Deciding When to Use Recovery Scenarios 2. Defining Recovery Scenarios 3. To create a recovery file Using Recovery Scenario Manager dialog box Choose Resources > Recovery Scenario Manager Using Welcome to the Recovery Scenario Wizard Screen Click on the New Scenario button on Recovery Scenario Manager 4. Managing Recovery Scenarios 5. Programmatically Controlling the Recovery Mechanism
  • 56. Using On Error Statement Enables or disables error-handling. On Error Resume Next On Error GoTo 0 On Error Resume Next Err.Raise 6 ' Raise an overflow error. MsgBox &quot;Error # &quot; & CStr(Err.Number) & &quot; &quot; & Err.Description Err.Clear ' Clear the error. If Browser(&quot;Mercury Tours&quot;).Page(&quot;Find Flights&quot;).exist Then …… End If Defining and Using Recovery Scenarios
  • 57. Code Debugging
  • 58. Code Debugging Using the Single Step Commands 1. Choose File > New > Test to open a new test or File > New > Function Library to open a new function library (in addition to your test). 2. If you created a new test, click the Expert View tab to display the Expert View. 3. In the test or function library, enter the following lines exactly: public Function myfunc() msgbox &quot;one&quot; msgbox &quot;two&quot; msgbox &quot;three&quot; End Function myfunc myfunc myfunc
  • 59. Code Debugging Using the Run to Step and Start from Step Commands Run to Step ➤ Insert your cursor in the step in which you want QuickTest to stop the run and choose Debug > Run to Step or press CTRL+F10 ➤ Right-click in the step in which you want QuickTest to stop the run and choose Run to Step from the context menu Start from Step ➤ Insert your cursor in the step where you want QuickTest to start the run and choose Debug > Start from Step, or ➤ Right-click in the step where you want QuickTest to start the run and choose Debug from Step from the context menu.
  • 60. Code Debugging Using Breakpoints To set a breakpoint: Perform one of the following: ➤ Click in the left margin of a step in the test or function library where you want the run to stop ➤ Click a step and then: • Click the Insert/Remove Breakpoint button • Choose Debug > Insert/Remove Breakpoint • Press F9 The breakpoint symbol is displayed in the left margin of the test or function library. To enable/disable a specific breakpoint: 1. Click in the line containing the breakpoint you want to disable/enable. 2. Choose Debug > Enable/Disable Breakpoint or press CTRL+F9. The breakpoint is either disabled or enabled (depending on its previous state). To enable/disable all breakpoints: Choose Debug > Enable/Disable All Breakpoints or click the Enable/Disable All Breakpoints button.
  • 61. Code Debugging Using Breakpoints To remove a single breakpoint: Perform one of the following: ➤ Click the breakpoint. ➤ Click the line in your test or function library with the breakpoint symbol and: • Click the Insert/Remove Breakpoint button • Choose Debug > Insert/Remove Breakpoint To remove all breakpoints: Click the Clear All Breakpoints button, or choose Debug > Clear All Breakpoints.
  • 62. Code Debugging Using the Debug Viewer To open the Debug Viewer pane: Choose View > Debug Viewer or click the Debug Viewer button. To add an expression to the Watch tab: Perform one of the following: ➤ Click the expression and choose Debug > Add to Watch ➤ Click the expression and press CTRL+T ➤ Right-click the expression and choose Add to Watch from the context menu ➤ In the Watch tab, paste or type the name of the object or variable into the Name column and press ENTER to view the current value in the Value column
  • 63. Other Automation Script in QTP QTP - How to test PDF file… ‘ ************************************************************** ‘ Purpose: Open PDF document and get the number of pages in PDF file ‘ Date : ‘ Comments: Change the path of PDF document ‘ ************************************************************** Option Explicit Dim gApp, gPDDoc, jso Set gApp = CreateObject( &quot;AcroExch.App&quot; ) Set gPDDoc = CreateObject( &quot;AcroExch.PDDoc&quot; ) If gPDDoc.Open( &quot;D:DocAutomatedTesting.pdf&quot; ) Then Msgbox gPDDoc.GetNumPages End If Set gPDDoc = Nothing : Set gApp = Nothing
  • 64. Other Automation Script in QTP QTP - How to use class and forms of Dot net… ‘ ************************************************************** ‘ Purpose: Sample of QTP script using DotNetFactory Object ‘ Date : ‘ Comments: ‘ ************************************************************** Set var_CreateInstance = DotNetFactory.CreateInstance(&quot;System.Windows.Forms.Form&quot;, &quot;System.Windows.Forms&quot;) var_CreateInstance.Show wait 2 var_CreateInstance.Close Set obj = DotNetFactory.CreateInstance(&quot;Test.myTest.QTPTest“, &quot;d:mtTest.dll“) obj.DoAction
  • 65. Working with User-Defined Functions and Function Libraries
  • 66. Using VB function library To create a new function library in QuickTest: Perform one of the following: ➤ Choose File > New > Function Library ➤ Click the New button down arrow and choose Function Library Open Associated Function Libraries: Perform one of the following: ➤ Choose File > Settings > Resources tab ➤ Select the associated Function Library
  • 67. Using VB function library To create a new function library in QuickTest: Perform one of the following: ➤ Choose File > New > Function Library ➤ Click the New button down arrow and choose Function Library Open Associated Function Libraries: Perform one of the following: ➤ Choose File > Settings > Resources tab ➤ Select the associated Function Library
  • 68. Sample Function Libraries and Scripts
  • 69. Sample Function Libraries and Scripts '********************************************* ' Get current date '********************************************* Public Function Get_Data() Dim currentDate currentDate = Date Get_Data = currentDate End Function '********************************************* ' Get current time '********************************************* Public Function Get_Time() Dim currentTime currentTime = Time Get_Time = currentTime End Function
  • 70. Sample Function Libraries and Scripts '********************************************* ' Get random number ' The fromNum and toNum must greater than zero '********************************************* Public Function Get_RandNum(fromNum,toNum) Dim TempNum If (fromNum<0) Or (toNum<0) Then MsgBox &quot;The input numbers must greater than zero!&quot; ElseIf fromNum>toNum then TempNum = fromNum fromNum = toNum toNum = TempNum Else Dim RunTime Randomize RunTime = Int((10 * Rnd) + 1) Dim MyValue,i For i = 1 To RunTime Randomize MyValue = Int(((toNum - fromNum + 1) * Rnd) + (fromNum)) Next Get_randNum=MyValue End If End Function
  • 71. Sample Function Libraries and Scripts '********************************************* ' Read the content on specific row in TXT file '********************************************* Function ReadLine(pathway, rowcount) Dim fso,myfile,i,flag flag = 1 Set fso=CreateObject(&quot;scripting.FileSystemObject&quot;) If fso.FileExists(pathway) then Set myfile = fso.openTextFile(pathway,1,false) Else flag = 0 End If For i=1 to rowcount-1 If Not myfile.AtEndOfLine Then myfile.SkipLine End If Next If flag = 1 then If Not myfile.AtEndOfLine Then ReadLine = myfile.ReadLine Else ReadLine = &quot;Error: Out of range!&quot; End If myfile.close Else ReadLine = &quot;Error: The file is NOT existed!&quot; End If End Function
  • 72. Sample Function Libraries and Scripts '********************************************* ' Send Email through Outlook '********************************************* Function SendMail(SendTo, Subject, Body, Attachment) Dim ol,mail Set ol=CreateObject(&quot;Outlook.Application&quot;) Set Mail=ol.CreateItem(0) Mail.to=SendTo Mail.Subject=Subject Mail.Body=Body If (Attachment <> &quot;&quot;) Then Mail.Attachments.Add(Attachment) End If Mail.Send ol.Quit Set Mail = Nothing Set ol = Nothing End Function
  • 73. Sample Function Libraries and Scripts '********************************************* ' Run Command '********************************************* Sub Run() Dim WshShell set WshShell = CreateObject(&quot;Wscript.Shell&quot;) WshShell.SendKeys &quot;^{ESC}R&quot; Set WshShell = nothing End Sub '********************************************* ' Run Application '********************************************* Sub RunApp(command) Dim WshShell set WshShell = CreateObject(&quot;Wscript.Shell&quot;) WshShell.Exec command End Sub
  • 74. Sample Function Libraries and Scripts '********************************************* ' Run QTP in minimize size '********************************************* Public Sub QTP_Small() Dim objQTPWin Set objQTPWin = GetObject(&quot;&quot; , &quot;QuickTest.Application&quot;) objQTPWin.WindowState = &quot;Minimized&quot; Set objQTPWin = Nothing End Sub '********************************************* ' Return QTP window '********************************************* Public Sub QTP_Big() Dim objQTPWin Set objQTPWin = GetObject(&quot;&quot; , &quot;QuickTest.Application&quot;) objQTPWin.WindowState = &quot;Restored&quot; Set objQTPWin = Nothing End Sub
  • 75. Sample Function Libraries and Scripts '********************************************* ' Take Screen Print '********************************************* Public Function QTP_Capture(pathway) Dim datestamp Dim filename datestamp = Now() filename = Environment(&quot;TestName&quot;)&&quot;_&quot;&datestamp&&quot;.png&quot; filename = Replace(filename,&quot;/&quot;,&quot;&quot;) filename = Replace(filename,&quot;:&quot;,&quot;&quot;) pathway = Trim(pathway) If Right(pathway, 1) = &quot;&quot; Then filename = pathway + &quot;&quot;&filename Else filename = pathway + &quot;&quot; + &quot;&quot;&filename End If Desktop.CaptureBitmap filename 'Reporter.ReportEvent micFail,&quot;image&quot;,&quot;<img src='&quot; & filename & &quot;'>&quot; End Function
  • 76. Sample Function Libraries and Scripts '********************************************* ' Set date format (dd-mmm-yyyy) '********************************************* Function MyCdate(oDate) currentLocale = GetLocale original = SetLocale(&quot;en-ca&quot;) mon=left(cstr(FormatDateTime(oDate,1)),3) original = SetLocale(currentLocale) MyCdate=cstr(day(odate))+&quot;-&quot;+mon+&quot;-&quot;+cstr(year(odate)) End Function '********************************************* ' Close all the existing IE windows '********************************************* Sub CloseWeb() Dim WinIe,Ie,i,m Set WinIe=description.Create() WinIe(&quot;regexpwndtitle&quot;).value=&quot;Microsoft Internet Explorer&quot; Set Ie=desktop.ChildObjects(WinIe) m=Ie.count For i=1 to m Ie(i-1).close '0 is the last window Next End Sub
  • 77. Using Third Party Tools ➤ PSPad http://www.pspad.com ➤ VbsEdit http://www.vbsedit.com ➤ Toad http://www.quest.com
  • 78. Questions?

×