使用Pester测试PowerShell模块,我的模拟函数不会返回值

时间:2015-12-08 23:33:10

标签: powershell mocking pester

我正在使用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,并且可以判断出一些不同的东西。

当用字符串模拟调用它时 - 一切都很好。

当使用数组模拟调用它时 - 它什么都不返回,甚至不返回文件和目录的标准列表..所以看起来模拟器正在做某事。

我试图找出为什么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"} } 

我测试的系统中的调用开始返回预期值,与返回普通字符串相同。

使用引导逗号并不起作用,并且施放应该呼叫也不起作用。

2 个答案:

答案 0 :(得分:1)

如何转换为System.IO.DirectoryInfo

Get-HighestBuildNumber -buildRoot "C:\my\test\directory" | Should Be @([System.IO.DirectoryInfo]"12348")

或使用“名称”属性

return $fakeListingOfDirectories.Name

答案 1 :(得分:1)

我不在我可以测试它的机器上,但 $start = date('c', $row['start_time']); while (strtotime($end) < $row['end_time']){ $title = 'Teacher Available'; $color = '#a3a3a3'; $end = date('c', strtotime($start) + hoursToSeconds($row_Branch['session'])); $allday = ($row['allDay'] == "1") ? true : false; if (in_array($start, $input_arrays) == false){ $input_arrays[]= array(title => $title, start => $start, end => $end, color => $color, allDay => $allday); } $start = date('c', strtotime($end)); } 脚本块可能与Mock {}脚本块不在同一范围内。我会像这样重写你的Describe {}块:

Describe{}