Skip to content

Instantly share code, notes, and snippets.

@stknohg
Last active November 1, 2017 04:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stknohg/4f3ebc9ccf94c66f926ff0c3224c87ed to your computer and use it in GitHub Desktop.
Save stknohg/4f3ebc9ccf94c66f926ff0c3224c87ed to your computer and use it in GitHub Desktop.
Pesterでカスタムアサーションを行うサンプル(Pester 4.0.5以前)
# 参考 http://kamranicus.com/blog/2016/08/17/posh-pester-extend-custom-assertions/
# Pester 3.4.0 で検証済み
Import-Module Pester
# Pester + 動詞 の名前を持つ3つの関数を作る必要がある
# 1. Pester[動詞]
function PesterBeHash($Value, $Expected) {
if (-not ($Value -is [Hashtable] -and $Expected -is [Hashtable])) {
return $Value -eq $Expected
}
if ($Value.Keys.Count -ne $Expected.Keys.Count) {
return $false
}
foreach ($key in $Value.Keys) {
if ($Value[$key] -ne $Expected[$key]) {
return $false
}
}
return $true
}
# 2. Pester[動詞]FailureMessage
Function PesterBeHashFailureMessage($Value, $Expected) {
$e = ""
if ($Expected -is [Hashtable]) {
foreach ($key in $Expected.Keys) {
if ($e -ne "") { $e += ";" }
$e += "{0}={1}" -f $key, $Expected[$key]
}
} else {
$e = "[{0}] {1}" -f ($Expected.GetType()), [string]$Expected
}
$v = ""
if ($Value -is [Hashtable]) {
foreach ($key in $Value.Keys) {
if ($v -ne "") { $v += ";" }
$v += "{0}={1}" -f $key, $Value[$key]
}
} else {
$v = "[{0}] {1}" -f ($Value.GetType()), [string]$Value
}
return "Expected: {0}`nBut was: {1}" -f $e, $v
}
# 3. NotPester[動詞]FailureMessage
Function NotPesterBeHashFailureMessage($Value, $Expected) {
return PesterBeHashFailureMessage -Value $Value -Expected $Expected
}
Describe "カスタムアサーションのサンプル" {
# Should Be ではハッシュは比較できない
It "通常のアサーションで失敗する例" {
@{ Name = "田中"; Salary = 300 } | Should Be @{ Name = "田中"; Salary = 300 }
}
# カスタムアサーションでハッシュを比較してみる
It "カスタムアサーション成功例" {
@{ Name = "田中"; Salary = 300 } | Should BeHash @{ Name = "田中"; Salary = 300 }
}
It "カスタムアサーション失敗例" {
@{ Name = "鈴木"; Salary = 300 } | Should BeHash @{ Name = "田中"; Salary = 300 }
}
}
@stknohg
Copy link
Author

stknohg commented Nov 1, 2017

Pester 4.0.5から正式にカスタムアサーションができる様になりました。
Pester 4.0.5以降の例はこちら。

Pesterでカスタムアサーションを行うサンプル(Pester 4.0.5以降)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment