我在 Pester 中有以下简单的测试:
# Name.Tests.ps1
$name = "foo"
Describe "Check name" {
It "should have the correct value" {
$name | Should -Be "foo"
}
}
所以当我导航到包含测试脚本的文件夹并运行 Invoke-Pester
时,我希望测试能够通过。相反,我收到以下错误:
[-]检查名称。应该有正确的值。预期为 'foo',但得到 $null...
知道为什么会失败以及为什么 $name
在 It
block 中设置为 null - 不应该仍然设置 $name
到 foo
因为它来自父范围?
最佳答案
Pester v5 需要遵循新规则,其中之一是以下 (https://github.com/pester/Pester#discovery--run):
Put all your code into It, BeforeAll, BeforeEach, AfterAll or AfterEach. Put no code directly into Describe, Context or on the top of your file, without wrapping it in one of these blocks, unless you have a good reason to do so. ... All misplaced code will run during Discovery, and its results won't be available during Run.
因此,将变量赋值放在 Describe
block 内的 BeforeAll
或 BeforeEach
中应该可以使其工作:
Describe "Check name" {
BeforeAll {
$name = "foo"
}
It "should have the correct value" {
$name | Should -Be "foo"
}
}
感谢@Mark Wragg 为我指明了正确的方向!
关于powershell - 纠缠:无法访问父作用域变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62539713/