Powershell Core + Pester - 将测试与 src 分开

标签 powershell unit-testing powershell-core pester

问题:

将函数导入不在同一目录中的测试的最佳方法是什么?

例子

📁 src
      📄 Get-Emoji.ps1
📁 test
      📄 Get-Emoji.Tests.ps1

Inb4

  • Pester 文档[1] 建议将测试文件放在与他们测试的代码相同的目录中。未提供替代示例。
  • Pester 文档[2] 建议使用点源来导入文件。仅使用同一目录中的示例
  • 从 src 中分离测试是否是好的做法,将在别处讨论
  • 使用 Powershell Core 在不同操作系统文件系统上提供跨平台支持(正斜杠与反斜杠)

[1] File placement and naming convention

Pester considers all files named .Tests.ps1 to be test files. This is the default naming convention that is used by almost all projects.

Test files are placed in the same directory as the code that they test. Each file is called as the function it tests. This means that for a function Get-Emoji we would have Get-Emoji.Tests.ps1 and Get-Emoji.ps1 in the same directory. What would be the best way to referencing tests to functions in Pester.

[2] Importing the tested functions

Pester tests are placed in .Tests.ps1 file, for example Get-Emoji.Tests.ps1. The code is placed in Get-Emoji.ps1.

To make the tested code available to the test we need to import the code file. This is done by dot-sourcing the file into the current scope like this:

Example 1

# at the top of Get-Emoji.Tests.ps1
BeforeAll { 
    . $PSScriptRoot/Get-Emoji.ps1
}

Example 2

# at the top of Get-Emoji.Tests.ps1
BeforeAll { 
    . $PSCommandPath.Replace('.Tests.ps1','.ps1')
}

最佳答案

我倾向于将我的测试放在一个文件夹中,该文件夹距离脚本所在的位置有一个或两个父级别(通常在一个命名的模块目录下,然后在一个名为 Private 或 Public 的文件夹中)。我只是点源我的脚本或模块,并使用 ..$PSScriptRoot(当前脚本路径)作为引用点来引用父路径。例如:

  • \SomeModule\Public\get-something.ps1 中的脚本
  • \Tests\get-something.tests.ps1 中的测试
BeforeAll { 
    . $PSScriptRoot\..\SomeModule\Public\get-something.ps1    
}

如果考虑跨平台兼容性,请使用正斜杠,Windows 不介意路径分隔符是正斜杠还是反斜杠。如果您想确定使用了有效的完整路径,您也可以先通过 Resolve-Path 运行此路径,但我通常认为没有必要这样做。

关于Powershell Core + Pester - 将测试与 src 分开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65160262/

相关文章:

Powershell 全选 Word Doc

powershell - 对Foreach对象的错误处理

powershell - 您不能在空值表达式上调用方法 - 一般

azure-cli - 如何传递带空格的标签

c# - 使用 SimpleInjector 的二进制 PowerShell Core cmdlet 导致 FileNotFoundException

powershell - 将元素插入嵌套在哈希表中的数组中

php - 用于单元测试的模拟 php 资源类型

javascript - 如何替换 Polymer 中的元素和 stub 方法

java - Sonar Java : check the quality of the test classes source code?

powershell - 如何防止 PowerShell 7 Write-Error 按字面写回文本 "Write-Error"?