Functional Pointer in VBScript Abstract Function pointers are used in C and C++ to enable callbacks and as a result, more generic

and parsimonious coding. This article shows how to implement function pointers in VB Script using the Scripting.Dictionary object and the Command Wrapper design pattern. It is also shown how to implement “constructor” functions, callbacks land event handlers.

Keywords: function pointer, callback, delegate, scripting dictionary, hash table, design pattern, command wrapper, event handler. Introduction In the following sections I shall explain several basic concepts that are essential to understand the rationale behind the suggested method. The list might be nonexhaustive and the reader is hereby encouraged to recur to complementary sources to fill-in any eventual knowledge gaps. Function Pointers A function pointer is a variable that stores the memory address of a block of code that is programmed to fulfill a specific function. Function pointers are useful to avoid complex switch case structures; instead, they support direct access in run-time to previously loaded functions or class methods. This enables the construction of callback functions. A callback is, in essence, executable code that is passed as argument to a function. This enables more generic coding, by having lower-level modules calling higher-level functions or subroutines. Function pointers are supported by programming languages like C and C++. A recent good introductory text on the subject with implementation examples is Lars Haendel (2005). This article shows how to implement function pointers in VB script. Design Patterns Design patterns are well established generic design techniques whose aim is to make software design and the derived code more parsimonious, scalable, and reusable, as well as more easily maintainable. This article will delve only into the command wrapper design pattern, which is important for its purpose. For a more extensive explanation of

design patterns, the reader is encouraged to read the literature in the field (e.g., Gamma, Helm, Johnson, & Vlissides, 1997). The command-wrapper design pattern enables to load blocks of code dynamically to memory as well as other uses as will be reviewed below. The singleton design pattern is used to restrict instantiation of a class to one object. This is useful when there is no need for more than one object within a system (e.g., a reporter/logger object). For example, the factory design pattern usually implements the singleton design pattern to have a single interface from which to retrieve references to a specific class object or to a variety of class objects. The Command Wrapper Design Pattern The command wrapper design pattern is a technique that implements a function as a class, usually with a single public method. During run-time, it is possible to instantiate the class and thus to get a reference (or pointer) to the object. This way, the code embodied in such methods can be dynamically loaded, a feature that can be of great value in systems that are poor in resources. This is especially true when the to-be called function is rarely used. After creating the object, it is possible to execute its method according to need. For example, let us assume a function that adds numbers (note: this example is, of course, trivial. It is done just to illustrate the point.)
1: Public Function Sum(ByVal arrNumbers) 2: Dim ix 3: 4: 'Check if an array was passed. If so, there's nothing to do – exit function 5: If (Not IsArray(arrNumbers)) Then 6: 'Add your error handling code here 7: Exit Function 8: End If 9: 10: Sum = 0 11: For ix = LBound(arrNumbers) To UBound(arrNumbers) 12: If (IsNumeric(arrNumbers(ix))) Then 13: Sum = Sum + arrNumbers(ix) 14: Else 15: 'Add your error handling code here 16: End If 17: Next 18: End Function 19: 20: 'Test the function and display result returned by the Sum function 21: MsgBox Sum(Array(23, 56, 78, 95, 114)), vbOKOnly, "Result from simple function" 22: 23: 24: 'Now, let us convert this function into an object using the Command Wrapper design pattern:

25: Class Sum 26: Private m_arrVarNumbers 27: Private m_varResult 28: 29: Private Sub Class_Initialize() 30: 'Initialize the Numbers member as an empty array 31: ReDim m_arrVarNumbers(-1) 32: End Sub 33: 34: Public Function Init(ByVal arrVarNumbers) 35: Numbers = arrVarNumbers 36: End Function 37: 38: Public Default Function Exec() 39: Dim ix, arrNumbers 40: 41: 'Check if an array was passed. If so, there's nothing to do – exit function 42: If (Not IsArray(Numbers)) Then 43: 'Add your error handling code here 44: Exec = "Invalid data type was supplied to perform the operation." 45: Exit Function 46: ElseIf (UBound(Numbers) - LBound(Numbers) + 1 <= 1) Then 47: 'Array is empty or has single item - Add your error handling code here 48: Exec = "Not enough data was supplied to perform the operation." 49: Exit Function 50: Else 51: arrNumbers = Numbers 52: End If 53: 54: Result = 0 55: For ix = LBound(arrNumbers) To UBound(arrNumbers) 56: If (IsNumeric(arrNumbers(ix))) Then 57: Result = Result + arrNumbers(ix) 58: Else 59: 'Add your error handling code here 60: End If 61: Next 62: Exec = Result 63: End Function 64: 65: Public Property Get Numbers() 66: Numbers = m_arrVarNumbers 67: End Property 68: 69: Private Property Let Numbers(ByVal arrVarNumbers) 70: m_arrVarNumbers = arrVarNumbers 71: End Property 72: 73: Public Property Get Result() 74: Result = m_varResult 75: End Property 76: 77: Private Property Let Result(ByVal varResult) 78: m_varResult = varResult

79: End Property 80: End Class 81: 82: 'This function behaves as a constructor and returns an initialized instance of the class 83: Public Function GetSum(ByVal arrNumbers) 84: Set GetSum = New Sum 85: GetSum.Init(arrNumbers) 86: End Function 87: 88: 'Test the class 89: Dim objSum, arrNumbers 90: 91: 'Assign an array of numbers 92: arrNumbers = Array(23, 56, 78, 95, 114) 93: 94: 'Get an instance of class Sum and initialize it with numbers array 95: Set objSum = GetSum(arrNumbers) 96: 97: 'Execute Sum (Exec method) 98: objSum.Exec() 99: 100: 'Display result stored in Result property 101: MsgBox objSum.Result, vbOKOnly, "Result from Result Property" 102: 103: 'Alternatively, display the result returned by the Exec method: 104: MsgBox GetSum(Array(23, 56, 78, 95, 114)).Exec, vbOKOnly, "Result from Exec method"

The Scripting Dictionary In VB Script, the scripting dictionary is an object that stores key-item pairs using a hashing algorithm. The items can be accessed using their corresponding keys. Basically, the dictionary is useful to store variant type, non-structured data, such as the catalog number of an item in an inventory list, or the authors of a list of books, and to retrieve the data using the unique keys supplied, as in the following example:
1: Dim dicBooksAuthors 2: 3: 'Create an instance of the scripting dictionary class 4: Set dicBookAuthors = CreateObject("Scripting.Dictionary") 5: 6: With dicBookAuthors 7: 'Add some books (keys) and authors (items) 8: .Add "The Selfish Gene", "Richard Dawkins" 9: .Add "The Mismeasure of Man", "Stephen J. Gould" 10: .Add "The Da Vinci Code", "Dan Brown" 11: 12: 'Answer the question: who wrote "The Selfish Gene"? 13: strBook = "The Selfish Gene" 14: MsgBox .item(strBook), vbOKOnly+vbInformation, "Author query result for book: " & strBook 15: End With

The Addition Operation 1: Class Sum 2: Private m_arrVarNumbers 3: Private m_varResult 4: 5: Private Sub Class_Initialize() 6: 'Initialize the Numbers member as an empty array 7: ReDim m_arrVarNumbers(-1) 8: End Sub 9: 10: Public Function Init(ByVal arrVarNumbers) 11: Numbers = arrVarNumbers 12: End Function 13: 14: Public Default Function Exec() 15: Dim ix. however. we have shown that it is possible to encapsulate any function as a class by using the command wrapper design pattern. Thanks to its capacity to store variant data types. including references to objects. it has been indicated that the VBScript Scripting Dictionary object is equipped with the capacity of storing variant data types. In addition. it eliminates the need for item search functions (direct access) and avoids duplicate key creation. arrNumbers 16: 17: If (Not IsArray(Numbers)) Then 'Not an array. Following the example given above in the Command Wrapper section. Recall that a pointer is a variable that stores the memory address of a function or instantiated class object. In the next chapter.The example above demonstrates the power of a dictionary as a data storage and data retrieval device. the dictionary can be much more than just a data storage and retrieval device. is out of the scope of the current paper). we shall now show how it is possible to build function pointers using a Scripting Dictionary. so nothing to do – exit function 18: 'Add your error handling code here . In what follows a method will be described to combine these two features into a powerful design and programming technique. we shall delve into a method to exploit this feature of the scripting dictionary object to implement function pointers in VBScript. However. Here below. it is actually possible to store references to objects of different types. it is possible to store complex data structures by using nested dictionaries (this issue. For instance. Implementing Function Pointers in VB Script Earlier in this article. For instance. we shall demonstrate the case of the four basic arithmetic operations.

