Pester重置测试数据

时间:2017-11-22 11:01:17

标签: unit-testing powershell pester

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

我有2个It块用于我的pester测试,检查2个场景 - 密钥存在且密钥不存在。我希望为每个$ht块重新创建It,但如果我交换2 It的顺序,那么Returns existing entry when passed existing key失败是因为$ht.count仍然是3。<​​/ p>

有没有办法让$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
    }
}

1 个答案:

答案 0 :(得分:0)

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

我建议在每次测试之前使用Function设置哈希表:

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
    }
}