使用Pester和Powershell编写一些测试
代码:
Import-Module Module
Import-Module Pester
InModuleScope Module{
Describe 'Add-Patchgroup' {
Context 'Add_server_to_group_fail' {
Mock Add-ADGroupMember {throw [ADIdentityNotFoundException]}
It 'NotCorrectNamingConvention' {
{Add-Patchgroup -ComputerName "NotExistingServer" | Should -BeLike "WARNING: Could not reach*"}
}
It 'CorrectNamingConventionNotExistingServer' {
{Add-Patchgroup -ComputerName "<nameOfTheServer>" | Should -Throw}
}
Assert-MockCalled Add-ADGroupMember -Exactly 1
}
}
}
并获得以下输出:
Context Add_server_to_group_fail
[+] NotCorrectNamingConvention 41ms
[+] CorrectNamingConventionNotExistingServer 5ms
[-] Error occurred in Context block 56ms
Expected Add-ADGroupMember in module PsLeanOps to be called 1 times exactly but was called 0 times
25: Assert-MockCalled Add-ADGroupMember -Exactly 1
at <ScriptBlock>, C:\Users\a.antr01\Desktop\AddPatchGroups.Tests.ps1: line 25
at DescribeImpl, C:\Users\a.antr01\Documents\WindowsPowerShell\Modules\pester\Functions\Describe.ps1: line 171
为什么没有嘲笑Add-ADGroupMember
?
要澄清:
Module
-模块名称
Add-Patchgroup
-PSLeanOps
中的功能
Add-ADGroupMember
-Add-Patchgroup
编辑
如TheIncorrigible1所说修改了代码。这是最终代码:
Mock Add-ADGroupMember {throw [Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException]::new()}
It 'CorrectNamingConventionNotExistingServer' {
{Add-Patchgroup -ComputerName "<nameOfTheServer>" -ErrorAction Stop} | Should -Throw -ExceptionType "Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException"
}
Assert-MockCalled Add-ADGroupMember -Exactly 1
答案 0 :(得分:1)
问题在于您的主张。除非您正在使用-Throw
,否则它们不应位于脚本块中,但即使如此,也只能使用以下命令:
It 'NotCorrectNamingConvention' {
Add-Patchgroup -ComputerName "NotExistingServer" | Should -BeLike "WARNING: Could not reach*"
}
It 'CorrectNamingConventionNotExistingServer' {
{ Add-Patchgroup -ComputerName "ATVT1WWFYC050" } | Should -Throw
}
顺便说一句,您是否在代码中包含using namespace
语句或添加了类型加速器? [ADIdentityNotFoundException]
应该抛出类型未找到的异常(并且可能被调用两次,因为您两次调用了该函数)。