1

I am trying to unit test my Powershell script file with below code snippet using Pester

#code to create a 7z file 
$7zipPath = "C:\Program Files\7-Zip\7z.exe"
Set-Alias 7zip $7zipPath
if (!(Test-Path -Path $7zipPath -PathType Leaf)) {
    throw "7 zip file '$7zipPath' not found"
}
7zip a -mx=9 $jenkinsWorkspacepath\IntegrationZip.7z $jenkinsWorkspacepath\IntegratedScripts

And mocking the Test-Path command as below

    Mock -CommandName Test-Path –MockWith {
        Return $false  
    }

But the coverage report shows the below line as uncovered.. What am i doing wrong here(in the mocking part)?

**throw "7 zip file '$7zipPath' not found"**
An Kumar
  • 77
  • 1
  • 8

1 Answers1

1

What does your test look like? I tried the following and it worked fine for your code:

Mock -CommandName Test-Path -MockWith { return $false }  

It "fails to find executable" {
    { Invoke-SevenZip } | Should -Throw "not found"
}

Note: I wrapped your code in a function called Invoke-SevenZip

boxdog
  • 7,894
  • 2
  • 18
  • 27
  • This is likely the answer. You need to have a test that is checking for a `Throw` result. You pipe a scriptblock to the test for `-Throw` as Boxdog has shown above. – Mark Wragg Feb 19 '20 at 10:13