Search code examples
unit-testingpowershellpester

Simple Powershell Pester Test not working for $false


I wrote a very simple function called "Check-RegValueExists" which works as follows when executing directly from the command prompt

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"

which outputs the following

True
False
False

which are all correct outcomes.

My pester test is

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
        } 

}

However only the first test passes and other two fail with following

[-] 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

I even copied and pasted first test and modified only the string to confirm but still failing. Is there a syntax error or something else?


Solution

  • Your issue is because you have wrapped your commands in single quotes, which has turned them in to strings. As a result you are testing whether each string is $true or $false and any value is considered $true.

    You need to do this:

    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
        } 
    }