You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Quamotion Pester移动应用测试中使用全局变量?

在Quamotion/Pester测试中使用全局变量优化参数输入

当然可以!在Quamotion搭配Pester做移动应用测试时,用全局变量来统一管理重复输入的参数(比如用户名、密码),不仅能减少重复劳动,还能让测试脚本更易维护。下面我给你分享几种实用的实现方案:

1. 直接使用PowerShell全局变量

因为Pester是基于PowerShell的测试框架,所以可以直接借助PowerShell的全局变量特性来定义通用参数,简单直接:

# 在测试脚本的最开头定义全局变量
$Global:TestUsername = "test_user_01"
$Global:TestPassword = "SecurePass123!"

之后在任意测试用例里直接调用这些变量即可:

Describe "移动应用登录功能测试" {
    It "使用合法账号登录成功" {
        # 调用Quamotion的登录动作,传入全局参数
        $loginResult = Start-QuamotionAction -Command Login -Parameters @{
            Username = $Global:TestUsername
            Password = $Global:TestPassword
        }
        
        $loginResult | Should -Be $true
    }
}

这种方式适合小型测试项目,但要注意全局变量会污染PowerShell的全局作用域,尽量避免和其他脚本的变量重名。

2. 利用Pester内置的测试会话变量

Pester提供了更规范的测试会话变量机制,变量会被封装在测试会话中,不会污染全局环境,更符合Pester的最佳实践:

# 初始化Pester配置并注入全局参数
$pesterConfig = New-PesterConfiguration
$pesterConfig.TestSession.Variables.Add("TestUsername", "test_user_01")
$pesterConfig.TestSession.Variables.Add("TestPassword", "SecurePass123!")

# 传入配置运行测试
Invoke-Pester -Configuration $pesterConfig

在测试用例中通过$Pester.Variables访问这些参数:

Describe "移动应用登录功能测试" {
    It "使用合法账号登录成功" {
        $username = $Pester.Variables["TestUsername"]
        $password = $Pester.Variables["TestPassword"]
        
        $loginResult = Start-QuamotionAction -Command Login -Parameters @{
            Username = $username
            Password = $password
        }
        
        $loginResult | Should -Be $true
    }
}

3. 外部配置文件(推荐用于多环境场景)

如果你的测试需要适配不同环境(比如测试/预发/生产),或者参数需要频繁修改,把参数存到外部配置文件里是最优解——相当于把“全局变量”和测试代码分离,维护起来更灵活。

比如创建一个test-config.json文件:

{
    "TestCredentials": {
        "Username": "test_user_01",
        "Password": "SecurePass123!"
    },
    "AppSettings": {
        "PackageName": "com.example.myapp"
    }
}

然后在测试脚本里加载这个配置文件作为全局可用的变量:

# 加载配置文件并转为全局变量
$Global:TestConfig = Get-Content -Path "./test-config.json" | ConvertFrom-Json

Describe "移动应用登录功能测试" {
    It "使用合法账号登录成功" {
        $loginResult = Start-QuamotionAction -Command Login -Parameters @{
            Username = $Global:TestConfig.TestCredentials.Username
            Password = $Global:TestConfig.TestCredentials.Password
        }
        
        $loginResult | Should -Be $true
    }
}

重要注意事项

敏感数据不要明文存储!如果是密码这类机密信息,建议用PowerShell的ConvertTo-SecureString加密后再存入配置,或者使用PowerShell的SecretManagement模块来安全管理,避免泄露风险。

内容的提问来源于stack exchange,提问作者Jacob Peeters

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 09:14:26