安装PowerShell Tools for Visual Studio 2015后,我创建了一个新的Powershell Module Project,它创建了一个MyProject.psd1,一个MyProject.psm1和一个MyProject.tests.ps1文件。

MyProject.tests.ps1文件看起来像这样

Describe "Connect-Database" {
    Context "When Connection To Database" {
        $result = Connect-Database -host localhost -user admin -pass pass
        It "Should Return True" {
            $result | Should Be $True
        }
    }
}

Connect-Database是MyProject.psm1的函数,并通过MyProject.psd1导出
# Functions to export from this module
FunctionsToExport = 'Connect-Database'

运行Powershell控制台并执行
Import-Module .\MyProject.psd1
Invoke-Pester

效果很好,返回很高
Describing Connect-Database
   Context When Connection To Database
    [+] Should Return True 627ms
Tests completed in 627ms
Passed: 1 Failed: 0 Skipped: 0 Pending: 0

这是我的问题:PowerShell Tools附带了一个测试适配器,并且我的测试显示在Test Explorer中。

但是,如果我执行它,它总是失败并带有The term Connect-Database is not recognized as cmdlet function script file or operable program
即使将Import-Module .\MyProject.psd1添加到MyProject.tests.ps1文件也无济于事。有什么想法在运行测试之前如何加载模块?

最佳答案

我在MyProject.tests.ps1文件中添加了Get-Location | Write-Host,发现工作目录为C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE
我没有首先检查它,因为我相信测试适配器只会在工作目录中执行Invoke-Pester
最终我解决了

Split-Path $PSCommandPath | Set-Location
Import-Module (".\" + (Split-Path -Leaf $PSCommandPath).Replace(".tests.ps1", ".psd1"))

09-10 06:05
查看更多