19: 20: 21: 22: 23: 24: 25: 26: 27: 28: 29: 30: 31: 32: 33: 34: 35: 36: 37: 38: 39: 40: 41: 42: 43: 44: 45: 46: 47: 48: 49: 50: 51: 52: 53: 54: 55: 56: 57: 58: 59: 60: 61: Exec = "Invalid data type was supplied to perform the operation." Exit Function ElseIf (UBound(Numbers) ." Exit Function Else arrNumbers = Numbers End If Result = 0 For ix = LBound(arrNumbers) To UBound(arrNumbers) If (IsNumeric(arrNumbers(ix))) Then Result = Result + arrNumbers(ix) Else 'Add your error handling code here End If Next Exec = Result End Function Public Property Get Numbers() Numbers = m_arrVarNumbers End Property Private Property Let Numbers(ByVal arrVarNumbers) m_arrVarNumbers = arrVarNumbers End Property Public Property Get Result() Result = m_varResult End Property Private Property Let Result(ByVal varResult) m_varResult = varResult End Property End Class 'This function behaves as a constructor and returns an initialized instance of the class Public Function GetSum(ByVal arrNumbers) Set GetSum = New Sum GetSum.Add your error handling code here Exec = "Not enough data was supplied to perform the operation.LBound(Numbers) + 1 <= 1) Then 'Array is empty or has single item .Init(arrNumbers) End Function The Subtraction Operation 1: Class Subtract 2: Private m_arrVarNumbers 3: Private m_varResult 4: 5: Private Sub Class_Initialize() 6: 'Initialize the Numbers member as an empty array .

" 24: Exit Function 25: Else 26: arrNumbers = Numbers 27: End If 28: 29: Result = arrNumbers(LBound(arrNumbers)).arrNumbers(LBound(arrNumbers)+1) 30: For ix = LBound(arrNumbers)+2 To UBound(arrNumbers) 31: If (IsNumeric(arrNumbers(ix))) Then 32: Result = Result ." 20: Exit Function 21: ElseIf (UBound(Numbers) .Init(arrNumbers) .LBound(Numbers) + 1 <= 1) Then 22: 'Array is empty or has single item . so nothing to do – exit function 18: 'Add your error handling code here 19: Exec = "Invalid data type was supplied to perform the operation. arrNumbers 16: 17: If (Not IsArray(Numbers)) Then 'Not an array.7: ReDim m_arrVarNumbers(-1) 8: End Sub 9: 10: Public Function Init(ByVal arrVarNumbers) 11: Numbers = arrVarNumbers 12: End Function 13: 14: Public Default Function Exec() 15: Dim ix.Add your error handling code here 23: Exec = "Not enough data was supplied to perform the operation.arrNumbers(ix) 33: Else 34: 'Add your error handling code here 35: End If 36: Next 37: Exec = Result 38: End Function 39: 40: Public Property Get Numbers() 41: Numbers = m_arrVarNumbers 42: End Property 43: 44: Private Property Let Numbers(ByVal arrVarNumbers) 45: m_arrVarNumbers = arrVarNumbers 46: End Property 47: 48: Public Property Get Result() 49: Result = m_varResult 50: End Property 51: 52: Private Property Let Result(ByVal varResult) 53: m_varResult = varResult 54: End Property 55: End Class 56: 57: 'This function behaves as a constructor and returns an initialized instance of the class 58: Public Function GetSubtract(ByVal arrNumbers) 59: Set GetSubtract = New Subtract 60: GetSubtract.

" 24: Exit Function 25: Else 26: arrNumbers = Numbers 27: End If 28: 29: Result = arrNumbers(LBound(arrNumbers)) * arrNumbers(LBound(arrNumbers)+1) 30: For ix = LBound(arrNumbers)+2 To UBound(arrNumbers) 31: If (IsNumeric(arrNumbers(ix))) Then 32: Result = Result * arrNumbers(ix) 33: Else 34: 'Add your error handling code here 35: End If 36: Next 37: Exec = Result 38: End Function 39: 40: Public Property Get Numbers() 41: Numbers = m_arrVarNumbers 42: End Property 43: 44: Private Property Let Numbers(ByVal arrVarNumbers) 45: m_arrVarNumbers = arrVarNumbers 46: End Property 47: 48: Public Property Get Result() .61: End Function The Multiplication Operation 1: Class Multiply 2: Private m_arrVarNumbers 3: Private m_varResult 4: 5: Private Sub Class_Initialize() 6: 'Initialize the Numbers member as an empty array 7: ReDim m_arrVarNumbers(-1) 8: End Sub 9: 10: Public Function Init(ByVal arrVarNumbers) 11: Numbers = arrVarNumbers 12: End Function 13: 14: Public Default Function Exec() 15: Dim ix.Add your error handling code here 23: Exec = "Not enough data was supplied to perform the operation. arrNumbers 16: 17: If (Not IsArray(Numbers)) Then 'Not an array.LBound(Numbers) + 1 <= 1) Then 22: 'Array is empty or has single item . so nothing to do – exit function 18: 'Add your error handling code here 19: Exec = "Invalid data type was supplied to perform the operation." 20: Exit Function 21: ElseIf (UBound(Numbers) .

LBound(Numbers) + 1 <= 1) Then 22: 'Array is empty or has single item .Init(arrNumbers) End Function The Division Operation 1: Class Divide 2: Private m_arrVarNumbers 3: Private m_varResult 4: 5: Private Sub Class_Initialize() 6: 'Initialize the Numbers member as an empty array 7: ReDim m_arrVarNumbers(-1) 8: End Sub 9: 10: Public Function Init(ByVal arrVarNumbers) 11: Numbers = arrVarNumbers 12: End Function 13: 14: Public Default Function Exec() 15: Dim ix. arrNumbers 16: 17: If (Not IsArray(Numbers)) Then 'Not an array." 34: Exit Function 35: End If ." 24: Exit Function 25: Else 26: arrNumbers = Numbers 27: End If 28: 29: If (IsNumeric(arrNumbers(LBound(arrNumbers))) And IsNumeric(arrNumbers(LBound(arrNumbers)+1)) And (arrNumbers(LBound(arrNumbers)+1) <> 0)) Then 30: Result = arrNumbers(LBound(arrNumbers)) / arrNumbers(LBound(arrNumbers)+1) 31: Else 32: 'Add your error handling code here 33: Exec = "Invalid data was supplied to perform the operation.Add your error handling code here 23: Exec = "Not enough data was supplied to perform the operation. so nothing to do – exit function 18: 'Add your error handling code here 19: Exec = "Invalid data type was supplied to perform the operation." 20: Exit Function 21: ElseIf (UBound(Numbers) .49: 50: 51: 52: 53: 54: 55: 56: 57: 58: 59: 60: 61: Result = m_varResult End Property Private Property Let Result(ByVal varResult) m_varResult = varResult End Property End Class 'This function behaves as a constructor and returns an initialized instance of the class Public Function GetMultiply(ByVal arrNumbers) Set GetMultiply = New Multiply GetMultiply.

Add "-".Add "/". New Subtract 10: .Add "+".36: 37: 38: 39: 40: 41: 42: 43: 44: 45: 46: 47: 48: 49: 50: 51: 52: 53: 54: 55: 56: 57: 58: 59: 60: 61: 62: 63: 64: 65: 66: 67: 68: For ix = LBound(arrNumbers)+2 To UBound(arrNumbers) If (IsNumeric(arrNumbers(ix)) And (arrNumbers(ix) <> 0)) Then Result = Result / arrNumbers(ix) Else 'Add your error handling code here End If Next Exec = Result End Function Public Property Get Numbers() Numbers = m_arrVarNumbers End Property Private Property Let Numbers(ByVal arrVarNumbers) m_arrVarNumbers = arrVarNumbers End Property Public Property Get Result() Result = m_varResult End Property Private Property Let Result(ByVal varResult) m_varResult = varResult End Property End Class 'This function behaves as a constructor and returns an initialized instance of the class Public Function GetDivide(ByVal arrNumbers) Set GetDivide = New Divide GetDivide.item("+") . New Divide 12: End With 13: 14: 'Execute the functions using the Function Handler 15: With dicFunctionHandler 16: With .Add "*". New Multiply 11: .Dictionary") 5: 6: 'Load some functions 7: With dicFunctionHandler 8: .Init(arrNumbers) End Function Using the Function Pointers to Perform the basic Arithmetic Operations 1: Dim dicFunctionHandler 2: 3: 'Create an instance of the scripting dictionary class 4: Set dicFunctionHandler = CreateObject("Scripting. New Sum 9: .

