PowerShell + Pester
方針
- PowerShell のサードパーティ フレームワーク
Pesterを使う
前提
- v5.* 系を使う場合はインストール (Install-Module コマンドで NuGet という仕組みで入るらしい)
- v3.* 系はデフォルトで入っているようだが、試していない
ps1
Install-Module Pester -Force -Scope CurrentUser -SkipPublisherCheck
-SkipPublisherCheck をつけている理由:
Windows に同梱の Microsoft 署名 Pester(例: 3.4.0)と、PSGallery から入る Pester の発行者が違うので警告され、続行には -SkipPublisherCheck が必要になることがある。
プロジェクト作成
bat
mkdir $HOME\workdir\SamplePowerShell
cd $HOME\workdir\SamplePowerShell
code .
最小のコード
sample.ps1
function Add {
param(
[int]$a,
[int]$b
)
return $a + $b
}
sample.Tests.ps1
BeforeAll {
. "$PSScriptRoot\..\sample.ps1"
}
Describe 'Add' {
It 'adds two and three' {
Add 2 3 | Should -Be 5
}
}
決まりごと
- ファイル名 :
*.Tests.ps1がデフォルトのテストファイル扱い - テスト構造 :
Describe .. It - 検証 :
Should -Be <期待する結果>
いわゆる BDD 方式
実行
ps1
Import-Module Pester -PassThru
Invoke-Pester
→ これで カレントディレクトリ以下 *.Tests.ps1 を探して実行してくれる
-Output Detailed をつけると詳細が出るようだが、あまり変わってないように見える
表示例
成功時
txt
Starting discovery in 1 files.
Discovery found 1 tests in 21ms.
Running tests.
[+] sample.Tests.ps1 80ms (14ms|51ms)
Tests completed in 87ms
Tests Passed: 1, Failed: 0, Skipped: 0, Inconclusive: 0, NotRun: 0
失敗時
txt
Starting discovery in 2 files.
Discovery found 1 tests in 20ms.
Running tests.
[-] Add.adds two and three 4ms (3ms|1ms)
at Add 2 4 | Should -Be 5, ....\test\sample.Tests.ps1:8
...
Expected 5, but got 6.
Tests completed in 75ms
Tests Passed: 0, Failed: 1, Skipped: 0, Inconclusive: 0, NotRun: 0
以下広告