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

标签 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

我什至复制并粘贴了第一个测试并仅修改了字符串以进行确认,但仍然失败。是否有语法错误或其他错误?

最佳答案

您的问题是因为您将命令用单引号括起来,这已将它们转换为字符串。因此,您正在测试每个字符串是 $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
    } 
}

关于unit-testing - 简单的 Powershell Pester 测试不适用于 $false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47061810/

相关文章:

powershell - 模拟 New-AzureRmDnsRecordConfig 返回 Microsoft.Azure.Commands.Dns.DnsRecordBase[] 类型的值

javascript - 如何在模拟函数的回调中调用解析?

c# - ATDD - 验收测试从哪里开始?

xml - powershell xml 排序节点和 replacechild

c# - 我如何使用 Pester 模拟 .cs 文件的内容,从而允许我迭代每一行和每个字符?

powershell - 通过内置的模拟脚本 block (Pester)访问外部变量

visual-studio-2010 - VS 2010 中的 MS 单元测试,测试方法 [我的方法] 抛出异常 : . ..,WT*?

django - 在 VSCode 测试资源管理器中运行 Django 测试?

windows - 在 Windows 上查找当前事件语言

.net - .NET应用程序-提取程序集/文件版本令人困惑