Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
616 views
in Technique[技术] by (71.8m points)

Pass Variables to Powershell Pester Tests v5

I am at the last stages with my pester tests, but am having issues with the variable scoping. I have quite a few tests and would like use something like Global scoping in order to declare variables such as $ModuleName, $ProjectRoot, and other similar things that are needed in each test.

I have tried using New-Variable -Scope Global and $Global:ModuleName but these don't seem to be visible in the Pester Tests.

I am calling Invoke-Pester from a build.ps1 file which has these declared.

Has anyone seen any good ways to use centrally defined variables, without using $env: variables?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I have found using $Env: variables to be the best approach. Thanks to the BuildHelpers module for showing me this.

This is now what the beginning of my Pester Test looks like:

Describe "Core Module Validation" {
BeforeAll {
    $Script:moduleName = $ENV:BHProjectName
    $Script:modulePath = $ENV:BHModulePath

    Remove-Module -Name $moduleName -Force -ErrorAction SilentlyContinue

    $Script:manifestTestResult = Test-ModuleManifest -Path $Env:BHPSModuleManifest
    $Script:publicScriptFiles = Get-ChildItem -Path "$modulePathPublic" -Recurse
}

It "should cleanly import Module '$ENV:BHProjectName'" {
    { Import-Module -Name $modulePath -Force } | Should -Not -Throw
}
It "should export one or more functions" {
    Import-Module -Name $modulePath -Force
    Get-Command -Module $moduleName | Measure-Object | Select-Object -ExpandProperty Count | Should -BeGreaterThan 0
}

It "should have a valid PSD1 Module Manifest" {
    { Test-ModuleManifest -Path $ENV:BHPSModuleManifest } | Should -Not -Throw
}

These $Env: variables are set in my build.ps1 file, and are only temporary for the session.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...