Pester 试驾不存在

Pester Testdrive does not exists

我正在尝试使用 Pesters TestDrive 为自定义文件管理 powershell 函数创建测试。 但是,我没有以任何方式得到它 运行,总是收到 TestDrive 不存在的错误。

即使使用文档中的示例:https://pester.dev/docs/usage/testdrive

我创建了一个文件“pester.tests.ps1”,其中只有示例:

function Add-Footer($path, $footer) {
    Add-Content $path -Value $footer
}

Describe "Add-Footer" {
    $testPath = "TestDrive:\test.txt"
    Set-Content $testPath -value "my test text."
    Add-Footer $testPath "-Footer"
    $result = Get-Content $testPath

    It "adds a footer" {
        (-join $result) | Should -Be "my test text.-Footer"
    }
}

出现的错误:

Starting discovery in 1 files. Set-Content : Cannot find drive. A drive with the name 'TestDrive' does not exist. At ...\pester.tests.ps1:7 char:5
+     Set-Content $testPath -value "my test text."
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (TestDrive:String) [Set-Content], DriveNotFoundException
    + FullyQualifiedErrorId : DriveNotFound,Microsoft.PowerShell.Commands.SetContentCommand   Add-Content : Cannot find drive. A drive with the name 'TestDrive' does not exist. At ...\pester.tests.ps1:2 char:5
+     Add-Content $path -Value $footer
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (TestDrive:String) [Add-Content], DriveNotFoundException
    + FullyQualifiedErrorId : DriveNotFound,Microsoft.PowerShell.Commands.AddContentCommand   Get-Content : Cannot find drive. A drive with the name 'TestDrive' does not exist. At ...\pester.tests.ps1:9 char:15
+     $result = Get-Content $testPath
+               ~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (TestDrive:String) [Get-Content], DriveNotFoundException
    + FullyQualifiedErrorId : DriveNotFound,Microsoft.PowerShell.Commands.GetContentCommand   
Discovery finished in 46ms. [-] Add-Footer.adds a footer 10ms (8ms|2ms)  Expected strings to be the same, but they were different.  Expected length: 20  Actual length:   0  Strings differ at index 0.  Expected: 'my test text.-Footer'  But was:  ''  at (-join $result) | Should -Be "my test text.-Footer", ...\pester.tests.ps1:12  at <ScriptBlock>, ...\pester.tests.ps1:12 Tests completed in 152ms Tests Passed: 0, Failed: 1, Skipped: 0 NotRun: 0

我是不是忘记了什么?还有其他先决条件吗?我已经更新了 Pester 和 Powershell。

Pester v5 最近发布了,它对 Pester 的运行方式进行了相当大的更改,并提前解释了测试。因此,对于如何构建测试有一些重大更改,其中之一是需要通过 beforeallbeforeeach 块完成测试设置。

因此,您的示例的重写有效:

function Add-Footer($path, $footer) {
    Add-Content $path -Value $footer
}

Describe "Add-Footer" {

    BeforeAll {
        $testPath = "TestDrive:\test.txt"
        Set-Content $testPath -value "my test text."
    }
    
    It "adds a footer" {
        Add-Footer $testPath "-Footer"
        $result = Get-Content $testPath
        (-join $result) | Should -Be "my test text.-Footer"
    }
}

有一个 open issue 关于 Pester v5 如何影响 TestDrive,我刚刚添加了一个注释来说明它的文档示例不再有效的事实。