纠缠重置测试数据

Pester reset test data

这是关于pester中测试数据的范围。我正在测试一个函数 Add-HashTableIfNotPresent,它检查哈希表中是否存在键,如果不存在则添加它,否则它 returns 链接到该键的值。

我的 pester 测试有 2 个 It 块,用于检查 2 个场景 - 密钥存在和密钥不存在。我期望为每个 It 块重新创建 $ht 但事实并非如此,如果我交换我的 2 It 的顺序然后 Returns existing entry when passed existing key 失败,因为 $ht.count还是3.

是否有办法为每个测试重置 $ht,或者我是否需要在 It 块中定义它?

正在测试的功能:

function Add-HashTableIfNotPresent {
    [CmdletBinding()]
    param(
        [hashtable] $sourceTable,
        [string] $keyToCheck
    )

    $subTable = $sourceTable.$keyToCheck
    if(-not $subTable){
        $subTable = @{}
        $sourceTable.$keyToCheck = $subTable
    }
}

测试代码:

Describe 'Add-HashTableIfNotPresent' {
    $ht = @{
        subTable1 = @{
            st1 = "abc"
        }
        subTable2 = @{
            st2 = "def"
        }
    }

    It "Returns existing entry when passed existing key" {
        Add-HashTableIfNotPresent -sourceTable $ht -keyToCheck subTable2
        $ht.Count | Should BeExactly 2
        $value = $ht.subTable2
        $value.count | Should BeExactly 1
        $value.st2 | Should -Be "def"
    }

    It "Adds entry that doesn't exist" {
        Add-HashTableIfNotPresent -sourceTable $ht -keyToCheck subTable3
        $ht.Count | Should BeExactly 3
        $addedValue = $ht.subTable3
        $addedValue | Should -Be $true
        $addedValue.count | Should BeExactly 0
    }
}

ContextDescribe 块的范围意味着在它们中定义的变量仅限于该特定块并且不存在于它之外,但是您的变量仍然不会自动重置每个 It 测试。

我建议在每次测试前使用一个函数来设置你的哈希表:

Function Set-TestHashTable {
    @{
        subTable1 = @{
            st1 = "abc"
        }
        subTable2 = @{
            st2 = "def"
        }
    }
}

Describe 'Add-HashTableIfNotPresent' {

    $ht = Set-TestHashTable

    It "Returns existing entry when passed existing key" {
        Add-HashTableIfNotPresent -sourceTable $ht -keyToCheck subTable2
        $ht.Count | Should BeExactly 2
        $value = $ht.subTable2
        $value.count | Should BeExactly 1
        $value.st2 | Should -Be "def"
    }

    $ht = Set-TestHashTable

    It "Adds entry that doesn't exist" {
        Add-HashTableIfNotPresent -sourceTable $ht -keyToCheck subTable3
        $ht.Count | Should BeExactly 3
        $addedValue = $ht.subTable3
        $addedValue | Should -Be $true
        $addedValue.count | Should BeExactly 0
    }
}