Search code examples
unit-testingpowershellmockingpester

How to mock a call to an exe file with Pester?


Developing a script in PowerShell, I require to call an external executable file(.exe). currently I am developing this script with a TDD approach, therefore I require to mock the called to this .exe file.

I try this :

Describe "Create-NewObject" {
    Context "Create-Object" {
        It "Runs" {
            Mock '& "c:\temp\my.exe"' {return {$true}}
            Create-Object| Should Be  $true
        }
    }
}

I got this response:

Describing Create-NewObject
   Context Create-Object
    [-] Runs 574ms
      CommandNotFoundException: Could not find Command & "C:\temp\my.exe"
      at Validate-Command, C:\Program Files\WindowsPowerShell\Modules\Pester\Functions\Mock.ps1: line 801
      at Mock, C:\Program Files\WindowsPowerShell\Modules\Pester\Functions\Mock.ps1: line 168
      at <ScriptBlock>, C:\T\Create-NewObject.tests.ps1: line 13
Tests completed in 574ms
Passed: 0 Failed: 1 Skipped: 0 Pending: 0 Inconclusive: 0

Is there a way to mock this kind of calls without encapsulate them inside a function?


Solution

  • I found a way to mock the call to this executable files:

    function Create-Object
    {
       $exp = '& "C:\temp\my.exe"'
       Invoke-Expression -Command $exp
    }
    

    And the test with the mock should looks like:

    Describe "Create-NewObject" {
        Context "Create-Object" {
            It "Runs" {
                Mock Invoke-Expression {return {$true}} -ParameterFilter {($Command -eq '& "C:\temp\my.exe"')
                Create-Object| Should Be  $true
            }
        }
    }