豆子之前初步了解了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里面写一个简单求和功能


functionadd{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"{#ShoudBe比较结果是否一样,不区分大小写Context"Shouldbetest"{It"Add1and2isequalto3"{add12|ShouldBe3}It"Add-1and2isnotequalto0"{add-12|ShouldnotBe0}}#shouldbeExactly比较结果是否一样,区分大小写Context"ShouldBeExactlytest"{It"HostName"{hostname|Shouldbeexactly"yli-ise"}}#ShouldBeGreaterThan判断得到的结果是否比预定值大Context"ShouldBeGreaterThantest"{It"PsVersionisabove3"{$PSVersionTable.PSVersion.Major|ShouldbeGreaterThan3}}#Shouldbeoftype判断结果类型是否为指定类型Context"ShouldbeOfTypetest"{It"Get-ADUsertype"{Get-aduseryli|ShouldbeoftypeMicrosoft.ActiveDirectory.Management.ADUser}}#ShouldExist判断文件是否存在Context"ShouldExisttest"{It"C:\tempexist"{"c:\temp"|shouldexist}}#Shouldmatch判断结果是否匹配正则表达式,不区分大小写Context"Shouldmatchtest"{It"FindEmail"{"jksjsjsjssdjsabc.xyz@yahoo.comhsosofs"|shouldmatch"[a-z0-9!#\$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#\$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?"}}#ShouldThrow判断scriptblock结果是否抛出异常Context"ShouldThrowtest"{It"Getanon-existProcess"{{Get-Process-Name"!@#$%&"-ErrorActionStop}|ShouldThrow}}#ShouldBeNulorEmpty判断结果是否为空Context"ShouldBeNullorEmptytest"{It"Getsomethingfromtestfolder"{get-childitemC:\temp|shouldnotbenullorempty}}}


直接运行这个测试文件或者通过Invoke-pester执行,看看结果 成功