如何在测试脚本中从项目加载模块?

How do I load module from the project in a test script?

我无法将 Module.psm1 加载到 Module.tests.ps1

这是我的Module.psm1。我添加一个 return 到 Get-Function 只是为了看看它是否会被测试运行器拾取。

这是在Module.psm1:

function Get-Function {
    return $true
}

Module.psd1:

FunctionsToExport = 'Get-Function'

Module.tests.ps1:

Describe "Get-Function" {
    Context "Function Exists" {
        Import-Module .\Module.psm1
        It "Should Return" {
            Get-Function | Should Be $true
        }
    }
}

是否必须先构建模块并将其加载到我的模块路径中,然后才能针对它编写测试?或者有没有办法参考它相对于测试路径的位置?

我在输出 window 中看到的结果是:

------ Run test started ------
Describing Get-Function
   Context Function Exists
    [-] Should Return 731ms
The term 'Get-Function' is not recognized as the name of a cmdlet, function,
script file, or operable program. Check the spelling of the name, or if a path
was included, verify that the path is correct and try again.
at line: 12 in C:\Users\Adam\Documents\code\Powershell\TestModuleProject\TestModuleProject\Module.tests.ps1
Tests completed in 731ms
Passed: 0 Failed: 1 Skipped: 0 Pending: 0 
========== Run test finished: 1 run (0:00:08.1834099) ==========

有什么建议吗?

我怀疑工作目录 (.) 与您 运行 测试时文件所在的目录不同。您可以使用 $MyInvocation.MyCommand.Path 来确定测试脚本的目录。

Pester 单元测试(这是您的测试代码和输出的样子)通常包含这样一行:

$here = Split-Path -Parent $MyInvocation.MyCommand.Path

尝试按如下方式更改您的测试代码:

<b>$here = Split-Path -Parent $MyInvocation.MyCommand.Path</b>

Describe "Get-Function" {
    Context "Function Exists" {
        Import-Module <b>"$here\Module.psm1"</b>
        It "Should Return" {
            Get-Function | Should Be $true
        }
    }
}