【发布时间】:2020-01-10 20:56:16
【问题描述】:
我在 IIS 方法 Get-IISSite 的两个不同 It '' 块中设置了两个 Mocks...
我遇到的问题是它通过了这两个,但是当我尝试做一个不使用模拟的常规测试时(它在相同的'上下文中是一个新的'it'),该方法即使在将其分开。我在另一个页面上阅读了一些文档,表明父母可以使用 Mocks(相同的上下文)
这让我有点担心,因为我希望找到一种机制来处理一旦它不再需要它内部的模拟来恢复它。是否有必要在单独的描述和/或上下文中具有相同功能的非模拟? (肯定是这样的)
代码如下:
编写了一个方法来包装对 Get-IISSite 的空调用
### Get all IIS website collection
function IIS-SiteGetAll() {
$sites = Get-IISSite
if ($sites.Length -eq 0 -or $sites -eq $null) {
throw 'No IIS Sites found, please check that IIS is installed and service is running.'
}
return $sites
}
测试片段
Describe 'IIS Site Methods' {
Context 'IIS-SiteGetAll (mocked)' {
It 'Throws error if number of sites returned is 0' {
# Get-IISSite is the Powershell ISS command, we want it to return an empty collection
Mock -CommandName Get-IISSite {
return @()
}
{ IIS-SiteGetAll } | Should Throw
}
It 'Throws error if number of sites returned is $null' {
# Get-IISSite is the Powershell ISS command, we want it to return an empty collection
Mock -CommandName Get-IISSite {
return $null
}
{ IIS-SiteGetAll } | Should Throw
}
It 'Returns collection of sites' { #IIS-SiteGetAll fails because it points to one of the two Mocks in the It above
$actual = IIS-SiteGetAll
$actual | Should -BeOfType [Microsoft.Web.Administration.Site]
$actual.Length | Should -BeGreaterThan 0
}
}
Context 'IIS-SiteGetAll' {
It 'Returns collection of sites' { # This separate chain exact same test passes.
$actual = IIS-SiteGetAll
$actual | Should BeOfType [Microsoft.Web.Administration.Site]
$actual.Length | Should -BeGreaterThan 0
}
}
}
注意 powershell 有点模糊,因为如果您对第二个实际执行 GetType,它会显示为 Object[],BaseType 为 System.Array(但失败)只有 [Microsoft.Web.Administration.Site] 输出类似乎可以与此处的文档匹配:https://docs.microsoft.com/en-us/powershell/module/iisadministration/get-iissite?view=win10-ps
我不知道另一种解决方法,但我必须在博客中找到答案,而不是在 Pester 的文档中。
【问题讨论】:
-
当然,我通常不会在
It块中创建Mock;我会做你在这里所做的,并为它创建一个单独的Context。您可以在 Pester 中使用一个AfterEach块,该块将在每个It块之后运行,但您需要先知道如何删除 Mock 才能使用它... -
你能把这个作为答案提交给我吗,这正是我最终不得不做的事情
标签: powershell unit-testing mocking pester