您好,登錄后才能下訂單哦!
豆子之前初步了解了Pester的基本功能,今天繼續(xù)看看。Pester里面有個很重要的概念叫 assertion (斷言),他的作用是通過Should這個關(guān)鍵字 (function)來定義預(yù)測應(yīng)該出現(xiàn)的結(jié)果。
這個shoud后面的操作符有以下幾種
Be
BeExactly
BeGreaterThan
BeLessThan
BeLike
BeLikeExactly
BeOfType
Exist
Contain
ContainExactly
Match
MatchExactly
Throw
BeNullOrEmpty
下面這個鏈接有相關(guān)的wiki說明,有興趣的可以看看
https://github.com/pester/Pester/wiki/Should
這些關(guān)鍵字操作符從名字都能猜的出是干啥的,下面給幾個實例看看怎么用。
比如在一個test.ps1里面寫一個簡單求和功能
function add { param( [int]$a, [int]$b ) $sum=$a+$b $sum }
對應(yīng)的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 比較結(jié)果是否一樣,不區(qū)分大小寫 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 比較結(jié)果是否一樣,區(qū)分大小寫 Context "Should BeExactly test"{ It "HostName" { hostname | Should beexactly "yli-ise" } } #Should BeGreaterThan判斷得到的結(jié)果是否比預(yù)定值大 Context "Should BeGreaterThan test"{ It "PsVersion is above 3" { $PSVersionTable.PSVersion.Major | Should beGreaterThan 3 } } #Should beoftype判斷結(jié)果類型是否為指定類型 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 判斷結(jié)果是否匹配正則表達(dá)式, 不區(qū)分大小寫 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結(jié)果是否拋出異常 Context "Should Throw test" { It "Get a non-exist Process"{ {Get-Process -Name "!@#$%&" -ErrorAction Stop} | Should Throw } } #Should BeNulorEmpty 判斷結(jié)果是否為空 Context "Should BeNullorEmpty test"{ It "Get something from test folder"{ get-childitem C:\temp | should not benullorempty } } }
直接運行這個測試文件或者通過Invoke-pester執(zhí)行,看看結(jié)果 成功
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。