Implement a function handler using a scripting dictionary.Init(Array(117. execute the functions using the Function Handler 45: With dicFunctionHandler 46: MsgBox .Init(Array(23. 56. Instantiate such custom classes and load them to a scripting dictionary. vbOKOnly+vbInformation.RemoveAll 38: .item("/") 29: Call .Exec(). Implement a “constructor” for a class in VBScript.Exec().item("/"). 2. 12)) 30: MsgBox . "Result (-)" 'Display result returned by the Exec method 23: End With 24: With .item("*"). 114)) 18: MsgBox . vbOKOnly+vbInformation. "Result (+)" 'Display result returned by the Exec method 19: End With 20: With .item("+"). GetSum(Array(23. GetMultiply(Array(7. . 5)) 41: . "Result (-)" 'Display result returned by the Exec method 48: MsgBox . vbOKOnly+vbInformation.Exec(). 95. 12)) 42: End With 43: 44: 'Second.Add "*".Init(Array(84.Exec(). Call the loaded function via the dictionary key and retrieve the result. vbOKOnly+vbInformation. "Result (/)" 'Display result returned by the Exec method 50: End With In the above example we have shown how to: 1. 114)) 39: . 95. vbOKOnly+vbInformation.Add "+". load some functions 36: With dicFunctionHandler 37: .17: Call . "Result (*)" 'Display result returned by the Exec method 49: MsgBox .item("-").item("*") 25: Call . "Result (/)" 'Display result returned by the Exec method 31: End With 32: End With 33: 34: 'Or. 23)) 22: MsgBox . 23)) 40: . 5.item("-") 21: Call .Exec().Init(Array(7. using the "constructors": 35: 'First. 4. 56.Exec(). 3. "Result (*)" 'Display result returned by the Exec method 27: End With 28: With . GetSubtract(Array(117. 5)) 26: MsgBox .Exec(). 78. vbOKOnly+vbInformation. "Result (+)" 'Display result returned by the Exec method 47: MsgBox .Exec(). 78.Add "-". Implement the Command Wrapper design pattern in VBScript.Add "/". vbOKOnly+vbInformation. GetDivide(Array(84. vbOKOnly+vbInformation.

1219 Discussion We have seen so far how to implement the Command Wrapper design pattern in VBScript and a “constructor” for a class in VBScript. dicFunctionHandler(“/”).1561 10 0. vbOKOnly+vbInformation. vbOKOnly+vbInformation. Number of Calls Single Regular calls 0. In a similar fashion.Exec(). vbOKOnly+vbInformation.Exec(). as follows: 1: 2: 3: 4: 5: 'Execute the functions using the Function Handler MsgBox MsgBox MsgBox MsgBox dicFunctionHandler(“+”).5806 2. dicFunctionHandler(“/”).This is the method suggested in this paper to implement a function pointer in VBScript.0635 0. dicFunctionHandler(“-”). dicFunctionHandler(“-”). vbOKOnly+vbInformation.5630 0.Exec().5308 20 1. vbOKOnly+vbInformation. We have also shown how to instantiate such custom classes and load them to a scripting dictionary. "Result "Result "Result "Result (+)" (-)" (*)" (/)" The readers are encouraged to try to execute the sample code shown in this paper. as well as to try the method to implement their own functionality.0943 Function Pointers 0.0674 4.0922 100 5. as well as a function handler using a scripting dictionary. vbOKOnly+vbInformation. There is also another possible way to call a function implemented with this method. dicFunctionHandler(“*”). dicFunctionHandler(“*”).9212 50 2. the more worthwhile it is to use function pointers. together with different ways to call the loaded . vbOKOnly+vbInformation.Exec(). "Result "Result "Result "Result (+)" (-)" (*)" (/)" and this is because the item property is the scripting dictionary‟s default property. vbOKOnly+vbInformation. it is possible to define the Exec methods of the above mentioned classes as Default (by declaring it: Public Default Function) and then the code above can be further reduced to: 1: 2: 3: 4: 5: 6: 'Execute the functions using the Function Handler MsgBox MsgBox MsgBox MsgBox dicFunctionHandler(“+”). Performance of Function Pointers A small case study comparing the performance of regular function calls with that of function pointers shows that the more a function is used.

. to define the flow of the different code blocks in an external file. Third. 2005). (2005). With such a component it would be possible. This can be easily done by passing the function handler entry (dictionary item) to another function. which is a central feature of function pointers. when the system is low in RAM.e.. by means of dynamic loading of code blocks. the method can be used to emulate callbacks. it would be possible to build a generic controller component that would enable execution of real keyword-driven scripts. and hence they will not be covered here. In what remains I shall attempt to convey in which cases the implementation of this design pattern in VBScript in general. Future forthcoming articles will further expand on several topics mentioned throughout this paper. It is concluded that the technique can help developers to achieve more efficient and generic design and code. for it makes the need for decision structures to analyze the return code of a function obsolete. Conclusion This paper attempted to demonstrate how to implement function pointers in VBScript. We have also indicated that this method is. i.function via the dictionary key and to retrieve the result. Source: http://www. Callbacks and Functors. Fourth.g.newty. in fact. such as an XML file. References Haendel. Lars Haendel.de/fpt/zip/e_fpt.pdf . by implementing a function handler as illustrated above. First. An example for this can be found in Appendix 2. and pinpointed the possible uses and advantages of the method in general and particularly for QTP. L. the method presented in this paper should be of great value when the basic hardware configuration is poor. This can be achieved by returning a string with the name of the function to be called. for example. Second. the method can be used to emulate event handling. Introduction to C and C++ Function Pointers. and with Quicktest Pro (QTP) in particular. and better run-time resources management. The general uses and benefits of function pointers are explained elsewhere (e. The Function Pointer Tutorials. Recall that common QTP usage requires the automation developer to add every single function library to the test resources. might be of benefit. equivalent to the implementation of a function pointer in C or C++. Please notice that this technique would yield a highly parsimonious coding style.

In addition. two additional functions (AbortTest and Cleanup) are included for error handling and orderly exiting the test flow. J. Appendix 1: Event Handling Example We shall show here how to implement an event handler in VBScript for a typical login flow in QTP. "Login" 7: Exec = "AbortTest" 8: Else 9: MsgBox Join(arrArgs. vbOKOnly+vbInformation. in case of error the Login. "AbortTest" 25: Exec = "Cleanup" 26: 'Add your code here 27: End Function 28: End Class 29: 30: Class FirstTest .. Design Patterns: Elements of Reusable Object Oriented Software. E. with their corresponding arguments from arrActionArgs. ". FirstTest and Logout. 1: Class Login 2: Public Default Function Exec(ByVal arrArgs) 3: 'Add your code here 4: If (Not IsArray(arrArgs)) Then 5: MsgBox "Error: username & password are mandatory parameters. R.Exec function returns the name of the action to be performed (AbortTest). R. _ 6: vbOKOnly+vbCritical. & Vlissides. "Logout" 18: 'Add your code here 19: End Function 20: End Class 21: 22: Class AbortTest 23: Public Default Function Exec(ByVal arrArgs) 24: MsgBox "Exec". vbOKOnly+vbCritical.Gamma. the normal course of the test flow is altered such that the FirstTest action is never executed. Helm. vbOKOnly+vbInformation.".."). "Login" 10: Exec = "" 11: End If 12: End Function 13: End Class 14: 15: Class Logout 16: Public Default Function Exec(ByVal arrArgs) 17: MsgBox "Exec". Johnson. As can be seen in the code. Addison-Wesley Publishing. Within the TestFlow Sub.. This action is then performed by means of the statement: strNextAction = dicFunctionHandler(strNextAction)(arrArgs). (1997). the functions are loaded using a generic function (class) loader function (GetFunction). The flow includes three functions: Login. and since the for loop continues to advance. and then called according to their order in the arrRunActions.

ix. "Logout"). ByVal arrActionArgs) Dim dicFunctionHandler.LBound(arrArgs) + 1 = 0) Then 'If no args are found. arrArgs. "FirstTest".Dictionary") 'Load the required functions With dicFunctionHandler For ix = LBound(arrLoadActions) To UBound(arrLoadActions) . "FirstTest" 'Add your code here End Function End Class Class Cleanup Public Default Function Exec(ByVal arrArgs) MsgBox "Exec". pass an empty string arrArgs = "" End If 'If the next command is empty If (strNextAction = "") Then 'Run the next planned action strNextAction = dicFunctionHandler(arrRunActions(ix))(arrArgs) Else 'Run the action returned by the previously call action strNextAction = dicFunctionHandler(strNextAction)(arrArgs) End If Next End Sub Call TestFlow(Array("Login".Add arrLoadActions (ix). GetFunction(arrLoadActions (ix)) Next End With 'Run the required flow strNextAction = "" For ix = LBound(arrRunActions) To UBound(arrRunActions) 'Get the action arguments arrArgs = split(arrActionArgs(ix). "Cleanup"). "FirstTest". "AbortTest". "")) .31: 32: 33: 34: 35: 36: 37: 38: 39: 40: 41: 42: 43: 44: 45: 46: 47: 48: 49: 50: 51: 52: 53: 54: 55: 56: 57: 58: 59: 60: 61: 62: 63: 64: 65: 66: 67: 68: 69: 70: 71: 72: 73: 74: 75: 76: 77: 78: 79: 80: 81: 82: 83: 84: Public Default Function Exec(ByVal arrArgs) MsgBox "Exec". strNextAction Set dicFunctionHandler = CreateObject("Scripting. vbOKOnly+vbInformation. "". "Cleanup" 'Add your code here End Function End Class 'This generic function will load any class Public Function GetFunction(ByVal strFunctionName) Execute "Set GetFunction = New " & strFunctionName End Function 'This sub will run the flow Public Sub TestFlow(ByVal arrLoadActions.123456".") If (UBound(arrArgs) . Array("User. _ Array("Login". vbOKOnly+vbInformation. ". "Logout".Dictionary") Set arrArgs = CreateObject("Scripting. ByVal arrRunActions.

). the syntax looks complicated.Click X Y. while not having any testing value by themselves. and it is very . and after many attempts to solve the problem elegantly. RO Vs THE QTP SHELL Update: this is an article from the old site that wasn‟t transferred to the new one. I side with the latter opinion. I think this opinion is quite easy to understand. that calls for serious discussion. messing with the application‟s RO objects has no testing value (not emulating user behavior. by dynamically loading the functions without the function handler (as shown earlier in this article): 5: 'Execute the (*) function on the result of the (+) function to calculate the tax on an item 6: MsgBox GetMultiply(Array(GetSum(Array(23.g. that could otherwise fail our script. slow system behavior etc. The example used here will be the calculation of the total amount plus the tax on the sum of several items prices. Thus. the question whether it is “Kosher” to change the run-time properties of the AUT (application under test) was given new life in SQAForums (e.Appendix 2: Implementing a Callback with Function Pointers We shall show here how to implement a callback with the classes defined in Appendix 1 and used in this paper. 78. this sucks. and I think an example will illustrate why: Say our application has some input fields. 1: 'Define a constant with the tax value multiplier 2: Const CONST_DBL_VAT = 1. for two main reasons (beside being an ugly solution): It tends to break (Click events are often block by focus shifting. On the one hand. 114)). these task could safely get us to a position where we could do some real testing. CONST_DBL_VAT)). here). It‟s a tough question. _ 7: vbOKOnly. On the other hand. it becomes obvious that the only method that will work is TabControl. setting RO properties can give us a robust way of doing certian tasks. So here it is: In past few days. QTP doesn‟t recognize this tab-control. backstage behavior should be tested via unit-tests). when done carefully and selectively. divided among various tabs. residing within a tab-control. 56. and could miss UI bugs a user would have encountered. "Result (Tax)" 8: True. 95.155 3: 4: 'Now. but it is very useful. Now. it could cause serious bugs.

