Skip to content

Commit 19abcf7

Browse files
committed
refr: Refactor Mock-EnvironmentVariable
1 parent 702f6aa commit 19abcf7

File tree

2 files changed

+19
-13
lines changed

2 files changed

+19
-13
lines changed

src/PesterExtensions/Public/Mock-EnvironmentVariable.ps1

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -12,28 +12,31 @@ function Mock-EnvironmentVariable {
1212
[ScriptBlock]
1313
$Fixture
1414
)
15-
if (Test-Path -Path "env:${Variable}") {
16-
$OriginalValue = (Get-ChildItem -Path "env:${Variable}").Value
15+
$EnvironmentVariable = "env:${Variable}"
16+
if (Test-Path -Path $EnvironmentVariable) {
17+
$OriginalValue = (Get-ChildItem -Path $EnvironmentVariable).Value
1718
if ($value) {
18-
Set-Item -Path "env:${Variable}" -Value $Value
19+
Set-Item -Path $EnvironmentVariable -Value $Value
1920
}
2021
}
2122
else {
22-
New-Item -Path "env:${Variable}" -Value $Value
23+
New-Item -Path $EnvironmentVariable -Value $Value
2324
}
2425
try {
2526
Invoke-Command -ScriptBlock $Fixture
2627
}
28+
2729
catch {
2830
throw $_
2931
}
32+
3033
finally {
3134
if ($OriginalValue) {
32-
Set-Item -Path "env:${Variable}" -Value $OriginalValue
35+
Set-Item -Path $EnvironmentVariable -Value $OriginalValue
3336
}
34-
elseif (Test-Path -Path "env:${Variable}") {
37+
elseif (Test-Path -Path $EnvironmentVariable) {
3538
Remove-Item `
36-
-Path "env:${Variable}" `
39+
-Path $EnvironmentVariable `
3740
-Recurse `
3841
-Force `
3942
-ErrorAction Stop

tests/PesterExtensions/Public/Mock-EnvironmentVariable.Tests.ps1

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -31,22 +31,25 @@ Describe 'Mock an environment variable' {
3131
}
3232
Describe 'Environment variable is set up' {
3333
BeforeAll {
34-
$script:environmentVariable = "test$(New-Guid)"
35-
$script:InitialValue = 'Some value here and there'
34+
$environmentVariableName = "test$(New-Guid)"
35+
$environmentVariable = "env:${environmentVariableName}"
36+
$InitialValue = 'Some value here and there'
3637
}
3738

3839
It 'Environment variable is set up' {
39-
$environmentVariable = "test$(New-Guid)"
40-
$InitialValue = 'Some value here and there'
4140
Test-Path -Path $environmentVariable | Should -BeFalse
4241
Mock-EnvironmentVariable -Variable $environmentVariable -Value $InitialValue {
43-
(Get-ChildItem -Path "env:${environmentVariable}").Value | Should -Be $InitialValue
42+
(Get-ChildItem -Path $environmentVariable).Value | Should -Be $InitialValue
4443
}
4544
Test-Path -Path $environmentVariable | Should -BeFalse
4645
}
4746

4847
AfterAll {
49-
48+
Remove-Item `
49+
-Path $environmentVariable `
50+
-Recurse `
51+
-Force `
52+
-ErrorAction Ignore
5053
}
5154
}
5255

0 commit comments

Comments
 (0)