简单的Powershell Pester测试不适用于$ false

时间:2017-11-01 18:57:06

标签: unit-testing powershell pester

我写了一个非常简单的函数叫做“Check-RegValueExists”,它直接从命令提示符执行时如下工作

Check-RegValueExists "HKLM:\Software\Microsoft\Windows\CurrentVersion" "DevicePath"

Check-RegValueExists "HKLM:\Software\Microsoft\Windows\CurrentVersion" "Devicexxxx"

Check-RegValueExists "HKCU:\Software\Classes\message-facebook-com" "URL Protocol"

输出以下

True
False
False

这些都是正确的结果。

我的纠缠测试是

Describe 'Check-RegValueExists Tests'{

It "has valid key with valid value" {
        'Check-RegValueExists "HKLM:\Software\Microsoft\Windows\CurrentVersion" "DevicePath"' | Should Be $true
        } 

It "has invalid key" {
        'Check-RegValueExists "HKLM:\Software\Microsoft\Windows\CurrentVersion" "Devicexxxx"' | Should Be $false
        } 

It "has empty value" {
        'Check-RegValueExists "HKCU:\Software\Classes\message-facebook-com" "URL Protocol"' | Should Be $false
        } 

}

但是只有第一次测试通过其他两次失败以及

[-] has invalid key 17ms
   Expected: {False}
   But was:  {Check-RegValueExists "HKLM:\Software\Microsoft\Windows\CurrentVersion" "Devicexxxx"}
   8:         'Check-RegValueExists "HKLM:\Software\Microsoft\Windows\CurrentVersion" "Devicexxxx"' | Should Be $false
   at <ScriptBlock>, <No file>: line 8
 [-] has empty value 28ms
   Expected: {False}
   But was:  {Check-RegValueExists "HKCU:\Software\Classes\message-facebook-com" "URL Protocol"}
   12:         'Check-RegValueExists "HKCU:\Software\Classes\message-facebook-com" "URL Protocol"' | Should Be $false
   at <ScriptBlock>, <No file>: line 12

我甚至复制并粘贴了第一个测试并仅修改了字符串以确认但仍然失败。是否存在语法错误或其他原因?

1 个答案:

答案 0 :(得分:2)

您的问题是因为您已将命令包装在单引号中,并将其转换为字符串。因此,您正在测试每个字符串是$ true还是$ false,并且任何值都被视为$ true。

你需要这样做:

Describe 'Check-RegValueExists Tests'{

    It "has valid key with valid value" {
        Check-RegValueExists "HKLM:\Software\Microsoft\Windows\CurrentVersion" "DevicePath" | Should Be $true
    } 

    It "has invalid key" {
        Check-RegValueExists "HKLM:\Software\Microsoft\Windows\CurrentVersion" "Devicexxxx" | Should Be $false
    } 

    It "has empty value" {
        Check-RegValueExists "HKCU:\Software\Classes\message-facebook-com" "URL Protocol" | Should Be $false
    } 
}