简体   繁体   中英

Pester: How do I keep my script from running?

I am testing a PowerShell script. I'd like to test individual functions without executing the entire script. I am not sure if this is the intended use case or supported, and I am not finding a good answer searching online

sut.ps1:

Param(
    [Parameter(Mandatory = $true,
        Position = 0)]
    [ValidateNotNullOrEmpty()]
    [string] $Message
)

function fut([string] $argument) {
    Write-Host $argument
}

function Main() {
    fut($Message)
}

Main

sut.tests.ps1:

$here = Split-Path -Parent $MyInvocation.MyCommand.Path
$sut = (Split-Path -Leaf $MyInvocation.MyCommand.Path) -replace '\.Tests\.', '.'
. "$here\$sut" "Message"

Describe "fut" {
    It "does something useful" {
        fut 'beer'
    }
}

Output

Message
Describing fut
beer
 [+] does something useful 385ms
Tests completed in 385ms

Now I can mock away 'beer', because it runs in the describe block. But I cannot mock away 'message', because the script starts to execute when I dot-source it.

In my case, 'message' is an operation I do not want to execute.

I am on Windows 10 15063.

Per the comments, the issue is that your script is self-executing, so it's not possible to load it for Pester via dot-sourcing without also executing the functions.

The workaround suggested by Roman to temporarily use Set-Alias to set main to Out-Null would work. Another suggestion would be to separate your functions to a separate file (eg named functions.ps1 ) and then in your original script you can use dot sourcing to include it, but in your test script just dot source the functions.ps1 file.

This will only run the main function if it is not called ny Dot Source, as a pester script would. I am using this instead of splitting functions to another file where it is not needed. Then pester runs without invoking the Main function.

if (-not ($MyInvocation.InvocationName -eq "."))
{
    Main
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM