如何正确地纠缠测试 Import-Clixml

How to properly Pester test Import-Clixml

所以首先我需要声明我对 Pester 很陌生,可能没有正确编写我的测试或者没有正确理解它的所有功能。

所以背景是我想用 Pester 自动化我的 PowerShell 模块并且到目前为止已经编写了一些测试。

我的模块的一部分是将配置内容保存在 clixml 文件中。我想编写一组测试以确保保存和抓取配置按预期工作。

基本上我有一个保存配置文件的功能和一个检索配置文件的功能。我的 Pester 测试如下所示:

BeforeAll{
        if(Test-path existingconfigfile.xml){

            Rename-Item -Path "existingconfigfile" -NewName "backup.xml"
        }

        Save-configfunction -param1 'Value1' -param2 'Value2'
        #saves as test.xml
    }

    Afterall{
        if(Test-path backup.xml){

            # Remove mocked test file
            Remove-Item -Path "test.xml" -Force

            # Place original back
            Rename-Item -Path "backup.xml" -NewName "existingconfigfile.xml"
        }
    }

    it "importconfig should return expected values for mocked object" {

        {
            $result = Get-config
            $result
            $result.Containsvalue('Value1') | Should be $true

        }
    }

现在我尝试了 it 块的几个变体:

it "importconfig should return expected values for mocked object" {

        {
            $result = Get-config
            $result.param1 | Should be "Value1"
        }
    }

    it "importconfig should return expected values for mocked object" {
        $result = Get-Config

        $result | Should match 'Value1'
        $result | Should match 'Value2'
    }

    it "importconfig should return expected values for mocked object" {

        $result = Get-Config

        $result.Param1 | Should match 'Value1'
        $result.Param2 | Should match 'Value2'
    }

总是纠缠 returns 通过的测试,即使我将匹配值更改为不正确的值。 Pester 在所有情况下都这样做。因此,出于某种原因,Pester 没有正确限定值,并且总是 returns 一个积极的结果。

所以我想知道我做错了什么。显然,如果值实际匹配,Pester 应该通过测试,但如果它们不匹配,它应该失败。

我认为与其使用 BeforeAllAfterAll 来创建 Mock 类型的行为来修改配置,我认为我会使用实际的 Mock 语句。这就是我的意思(我已经创建了我假设你的函数所做的简单表示,因为你没有共享它们):

function Set-Config {
    Param(
        $Config
    )
    $Config | Export-Clixml C:\Temp\production_config.xml
}

function Get-Config {
    Import-Clixml C:\Temp\production_config.xml
}

Describe 'Config function tests' {

    Mock Set-Config {
        $Config | Export-Clixml TestDrive:\test_config.xml
    }

    Mock Get-Config {
        Import-Clixml TestDrive:\test_config.xml
    }

    $Config = @{
        Setting1 = 'Blah'
        Setting2 = 'Hello'
    }

    It 'Sets config successfully' {
        { Set-Config -Config $Config } | Should -Not -Throw
    }

    $RetrievedConfig = Get-Config

    It 'Gets config successfully' {
        $RetrievedConfig.Setting1 | Should -Be 'Blah'
        $RetrievedConfig.Setting2 | Should -Be 'Hello'
    }
}

这将创建 Get-ConfigSet-Config 函数的模拟,将配置的 write/read 重定向到 TestDrive:\ 这是 Pester 提供并清理的特殊临时磁盘区域之后自动。

请注意,这仅在测试使用这些函数的父函数时才有意义。如果您正在编写 Get-ConfigSet-Config 函数本身的测试,那么您会想要模拟 Export-CliXmlImport-CliXml 命令。