让我举个例子:
首先是您的包装文件,如下所示:src\Do-Somethin.ps1
Function Get-Foobar() {
Return "This is a sample text"
}
然后让我们看一下pester文件tests\Do-Something.Tests.ps1
#region HEADER
$here = Split-Path -Parent $MyInvocation.MyCommand.Path
# Keep in mind to adjust `.parent` method based on the directory level of the pester test file.
$RepoRoot = (Get-Item -Path $here).Parent.FullName
$sut = (Split-Path -Leaf $MyInvocation.MyCommand.Path) -replace '\.Tests\.', '.'
$sut = $sut -replace "\d{2}`_", ''
$suthome = (Get-ChildItem -Path $RepoRoot -Exclude '.\tests\' -Filter $sut -Recurse).FullName
# Skip try loading the source file if it doesn't exists.
If ($suthome.Length -gt 0) {
. $suthome
}
Else {
Write-Warning ("Could not find source file {0}" -f $sut)
}
#endregion HEADER
Describe "Do-Something" {
Context "Mocking part" {
Mock Get-Foobar {
"Some mocked text"
}
It "Test1" {
$res = Get-Foobar
Write-Host $res
$res | Should Be "Some mocked text"
}
}
Context "without mocking" {
It "Test2" {
$res = Get-Foobar
Write-Host $res
$res | Should Be "This is a sample text"
}
}
}
然后终于跑了Invoke-Pester .\tests
。
所以你应该得到以下输出:
Describing Do-Something
Context Mocking part
Some mocked text
[+] Test1 81ms
Context without mocking
This is a sample text
[+] Test2 105ms
Tests completed in 186ms
Passed: 2 Failed: 0 Skipped: 0 Pending: 0 Inconclusive: 0