豆子之前初步了解了Pester的基本功能,今天繼續看看。Pester里面有個很重要的概念叫 assertion (斷言),他的作用是通過Should這個關鍵字 (function)來定義預測應該出現的結果。
這個shoud后面的操作符有以下幾種
Be
BeExactly
BeGreaterThan
BeLessThan
BeLike
BeLikeExactly
BeOfType
Exist
Contain
ContainExactly
Match
MatchExactly
Throw
BeNullOrEmpty
下面這個鏈接有相關的wiki說明,有興趣的可以看看
https://github.com/pester/Pester/wiki/Should
這些關鍵字操作符從名字都能猜的出是干啥的,下面給幾個實例看看怎么用。
比如在一個test.ps1里面寫一個簡單求和功能
function add {
param(
[int]$a,
[int]$b
)
$sum=$a+$b
$sum
}對應的test.tests.ps1 里面這么寫
$here = Split-Path -Parent $MyInvocation.MyCommand.Path
$sut = (Split-Path -Leaf $MyInvocation.MyCommand.Path) -replace '\.Tests\.', '.'
. "$here\$sut"
Describe "Test" {
#Shoud Be 比較結果是否一樣,不區分大小寫
Context "Should be test"{
It "Add 1 and 2 is equal to 3" {
add 1 2 | Should Be 3
}
It "Add -1 and 2 is not equal to 0" {
add -1 2 | Should not Be 0
}
}
#should be Exactly 比較結果是否一樣,區分大小寫
Context "Should BeExactly test"{
It "HostName" {
hostname | Should beexactly "yli-ise"
}
}
#Should BeGreaterThan判斷得到的結果是否比預定值大
Context "Should BeGreaterThan test"{
It "PsVersion is above 3" {
$PSVersionTable.PSVersion.Major | Should beGreaterThan 3
}
}
#Should beoftype判斷結果類型是否為指定類型
Context "Should beOfType test"{
It "Get-ADUser type"{
Get-aduser yli | Should beoftype Microsoft.ActiveDirectory.Management.ADUser
}
}
#Should Exist判斷文件是否存在
Context "Should Exist test"{
It "C:\temp exist"{
"c:\temp" | should exist
}
}
#Should match 判斷結果是否匹配正則表達式, 不區分大小寫
Context "Should match test"{
It "Find Email"{
"jksjsjsjssdjs abc.xyz@yahoo.com hsosofs" | should match "[a-z0-9!#\$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#\$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?"
}
}
#Should Throw 判斷script block結果是否拋出異常
Context "Should Throw test" {
It "Get a non-exist Process"{
{Get-Process -Name "!@#$%&" -ErrorAction Stop} | Should Throw
}
}
#Should BeNulorEmpty 判斷結果是否為空
Context "Should BeNullorEmpty test"{
It "Get something from test folder"{
get-childitem C:\temp | should not benullorempty
}
}
}直接運行這個測試文件或者通過Invoke-pester執行,看看結果 成功

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。