Last active
November 1, 2017 04:28
-
-
Save stknohg/4f3ebc9ccf94c66f926ff0c3224c87ed to your computer and use it in GitHub Desktop.
Pesterでカスタムアサーションを行うサンプル(Pester 4.0.5以前)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 参考 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 } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Pester 4.0.5から正式にカスタムアサーションができる様になりました。
Pester 4.0.5以降の例はこちら。
Pesterでカスタムアサーションを行うサンプル(Pester 4.0.5以降)