this is unacceptable. And this seems like a pretty good balance to me. It suddenly seems very tempting to just set the RO property whenever we want to switch tabs. and the script breaks). and answer a reasonable NO (since any bugs will cause the next step of the script to fail). resolutions etc. We can run through the tab collection. we gained: A. VERY small possibility for creating new tab-switching bugs due to messing around with the RO objects. we become confident that no new bugs will be caused by this. so we try thinking outside the box. but we shouldn‟t abandon it all together. So. Just to be clear – I agree we do need to be selective and careful about applying this methond (e. good-old-fashion QTP style. . we learn that the process works the other way as well – changing the property via QTP. B. find the tab with the relevant name (By looping the TabControl. A much more robust script (no . we can then decide that tab navigation will be done via RO manipulation. It doesn‟t test the tab control. and find out that when the user switches the active-tab. We ask the programmers. do a littlie investigating. A generic script (serves multiple systems with various fonts. and after a while.VERY demanding from a maintenance point of view (just change the tab-order. NEVER on a data-grid control).) C. makes the control bring the relevant tab to the front.Object. VERY small possibility for missing tab-switching UI bugs due to not actually pressing the tab control. and switch. After a little creative fiddling. Here comes the “carefully and selectively” part (which is REALLY important): we make damn sure that setting the object‟s RO property doesn‟t break anything. run a few tests of ourselves. Zero-maintenance growth and change (handles “out of the box” New tabs. where we could rip the application apart. different tab layout) We paid for it with: A. to sum-up. different tab ordering. the tab control‟s inner object change its ActiveTab property to the new tab‟s index. get its index. OK. change the resolution or the font.Tabs collection).Click breaking the script) B.g. So. we ask ourselves if we could miss UI bugs due to working backstage. but it makes sure we‟ll get to the right tab. At the end of the day. add a new tab. Moreover.

which is a set of attributes and values that serve as criteria to . A test object stores the description of the referenced object. Subsequently. I will describe an expansion of the OR concept that is compatible with OO principles – the GUI Layer. This concept has been adopted by SOLMAR‟s automation experts based on the observation that it is possible to maximize code reusability (and thus boosting maintainability) by undertaking an OO approach that breaks an automation project into several abstraction levels. then what is the optimal way to implement it?” are quite ubiquitous and the answers given can vary depending on the particular characteristics of the project. Questions such as: “Should we use an Object Repository (OR) or Descriptive Programming (DP)? if an OR is chosen. QTP descriptive programming (DP) and the Dictionary object to pack together GUI objects with their corresponding business oriented functions. preventing QTP from getting stuck when it fails to identify GUI objects during runtime. I shall attempt to show that QTP‟s Object Repository does not fit well with such principles and what is the impact of this on automation development viz-a-viz costeffectiveness and maintainability. In this article I will analyze the concept of Test Objects in the context of Object Oriented principles. Introduction A central issue in automation development is how to reduce the effort spent on maintenance.You can read more about RO manipulating techniques in our article about automating custom controls. The article includes a valuable bonus: a highly effective tip that enables to exit a test smoothly. Implementing a GUI Layer with Classes Abstract This article describes a powerful technique that exploits Object Oriented Design Patterns. Test Objects and Run-Time Objects A test object encapsulates a reference to a run-time object – the real world object that is instantiated in the application under test (AUT). then should we use a shared OR or a local OR for each Action? If DP is selected. but many times also on the individual personalities involved.

reflects a best practice according to which we ought to store the description of each GUI (Test) Object only once to reduce . you‟ve been told on the phone). but at the end of the day we need to perform actions on Runtime objects. QTP is able to identify a GUI object among all the objects currently loaded to the machine‟s RAM. This description is pretty much like the one we keep in mind to identify our blind date partner at the meeting time (“I‟m brunette. then. slim and tall. Test Complete. the OS returns the address of the object (a reference or pointer) and hence QTP gains access to the object‟s public methods and properties. seems to be the problem with the OR approach? Tests Objects are really data entities. and will be wearing a red dress and shoes”. I will explain below why. The difference is that in this case.). not the DB. If the answer is positive. AutoIt. if you noticed the bdb suffixed files in QTP tests. Though this description may seem overly simplified. Test Objects and the Object Repository The above account of test objects makes it seem only natural to think of them as data entities. What do I mean by this? Based on a description composed of a set of properties and values. QTP uses such a description to query the OS if there‟s an object currently loaded to the machine‟s RAM. It is true that the OR. Moreover. This is similar to the retrieval of a particular record from a database table based on a SQL WHERE clause. if lucky!). since the private methods and properties are hidden from view by definition (so QTP never makes progress to the private domain. it is the OS (Windows). then note that bdb actually stands for Berkeley Data Base – an Oracle product). Similarly. basically it is this process that enables us to interact with the GUI (and other) objects using QTP or other automation tools (Test Partner. as you would with the brunette. which essentially is exactly what the Object Repository is (a side note. it seems only natural to have these entities – Test Objects – stored in a database. this record contains a single field that stores a reference to the actual runtime object.locate the right object during the test run session. the one that returns the record. if used properly. Following this line of thought. A more detailed account of the distinction between Test Objects and Run-Time Objects is available in Yaron Assa‟s article “Differences and Connections between Runtime Objects and Test Objects” (2009). Rational Robot. What. insomuch that the above account leaves us with an incomplete picture. etc.

suppose that two automation developers work simultaneously with a shared repository. more often than not. classes mostly are representations of .maintenance costs. as well as the input data and expected results data. For instance. However. but one is maintaining the scripts for the last version and the other is developing new scripts for the newest one. as aforesaid. Of course. keeping versions of the OR leaves one issue still open. regressive by nature. it will not be too long until the OR becomes cluttered with new. The worst case would be one where each developer would change in turn the descriptions of existing objects to match their requirements. And this is a relatively good result. in general. not developed. because ad-hoc requests and resource limitations can endanger the integrity of such a precious resource. The Object Oriented View The Object Oriented software paradigm is based on the basic concepts of encapsulation. Encapsulation basically means to pack together functionality and data structures that belong together. for example. and the package through which we achieve this is called a class. test objects required by the developer working on the newest version. But. However. changes in the AUT would require matching changes in both the OR and the scripts that refer to its test objects. such as keeping separate versions of the OR that match each AUT version and using configuration management software in the automation project. damaging irrevocably the ROI on the automation project as a whole. which are many times also accompanied by even deeper changes – in the database structure. If the common situation would have been that only the object descriptions changed from one AUT version to the next. In fact. Moreover. then maintenance would certainly pertain not only to the OR but also that the code that implements the actual GUI manipulations and verifications. Given that GUI changes are made quite regularly from one AUT version to the next. GUI changes reflect modifications in the way the AUT actually functions. Taking into account the fact that scripts are most of the time maintained. then using an OR would be an excellent solution. So. as well as in the data sources that feed these scripts. this requires good project management. in order to achieve this a great effort must be invested also into managing the automation project properly. the aforementioned line of analysis lead me to the conclusion that something in the OR concept is faulty regarding the manageability of a large-scale automation project. which is not always available. redundant. inheritanceand polymorphism. there are solutions to such situations. Because automated tests are.

int) and so instead of having a single function with conditional statements that check for the value type that was passed. we‟ll have several functions with the same name but different signatures (different type of arguments). the class fields and methods). The difference between a fully featured class and a mere data structure (as in the C programming language) is that the class also wraps the functions available for use with the class data fields. which assign and retrieve the value of the respective field. readable.e. maintainable. They enable the code developer to determine which fields (also called properties or attributes of the class) and methods will be actually accessible to the world outside the class (public). However in QTP these two last concepts of inheritance and polymorphism cannot be implemented based on the VB Script language which provides very rudimentary support for working with classes. we would use the same interface in both cases. scalable. For example. and which will remain for internal (private) use of the class members (i. For instance. also more . etc. yes. we shall see later that this is not a reason to refrain from using classes in testing automation. firstName. In OO programming languages like C++ and Java. The public and private notions mentioned above are of great importance with regard to encapsulation and inheritance. reusability comes into play by means of the ability to device a new class that “inherits” the fields and methods of a previously defined class (also called a base class) and expands on these according to the specific requirements that raised the need for the new class. we might need to handle numbers of different types (float. The OO methodology is not new and has been widely put into practice in the software design and development industry. getCustomerId. Nevertheless. lastName. extensible and.. with the correct process ultimately invoked by the runtime environment.data entities (like Customer. a typical class for a Customer would pack the data fields that define the customer as a data entity (customerId. Polymorphism is yet another powerful concept that enables one to design more than one version of a function (with the same name but different number or types of arguments) to be able to handle transparently different situations within the application context. phoneNo. etc. Product. Inheritance is deeply related to one of the major goals of the OO approach – reusability. as well as others like getCustomerAge and getCustomerBalance which would perform a calculation based on the class fields current values and then return the result. These are commonly referred to as the classmethods.).) together with functions such assetCustomerId. Hence in our code that uses these functions we would not need to use casting. It is recognized as one approach that makes the resulting code more reusable.

self-contained capsules or packages). computer programs that perform operations instead of humans implement automation. Some of the main challenges are the following: 1. Sometimes this is even reflected by the job title given to the automation staff: “automatic tester” is one of the absurd titles I have encountered several years ago. Scripts that carry out operations on GUI objects – such as QTP tests – are not different than any other piece of software. then an automation project should be treated and managed as any other development project and. as I shall explain in what follows. the automation developer must have an overall view of the AUT. Generally speaking.testable (as huge pieces of functionality are broken down into smaller. How this relates to the way we approach. an automation project also has its own SRS (Software Requirements Specifications) document: the STD (Software Test Design) “document” (or tests design in a quality management tool such as HP‟s Quality Center or Orcanos‟ QPack). Put it in other words. As with any software product. which should guide the automation developer in the implementation of the required code. the testing automation challenge? Let us delve into it below. even more so. If so. it is not rare to find automation professionals that think likewise since many times the role of automation. making good use of the methodology requires deep analytical skills that enable the code designer to infer correctly from the requirements of the software under construction which are the appropriate entities involved and how they are interrelated. a specific kind of software development project. Not surprisingly. this belief is a true misconception of the essence of testing automation. indeed. This reflects a misunderstanding of the role of the Automation Developer and. or robot. This is because the automation developer faces challenges that are usually not felt by the developers of the AUT. So basically any block of code is a kind of automation device. First. Members of the AUT‟s development team do . Of course. Testing Automation and Software Development One thing I have witnessed throughout my career is that QA professionals of all levels treat testing automation as just another testing activity. or should approach. The task of automating tests should not be treated differently than any other content specific automation task. a testing automation project is. as the automation scripts may cover a large part of the AUT‟s main functionality. in fact.

I will illustrate below how such a layer can be built. But. especially the GUI Layer concept. 2. of which we shall have more to say later. where the opposite is true? Why not. the GUI controls used by the development team. approach to do it using the most widely accepted development method – Object Oriented – to attain the best possible results? In what follows I will describe a method to implement automation “scripts” based on an extension to the OR concept – the GUI Layer.not necessarily need this. automation developers find out that the test design leaves many open issues that need to be resolved beforehand. it is a set of classes that bridge between the AUT‟s GUI (i. as is the case with third-party and custom controls. and what are the benefits gained from adopting such an approach to testing automation. let us take a look at the concept of developing code in layers. In general. If this is so. Second. the automation scripts should be mapped to the test design. Implementing the GUI Layer . following the above discussion. but it is already accustomed among the experts to call it a GUI Layer. and also the AUT‟s behavior may pose a real technological challenge regarding the identification of the objects by QTP (or other tools). So a developer can focus on the part assigned to him and do it well even without having in depth knowledge of the whole system. Many times solutions that extend the basic capacities of the tools are required.e. may be it would be more appropriate to call it the GUI-Business Bridge Layer. Third. The Concept of Layers I hope to have managed so far to make clear why the OR approach. quite often. as the automation scripts do not possess the flexibility and ingenuity of a human tester during runtime. then. as they should emulate the steps done by a human tester. I think we may conclude that an automation project should be definitely managed as a development project. layers are useful to maximize reusability (recall the previous discussion on OO principles). is far from being the optimal approach. with scripts spread all around the place. In a sense. I shall define a GUI Layer as a set of classes that pack (encapsulate) together the interfaces required to manipulate the AUT‟s GUI objects in each application context. the test objects proper) and the Business or Application Layer. as the division of labor among the different teams is typically coordinated by the team leaders and a project manager. 3.. In other words. Now. why should one fall again and again victim to the fallacy of treating an automation project as a trivial task (does “record-replay” remind you of something?). to keep it short. which is based on solid OO principles. Following the above exposition.

.Encapsulating Test Objects in Classes Let us take a testing automation project on a typical AUT and see how the solution should be designed according to the approach outlined above. which are containers of other GUI objects. Because QTP does not allow for direct instantiation of classes defined in external vbs files with the operator New. as aforesaid. as follows: '------------------------------------------------------------------------------Public Function CreateLogin() '------------------------------------------------------------------------------'Function: CreateLogin 'Creates an instance of the Login class ' 'Remarks: ' 'Arguments: ' N/A ' 'Returns: ' Object . it is also required to define the following function that will return an instance of a GUI layer class (a kind of constructor function). For each of these entities. dialogs. we shall make use of the Scripting. obviously.As Login ' 'Owner: ' John Doe ' 'Date: ' dd-MMM-yyyy ' '------------------------------------------------------------------------------Dim objLogin Set objLogin = New Login Set CreateLogin = objLogin '------------------------------------------------------------------------------End Function '------------------------------------------------------------------------------- The second step is. . since each class is. for example: Class Login End Class Class MainWindow End Class Class CreateCustomer End Class and so on for each of the application contexts. and popup messages. The first step would be to make a simple list of all application GUI contexts – i. a container of other GUI objects. Now.e. the windows (pages in a Web application).Dictionary to store the references to the test objects contained in the window. to define the members of each class. we define a class.

Dictionary End Class and so on for each of the application contexts (ht stands for HashTable. (the Dictionary object has been already extensively discussed in other articles published at AdvancedQTP„s knowledge base). So.Dictionary End Class Class MainWindow Private m_htChildObjects 'As Scripting. and I will define it as m_htChildObjects. the first member I shall introduce here will be common to all GUI Layer classes. For this purpose. for example: Class Login Private m_htChildObjects 'As Scripting. as follows: '------------------------------------------------------------------------------- . I will define a public method within the class called Init.dialog or page. which is what the dictionary really is). This property is defined as follows: '------------------------------------------------------------------------------'Property: ChildObjects 'Get and Set the m_htChildObjects member field ' 'Remarks: ' R/W ' 'Arguments: ' dic ' 'Returns: ' m_htChildObjects As HashTable ' 'Owner: ' John Doe ' 'Date: ' dd-MMM-yyyy ' '------------------------------------------------------------------------------Public Property Get ChildObjects() '------------------------------------------------------------------------------Set ChildObjects = m_htChildObjects '------------------------------------------------------------------------------End Property '------------------------------------------------------------------------------'------------------------------------------------------------------------------Public Property Let ChildObjects(ByRef dic) '------------------------------------------------------------------------------Set m_htChildObjects = dic '------------------------------------------------------------------------------End Property '------------------------------------------------------------------------------- The third step is to define the objects contained within each context. The private member m_htChildObjects will be accessed through the class property ChildObjects.

WebEdit("html id:=Password") . ChildObjects("Browser").WebButton("outertext:=Submit") End With 'IsContextLoaded is a function that iterates through the Dictionary and checks if the GUI objects "exist" Init = IsContextLoaded(ChildObjects) '------------------------------------------------------------------------------End Function '------------------------------------------------------------------------------- The code snippet above shows a typical Init method for a GUI Layer class for a Web application Login page.Dictionary") With ChildObjects .Add "Browser". as follows: .WebEdit("html id:=Username") . The test objects are added as entries to the ChildObjects Dictionary. ChildObjects("Page"). Browser("name:=My App") . and their identity is defined using Descriptive Programming (DP). It is thanks to this encapsulation method that we ensure that GUI objects are always defined at a single place.Login") . At the end of the function body you will notice that it returns the result of a call to the function IsContextLoaded which accepts as argument the Dictionary that stores the ChildObjects. ChildObjects("Page"). The reader can easily infer the analogy to the OR.Add "Page". ChildObjects("Page").Public Function Init() '------------------------------------------------------------------------------'Function: Init 'Initializes the context and child objects ' 'Dependencies: ' IsContextLoaded(htContext) ' 'Remarks: ' N/A ' 'Arguments: ' N/A ' 'Returns: ' True/False ' 'Owner: ' John Doe ' 'Date: ' dd-MMM-yyyy ' '------------------------------------------------------------------------------ChildObjects = CreateObject("Scripting.Page("title:=My App \.Add "Password".Add "Submit".Add "Username". IsContextLoaded is defined in a separate common library.

Count-1 IsContextLoaded = IsContextLoaded And items(ix).Exist(0) strDetails = strDetails & vbNewLine & "Object #" & ix+1 & ": '" & keys(ix) & "' was" If IsContextLoaded Then intStatus = micPass strDetails = strDetails & "" strAdditionalRemarks = "" Else intStatus = micWarning strDetails = strDetails & " not" strAdditionalRemarks = " Please check the object properties. ' 'Remarks: ' N/A ' 'Arguments: ' ByRef htContext ." End If strDetails = strDetails & " found. SOLMAR Knowledge Networks Ltd. or False if at least one object is not found.ReportEvent intStatus." & strAdditionalRemarks Next '--------------------------------------------------------------------------Reporter. "IsContextLoaded".As HashTable ' 'Returns: ' True/False ' 'Owner: ' Meir Bar-Tal.'------------------------------------------------------------------------------Public Function IsContextLoaded(ByRef htContext) '------------------------------------------------------------------------------'Function: IsContextLoaded 'Checks that the current GUI context is loaded ' 'Iterates through the htContext (HashTable) items and executes the Exist method with 0 (zero) as parameter. strDetails '------------------------------------------------------------------------------End Function '------------------------------------------------------------------------------- And it returns True if all objects defined in the Dictionary are identified.Items keys = htContext. keys. items. strAdditionalRemarks '--------------------------------------------------------------------------items = htContext. ' 'Date: ' 11-Nov-2008 ' 'See Also: ' '------------------------------------------------------------------------------Dim ix.Keys For ix = 0 To htContext. strDetails. This function is generic and it is used in the projects I .

This is easily done by implementing class methods. making maintenance much easier. Another benefit of this method is that it points exactly to the object we need to recheck and update.Set GlobalDictionary("Username") '------------------------------------------------------------------------------End Function '------------------------------------------------------------------------------'------------------------------------------------------------------------------Public Function SetPassword() '------------------------------------------------------------------------------'Function: SetPassword 'Set the Password field ' 'Dependencies: ' N/A ' 'Remarks: .manage to ensure that QTP does not get stuck while attempting to perform some operation on a non-existing GUI object. Encapsulating Business Methods in Classes The next step after defining the child objects of the GUI context is to define the operations required to perform the application or business scenarios within the given context. These are shown below: '------------------------------------------------------------------------------Public Function SetUsername() '------------------------------------------------------------------------------'Function: SetUsername 'Set the Username field ' 'Dependencies: ' N/A ' 'Remarks: ' N/A ' 'Arguments: ' N/A ' 'Returns: ' N/A ' 'Owner: ' John Doe ' 'Date: ' dd-MMM-yyyy ' '------------------------------------------------------------------------------ChildObjects("Username"). For example. SetPassword and Submit. the login class outlined above would need the following methods to begin with: SetUsername.

. and the use of the ChildObjects property to retrieve through the test object a reference to the runtime object.Set GlobalDictionary("Password") '------------------------------------------------------------------------------End Function '------------------------------------------------------------------------------'------------------------------------------------------------------------------Public Function Submit() '------------------------------------------------------------------------------'Function: Submit 'Presses the Submit button ' 'Dependencies: ' N/A ' 'Remarks: ' N/A ' 'Arguments: ' N/A ' 'Returns: ' N/A ' 'Owner: ' John Doe ' 'Date: ' dd-MMM-yyyy ' '------------------------------------------------------------------------------ChildObjects("Submit").' N/A ' 'Arguments: ' N/A ' 'Returns: ' N/A ' 'Owner: ' John Doe ' 'Date: ' dd-MMM-yyyy ' '------------------------------------------------------------------------------ChildObjects("Password").Click 'TODO: Verify data submission performed successfully '------------------------------------------------------------------------------End Function '------------------------------------------------------------------------------- Notice the use of the GlobalDictionary to retrieve the values required by the functions.

SetUsername() objLogin.Init() Then objLogin. objLogin Set objLogin = CreateLogin() If objLogin. and is not cluttered with the references to both the OR test objects and data sources as quite often is the case. If changes are made to the GUI objects of a given context.Submit() 'If login succeeds intStatus = micPass Else intStatus = micFail End If do_login = intStatus '------------------------------------------------------------------------------End Function '------------------------------------------------------------------------------- Notice the use the Login class outlined above and of its Init function as a precaution to ensure the GUI context is loaded.The next step would be to move on to the Business Layer. and not get stuck. For instance to perform the Login function based on the above example. ' 'Remarks: ' 'Arguments: ' None ' 'Returns: ' Status ' 'Owner: ' John Doe ' 'Date: ' dd-MMM-yyyy ' '------------------------------------------------------------------------------Dim intStatus. then the changes will be concentrated within a single package.SetPassword() objLogin. we could wrap it with the following function: '------------------------------------------------------------------------------Public Function do_login() '------------------------------------------------------------------------------'Function: do_login 'Implements the business logic of the do_login Action. as mentioned above. which implements an application scenario building on the strong foundations of the GUI Layer. both with respect to the object properties and . As you can also see. the code within the function above is easy to understand.

' 'Remarks: ' 'Owner: ' John Doe ' 'Date: ' dd-MMM-yyyy ' '------------------------------------------------------------------------------'------------------------------------------------------------------------------'Methods '------------------------------------------------------------------------------'------------------------------------------------------------------------------Public Default Function Run() '------------------------------------------------------------------------------'Function: Run 'Implements the business logic of the do_login Action. and thus enhancing the manageability of the automation project. as outlined in my article Function Pointers in VB Script (revised). By implementing code this way we achieve a high degree of homogeneity in the code written by different developers. For example: 'VB Script Document Option Explicit '------------------------------------------------------------------------------Class do_login '------------------------------------------------------------------------------'Class: do_login 'Encapsulates the do_login Action. An advanced alternative to the last example is to pack such a Business Layer function using the Command Wrapper Design Pattern. ' 'Remarks: ' 'Arguments: ' None ' 'Returns: ' Status ' 'Owner: ' John Doe ' 'Date: ' dd-MMM-yyyy ' '------------------------------------------------------------------------------Dim intStatus Set objLogin = CreateLogin() . Yet another gain from this method is standardization.to the functionality required to manipulate the context‟s child objects.

SetPassword() objLogin. Future articles will expand on this theme and guide the readers into how to gain from the implementation of other design patterns within the framework laid out in this article.Submit() 'If login succeeds intStatus = micPass Else intStatus = micFail End If Run = intStatus '------------------------------------------------------------------------------End Function '------------------------------------------------------------------------------'------------------------------------------------------------------------------End Class '------------------------------------------------------------------------------- Adopting this method would enable the implementation of an advanced generic controller that loads its flow from an external data source such as an XML file. and explained in detail the benefits of adopting this approach to obtain the maximum ROI from an automation project regarding maintainability. extensibility and testability. scalability. Summary This article has reviewed an alternative approach to code implementation in a testing automation project that is based on object-oriented principles.Init() Then objLogin.SetUsername() objLogin. The article has provided a practical example of how to implement such a layer and how to invoke it using a Business Layer.If objLogin. Such a controller device was developed by me together with my partners at SOLMAR Knowledge Networks as part of our generic Object Oriented comprehensive automation framework – My System. I tried to convey that logically following this line of thought leads to the conclusion that an automation project must be approached as a software development project par excellence. and suggested an expansion to the OR concept – which was shown as inadequate viz-a-viz the OO paradigm – to encapsulate the interfaces to the GUI objects: the GUI Layer. . readability. I have shown that automation scripting should not be treated differently than software development. Moreover.

and explain all the nitpicking involved in all the commands and practices relevant to the matter. Test Objects refer to your everyday QTP entities. This article will guide you through the general concepts. For example. which represent real-world application objects “out there” (i.Differences and Connections between Runtime Objects and Test Objects There is a lot of confusion about how the concepts of Runtime Objects andTest Objects are used in QTP. The general idea is usually clear enough. a SwfComboBox Test Object has the property “all items”. but are only derived from it. it is derived from it. QTP creates a corresponding Test Object and stores it in the Object Repository. Window. We can easily see these methods and properties via the object spy‟s Test Object tab.. VBCheckbox. height. WebTable. .e. Whenever we record a real-world object (also known as a Runtime object). we tell QTP to look for a runtime window object with text = “Notepad”. but when it comes down to the actual details. sometimes even the experts do not quite know if using the GetROProperty method on a TO will work. The QTP Test Object Shell Under their fancy name. the most immediate one is object identification. on top of these. Browser – these are all QTP constructed test objects. in our application under test). So for example. It is important to understand that the test object‟s properties and methods are not really “out there” in the application‟s runtime object. Click. By using a window test object with a text property of “Notepad”. it also contains methods to operate it: Close. Maximize. so even though the property does not exist in the runtime object. nativeclass. etc. The Test Object contains QTP specific properties and methods which allow us both to identify the relevant runtime object during playback. as well as to perform standard operations on it and with it. Test Objects roles Test objects play several roles in QTP. a Window test object contains properties which allow QTP to identify it in the “real world”: text.. while the actual . QTP builds the “all items” property out of the combobox runtime object‟s available items collection.net application combobox runtime object has no such property.

events and properties. Aside from straightforwardly using our test objects to perform actions. GetROProperty requires the test object‟s corresponding runtime object to exist. and perform the relevant action on it. this command will print out “Notepad”: Msgbox Window("text:=Notepad"). The test object‟s simple properties and methods act as a bridge. the GetTOProperties command has nothing to do with the actual runtime object in our application.Net combobox usually involves changing several properties (SelectedIndex. select a value from a VBComboBox or click a WebElement. selecting a value in a . This means that unlike the GetTOProperty and GetTOProperties commands. GetROProperty allows us to get the current value of a test object property. or if that value was updated in “the real world” since the object was recorded. However. For example.GetTOProperty("text") The GetTOProperty command will retrieve the value as it was originally recorded (or created via DP). or create instant test objects via Descriptive Programming. Every time we maximize a window. For example. only the test object which represents it. we do it through the QTP test objects. Like GetTOProperty. sparing us the need to nitpick our way through the runtime object‟s unknown commands. etc. SelectedItem). While the application runtime objects might be extremely complex. TextChanged. We can either use prerecorded test objects from the object repository. GetTOProperties returns a collection with all the test object properties. the corresponding QTP test objects are standard and very simple in comparison. there are 4 special commands which allow us to access the core of QTP‟s test object mechanism: GetTOProperty. and raising several events (SelectionChanged.Another important role is standardization. ItemSelected. GetTOProperty allows us to retrieve the value of a test object property. SetTOProperty and GetROProperty. It does not matter if the corresponding runtime object exists. the corresponding SwfComboBox test object provides a much more simpleand standard “Select” method which does the trick for you. Working with Test Objects How can we work with test objects in our scripts? The most straight-forward way is to simply use them. GetTOProperties. QTP will touch the .). QTP will translate the test object‟s simple commands to the runtime object‟s commands required to perform the task at hand. QTP will then locate the corresponding “real” runtime object.

but GetROProperty will still be able to retrieve the value of the window‟s text property (where GetTOProperty would return an empty result).runtime object. the test objects it creates do not have the properties or methods that are required to operate the objects (like “all items” and Select). this command will retrieve the updated value: Msgbox Window("Notepad"). For example. and it will print out all the available items: Msgbox SwfWindow("X"). . "incorrect value") Window("Notepad"). the command still retrieves only test object properties.Net custom controls).SetTOProperty("nativeclass". and it will not find any object matching that description. In the following example. some combo-boxes might appear as SwfObjects. which QTP fails to recognize correctly. as opposed to the QTP test objects: There are some objects (especially . Msgbox Window("nativeclass:=Notepad"). As QTP fails to recognize the object for what they are (in this example. or even when you go in and out of actions. So even though a . For example. SetTOProperty allows us to change a test object‟s property for the duration of the test-run. our test object has only one property – nativeclass.Close 'this command will fail The second command will fail as QTP will search for an object with nativeclass = “incorrect value”.Net combobox runtime object does not have an “all items” property.SwfCombobox("Y").GetROProperty("all items") Last but not Least. you could still execute the following command. but they are sometimes too limited for the task at hand. Here it makes no difference if QTP succeeds to correctly recognize the object. There are two situations in which we might prefer working with the actual runtime objects of the application. and retrieve the value of the property from it. So for example: Call Window("Notepad"). From Test Objects to Runtime Objects Test objects are the cornerstone of all QTP object operations. Any changes made with SetTOProperty will be reset once the test-run had finished. Even though it has RO (Runtime Object) in it. Another case is when we are required to perform some non-standard operation with an object.GetROProperty("text") It is important not to be confused by the “RO” in the command name. or generic ActiveX controls. It is important to note that changing a test object‟s properties might cause QTP not to identify its corresponding runtime object. if the text of the Notepad window changed from when that object was recorded.GetROProperty("text") Unlike GetTOProperty and GetTOProperties. it does not even matter if the test object originally recorded the relevant property. combo-boxes).

WebList ("z"). we‟ll still be able to select an item from it. If it is a . So even if our . these commands will print the same value: Print Browser("X").Object property. For example: Print Browser("X").Color We can even use the runtime object‟s methods. WebList ("z").Page("Y"). we can perform almost any operation on our objects. Not all test objects support working with their corresponding runtime objects. It is important to note that WebList test object does not have a selectedIndex property.selectedIndex Print Browser("X"). regardless of QTP‟s ability to recognize them for what they truly are.Object. only a derived property called “selected item index”. you can also use the .Page("Y"). So for example. Working with Runtime Objects You can see an object‟s runtime properties and methods in the RO tab of the object spy. by overwriting the runtime property of the selected item‟s index.as the corresponding test object will only provide us with a standard set of commands and properties. WebList ("z").Object. it can be done via their . and print its value.Object. WebList ("z"). A good example for this case is trying to find the font style of a WebElement. but if they do.SelectedIndex = 1 . we can find out the color of a WebList‟s items text: Print Browser("X"). WebList ("z").SwfObject("Y"). The WebElement test object simply does not carry the information we need.selectedIndex This command will find the runtime object corresponding to the WebList‟s test object.focus By accessing the runtime world.net combobox is identified as a SwfObject.GetROProperty("selected item index") The true benefit of working with runtime objects lies with properties and methods that are not available through the QTP test object. and so we have to resort to unusual measures such as working with the WebElement‟s runtime object.Page("Y").Object.Net form spy to get a more detailed look of those properties that contain inner complex objects.Object.Page("Y"). SwfWindow("X"). and perform operations that are otherwise unavailable to us: Print Browser("X").CurrentStyle. access its selectedIndex property.netobject. This property exposes all the properties and methods of the runtime object “hiding” behind our test object. Of course that in order for this to work the runtime object must exist when we execute the command. So in this case.Page("Y").

Adding a Call-Chain Mechanism to QTP Background and motivation A common frustrating experience is having your script pop-up an error dialog in some long-forgotten function. whereas in C++ it would trigger a compilation error. calling the wrapping function. or by testing the inner function call on a standalone basis. There are ways to overcome these shortcomings.Color was hard to come by). without one having the slightest clue in its regard. a faulty call to a function (wrong function name or number of parameters) would pass unnoticed in VB Script when part of a function. but nonetheless. Unlike the standard and simple test objects. it is important to remember that working directly with runtime objects can have significant downsides. and carefully mapping the consequences of changing runtime properties. that is. and exactly what properties and methods it has (CurrentStyle. in which compilation at least guarantees that the function calls are syntactically correct. we must always be aware of them. The only way to get the error message in such cases is by actually performing the code. such as exploring custom controls. it is unclear how to operate the object. This is because in VB Script compilation is done on the basis of a line-after line interpretation during run-time. it is not long until the calls to functions and object methods become too deeply nested for us humans to grasp. For example. What usually follows is a series of trial-and-error breakpoint runs to determine which action the script was actually trying to perform when executing the function call that triggered the error. . In any language. All programming languages suffer from such problems.With all their benefits. but in late bound languages like VB Script this problem is really challenging. in contrast to languages such as C/C++. Even when we find the right properties or methods. using them “from behind the scenes” may cause application errors and invoke hidden bugs.

Please notice that it shows both the functions and code lines that precipitated the error. indeed. QTP reports are inaccessible during the run-session. and see where things started to go wrong (usually 2-3 function calls before the function we are currently in). Moreover. even when bugs and error occur within extremely nested function calls. how valuable would it been to know which parameters were sent into those function calls. Developed by our people at SOLMAR‟s R&D Division. A call-chain mechanism is just one of the rich features provided by SOLMAR‟s flagship product: My SystemTM. This allows us to analyze the error‟s path. and so on up to the root of the call hierarchy. Possible Implementations Now. stay tuned!). They manage to do so via a dedicated mechanism: the call-chain (sometimes referred to as the call-stack). which function called that function. Or. There is a way. Meanwhile. The call-chain shows us exactly which function called the currently executing function. the answer is no. My SystemTM brings the latest advances to boost ROI on testing automation (We shall have much more to say on that in future posts. An example of a Visual Studio call-stack for an error can be viewed in Figure 1 below. it is possible to implement a call-chain in QTP with intensive reporting – just by sending a line to the report from any function as you enter and exit it. Figure 1: A Sample Visual Studio Error Call-Stack Just imagine how many debug runs you could have saved just by knowing the exact order of calls which lead you to the current function. I thought that I could share some of my techniques and thoughts on the subject. though it‟s not trivial. . Is the inevitable conclusion that there is no way to implement a call-chain in QTP effectively? Well.Having said that. However. programmers do debug their code. and that is exactly why the call-chain data is crucial. this will render your report cluttered and hence difficult to grasp.

and nothing else.. Here is an example of how the stack mechanism would work: Let‟s say our code went though these functions: Function Func1 Call Func2 End Function Function Func2 Call Func3 End Function Function Func3 Dim x Call Func 4 x = 1/0 End Function . 3. The Concept Developing an effective call-chain requires four basic components: 1. 2. sub or action). A place to store the call-chain data. This will make sure your call chain contains all the relevant data needed to understand what got you until this point. A mechanism for viewing the stored data mid-run (we won‟t get into this one – it is basically just a simple window to peek at the stored data) If you have a robust mechanism for updating the call-chain when you are exiting and entering contexts. 4. Storing the Call-Chain Data An excellent mechanism for storing call-chain data is a stack.e.Though the examples given here are not meant to be used or to be an out-of-the-box solution. the names of the contexts you happen to enter during the flow) in a FILO manner – First-In Last-Out. A mechanism for updating the call-chain when you enter a context (by context I mean a function. then implementing the call-chain will be quite straightforward. A stack can store data (i. and an easy to use storage for the call chain. A mechanism for updating the call-chain when you exit a context. I do believe they can point you in the right direction for developing robust solutions of your own.

At this point. once the code will exist Func4. it will remove the last item from our stack.Remove End Function Notice that we don‟t have to specify the function name for our Remove command.. which would hold just enough data to understand how we got into Func3.Add "Func1" '[. Line 14 will result is an error.Add "Func1" . “Func2”. Now Func4 will end. A Naive Approach to Updating the Call-Chain Data on the Run Well. after we got our own storing mechanism for the call-chain data.Function Func4 'Ended End Function If we call Func1. you can take a look at Dani Vainstein‟s excellent article on the matter – here. returning the control to Func3. and a removecommand every time we exit it. where we could debug. as shown in the following example: Function Func1 'Add to call chain oChainData. The naive approach would be to simply perform an add command once we enter a function. make it: (“Func1”. and it would call Func4. ' Function body ' . Since our call chain is a Stack. and no irrelevant data (for example.] 'Remove from stack oChainData. but usually our code is more complex than this – usually our functions have multiple exit gates. which would call Func3. So it should look something like this (assuming our data is stored in an oChainData stack storage. “Func2”. “Func3”). we better start recording it... as the stack mechanism always know to remove the top level item.. it will call Func2. with add and remove commands): Function Func1 'Add to call chain oChainData. If you‟d like to know exactly how to implement a stack. and take a look at our stack. “Func3”. Problems with the Naive Approach That is all fine and well. our call-chain stack would look like this: (“Func1”. the fact the we have entered and exited Func4). “Func4”).

anything we write within the Class_Terminate sub of the class will be executed when the class object is destroyed..Remove Exit Function 'Now the regular exit gate: oChainData. and tell us (or rather the call-chain) when we enter and exit it. When we write a class.Remove Exit Function 'More Code.... for example: Class KillSwitch Sub Class_Terminate Msgbox "Object terminated" End Sub End Class Set oKill = New KillSwitch Set oKill = Nothing .. But such errors are exactly our motivation to be willing to put an effort in maintaining a call-chain mechanism in the first place! A More Robust Solution We have seen that our naive solution fails at some basic everyday cases.. and that would just make our whole stack misleading and useless. oChainData. In order to achieve that. oChainData. but perhaps we can overcome this with more complex scripting.. 'If structures etc. before letting us update the call-chain data.Remove Exit Function 'More Code. What these examples show is that we need an automatic component that will “listen” to our function.. we still run the risk of a mid-function error that will throw us out. 'If structures etc.Remove End Function When our function has multiple exit gates. we could use the termination event of an object. but we can do the exit part quite easily....'Code. oChainData. And even if our code is perfect (and it never is). it is just a matter of time before we forget to update the call-chain.. 'If structures etc. So. Implementing the whole package (monitor both entering and exiting a function) might be hard.

Since the object will be destroyed whenever we exit the function (either purposefully. We have seen that the naive approach (manually update on entering and exiting a context) is impractical. or due to an error).'Now the message box will appear As you can see. to share with the community your own call-chain mechanism! . We can use this to our advantage – instead of popping up a message box. it builds upon the same basic principles demonstrated in this article. SOLMAR Knowledge Networks has developed an automation framework with a built-in call-chain mechanism. we don‟t have to worry about “forgetting” to update the call-chain. As a closing word. no matter when we exit the function. about this article. The main concept explained how we can keep track of the chain-data. While it is much more detailed and effective. let us make our object update the call-chain.Remove End Sub End Class Function Func1 Dim oUpdater 'This will hold the exit kill-switch oChainData.Add "Func1" 'Update the chain-data Set oUpdater = New ChainUpdater 'Create an instance of the kill switch 'Now. Although the article did not provide a detailed example of a call-chain. the kill switch will be activated 'And the chain-data will be updated End Function Summary This article introduced the concept of a call-chain and provided substantial reasons for its centrality in the automation development effort. It could look something like this: 'The blueprint for the updater Class ChainUpdater Sub Class_Terminate oChainData. We examined an alternative approach by which call-chain update is achieved automatically through an object‟s kill-switch mechanism. and if you happen to dare and design. As aforementioned. the object “knows” when it is destroyed. I hope that it has successfully outlined how to build the main components that are required in order to implement such a mechanism. let me encourage you to share your thoughts and comments about the call-chain concept.

Sign up to vote on this title
UsefulNot useful