今天繼續學習Pester,invoke-pester有一個很nb的選項叫codeCoverage,可以指定需要測試的腳本,function甚至某一個片段的範圍,然後他會告訴你這個範圍内的功能是否都測試過了。
來個執行個體看看,豆子直接在上一篇的腳本裡面添加了一個switchtest的function,然後測試了其中一個if的功能
Test.ps1
function add {
param(
[int]$a,
[int]$b
)
$sum=$a+$b
$sum
}
function switchtest{
param(
[switch]$switch
)
if($switch){
return "Switch is On"
}
else{
return "Switch is Off"
}
}
Test.tests.ps1
$here = Split-Path -Parent $MyInvocation.MyCommand.Path
$sut = (Split-Path -Leaf $MyInvocation.MyCommand.Path) -replace '\.Tests\.', '.'
. "$here\$sut"
Describe "Test" {
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
}
It "Test Switch option"{
switchtest -switch | Should be "Switch is on"
}
}
Context "Should BeExactly test"{
It "HostName" {
hostname | Should beexactly "yli-ise"
}
}
Context "Should BeGreaterThan test"{
It "PsVersion is above 3" {
$PSVersionTable.PSVersion.Major | Should beGreaterThan 3
}
}
Context "Should beOfType test"{
It "Get-ADUser type"{
Get-aduser yli | Should beoftype Microsoft.ActiveDirectory.Management.ADUser
}
}
Context "Should Exist test"{
It "C:\temp exist"{
"c:\temp" | should exist
}
}
Context "Should match test"{
It "Find Email"{
"jksjsjsjssdjs [email protected] 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])?"
}
}
Context "Should Throw test" {
It "Get a non-exist Process"{
{Get-Process -Name "!@#$%&" -ErrorAction Stop} | Should Throw
}
}
Context "Should BeNullorEmpty test"{
It "Get something from test folder"{
get-childitem C:\temp | should not benullorempty
}
}
}
執行看看,最後他告訴我在我指定的腳本裡面,隻完成了80%的測試,因為if語句的還有一個分支我沒有測試
![](https://img.laitimes.com/img/_0nNw4CM6IyYiwiM6ICdiwiIn5GcuEjM2k1RZpFOKhWREFUQWVjMnF0SLhmakFDTvl2S39CXGR0LcJDOvwVMw00LcJDMzZWe39CXt92Yu8GdjFTNuUzcvw1LcpDc0RHaiojIsJye.png)