"本文介绍了QTP(QuickTest Professional,现已被命名为UFT,Unified Functional Testing)如何调用外部函数的三种方法:Executefile、添加到Resource和ExecuteGlobal。"
在自动化测试领域,QTP(现在称为UFT)是一款广受欢迎的自动化测试工具,它允许用户创建和执行功能测试脚本来验证软件的正确性。有时,我们需要在QTP测试脚本中调用外部的函数库,以便重用代码或执行特定的操作。以下是三种调用外部函数的方法:
1. **Executefile方法**
这是最直接的方式,通过`ExecuteFile`函数来运行一个包含自定义函数的外部脚本文件。例如,如果你有一个名为`Wally.vbs`的文件,其中包含一个获取本机IP地址的函数`GetIPAddr`,你可以在QTP脚本中使用以下代码来调用这个函数:
```vbscript
ExecuteFile "c:\wally.vbs"
MsgBox GetIPAddr()
```
在执行这行代码后,QTP会运行`Wally.vbs`,并使其中的所有函数对当前脚本可见。
2. **添加到Resource**
另一种方法是将外部脚本文件添加到QTP的资源中。在QTP的菜单栏中,选择`File` -> `Settings` -> `Resources`,然后将`Wally.vbs`添加进去。这样,每次启动QTP时,该脚本都会自动加载,你可以像使用内置函数一样调用其内容:
```vbscript
MsgBox GetIPAddr()
```
这种方法的好处是不需要每次调用函数时都执行`ExecuteFile`。
3. **ExecuteGlobal方法**
`ExecuteGlobal`是VBScript的一个内置函数,它允许在当前作用域中执行一个字符串内的VBScript代码。这意味着你可以读取外部文件的内容,并将其作为代码执行。例如,你可以这样做:
```vbscript
Dim fso
Set fso = CreateObject("Scripting.FileSystemObject")
ExecuteGlobal fso.OpenTextFile("c:\wally.vbs", 1).ReadAll
Set fso = Nothing
MsgBox GetIPAddr()
```
使用`ExecuteGlobal`,你可以动态地引入和执行外部脚本,但需要注意的是,这种方法可能会增加脚本的复杂性和执行时间。
每种方法都有其适用场景。`Executefile`适合简单的脚本调用,`添加到Resource`适合需要长期重复使用的代码,而`ExecuteGlobal`则适用于需要动态加载和执行代码的情况。根据实际需求和项目管理策略,选择最合适的方法可以提高测试脚本的可维护性和复用性。