今天继续学习Pester,invoke-pester有一个很nb的选项叫codeCoverage,可以指定需要测试的脚本,function甚至某一个片段的范围,然后他会告诉你这个范围内的功能是否都测试过了。


来个实例看看,豆子直接在上一篇的脚本里面添加了一个switchtest的function,然后测试了其中一个if的功能


Test.ps1

functionadd{param([int]$a,[int]$b)$sum=$a+$b$sum}functionswitchtest{param([switch]$switch)if($switch){return"SwitchisOn"}else{return"SwitchisOff"}}


Test.tests.ps1

$here=Split-Path-Parent$MyInvocation.MyCommand.Path$sut=(Split-Path-Leaf$MyInvocation.MyCommand.Path)-replace'\.Tests\.','.'."$here\$sut"Describe"Test"{Context"Shouldbetest"{It"Add1and2isequalto3"{add12|ShouldBe3}It"Add-1and2isnotequalto0"{add-12|ShouldnotBe0}It"TestSwitchoption"{switchtest-switch|Shouldbe"Switchison"}}Context"ShouldBeExactlytest"{It"HostName"{hostname|Shouldbeexactly"yli-ise"}}Context"ShouldBeGreaterThantest"{It"PsVersionisabove3"{$PSVersionTable.PSVersion.Major|ShouldbeGreaterThan3}}Context"ShouldbeOfTypetest"{It"Get-ADUsertype"{Get-aduseryli|ShouldbeoftypeMicrosoft.ActiveDirectory.Management.ADUser}}Context"ShouldExisttest"{It"C:\tempexist"{"c:\temp"|shouldexist}}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])?"}}Context"ShouldThrowtest"{It"Getanon-existProcess"{{Get-Process-Name"!@#$%&"-ErrorActionStop}|ShouldThrow}}Context"ShouldBeNullorEmptytest"{It"Getsomethingfromtestfolder"{get-childitemC:\temp|shouldnotbenullorempty}}}


执行看看,最后他告诉我在我指定的脚本里面,只完成了80%的测试,因为if语句的还有一个分支我没有测试



改变一下脚本的范围,只测试16-18行的内容,那么最后报告表示选择范围的功能已经100%测试过了