[英]Using Pester to test a PowerShell module, my mocked function doesnt return a value
我正在使用Pester,一个PowerShell测试库来帮助进行TDD /单元测试覆盖。
我正在尝试模拟Get-ChildItem我在模块中进行的测试应该进行环境设置。 如果我有我的模拟Get-ChildItem函数返回一个普通字符串它工作正常但如果我有它返回此数组,它不会返回任何东西。
Describe "Get-HighestBuildNumber" {
Context "Get-ChildItem mocked to returns 12345, 12346, 12348, Foobar12349" {
$directory1 = New-Object -TypeName System.IO.DirectoryInfo -ArgumentList "12345"
$directory2 = New-Object -TypeName System.IO.DirectoryInfo -ArgumentList "12346"
$directory3 = New-Object -TypeName System.IO.DirectoryInfo -ArgumentList "12348"
$directory4 = New-Object -TypeName System.IO.DirectoryInfo -ArgumentList "Foobar12349"
$fakeListingOfDirectories = @( $directory1, $directory2, $directory3, $directory4 )
Mock -ModuleName EnvironmentSetup Get-ChildItem {
#return "this return text works" #this works
return $fakeListingOfDirectories #this return array does not work
}
it "should return 12348" {
Get-HighestBuildNumber -buildRoot "C:\my\test\directory" | Should Be "12348"
}
}
}
在测试中的代码中,我设置了一个断点并调用了模拟的Get-ChildItem并且可以告诉它有什么不同。
当它用字符串模拟调用时 - 一切都很好。
当使用数组mock调用它时 - 它什么都不返回,甚至不返回文件和目录的标准列表..所以看起来模拟器正在做某事。
我试图弄清楚为什么Get-ChildItem没有返回我的DirectoryInfo项目数组。
谢谢!
编辑:当我改变时:
Mock -ModuleName EnvironmentSetup Get-ChildItem {
return $fakeListingOfDirectories #this return array does not work
}
返回不同的文字:
Mock Get-ChildItem -ModuleName NavEnvironmentSetup { return @{Name = "12345"}, @{Name = "12346" }, @{Name = "12348"}, @{Name = "Foobar12349"} }
我测试的系统中的调用开始返回预期值,与返回普通字符串相同。
使用前导逗号不起作用,并且施放应该调用也不起作用。
如何转换为System.IO.DirectoryInfo
Get-HighestBuildNumber -buildRoot "C:\my\test\directory" | Should Be @([System.IO.DirectoryInfo]"12348")
或使用“名称”属性
return $fakeListingOfDirectories.Name
?
我不在我可以测试它的机器上,但是Mock {}
scriptblock可能与Describe {}
scriptblock不在同一范围内。 我会像这样重写你的Describe{}
块:
Describe "Get-HighestBuildNumber" {
Context "Get-ChildItem mocked to returns 12345, 12346, 12348, Foobar12349" {
Mock -ModuleName EnvironmentSetup Get-ChildItem {
@(
"12345","12346","12348","Foobar12349" |
% { New-Object System.IO.DirectoryInfo($_) }
)
}
it "should return 12348" {
Get-HighestBuildNumber -buildRoot "C:\my\test\directory" | Should Be "12348"
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.