如何使用pester测试框架编写一个小测试函数

How to write a small test function using pester testing framework

如何使用pester测试框架编写一个小测试函数

function SaveStudent($Student){
 Write-Host "save student email for $($Student.Email)
 return $Student 
}

我们使用 pester 框架编写了示例测试函数,并在本地环境中进行了测试。 下面是示例 Get-Something 函数,这里是函数模块:

    function Get-Something {    
    [CmdletBinding()]
    param (
        [Parameter()]
        [string]
        $ThingToGet
    )
 
    if ($PSBoundParameters.ContainsKey('ThingToGet')) {
        Write-Output "I got $ThingToGet!"
    }
    else {
        Write-Output "I got something!"
    }
}

这里是功能模块测试用例

Describe "Get-Something" {
    Context "when parameter ThingToGet is not used" {
        It "should return 'I got something!'" {
            Get-Something | Should -Be 'I got something!'
        }
    }
 
    Context "when parameter ThingToGet is used" {
        It "should return 'I got ' follow by a string" {
            $thing = 'a dog'
            Get-Something -ThingToGet $thing | Should -Be "I got $thing!"
        }
    }
}

有关更多信息,您可以参考这个 blog or pester documentation to Quick start with pester testing frame work。