繁体   English   中英

使用 Pester 5.3.3 进行测试

[英]Testing with Pester 5.3.3

我编写了一个函数来将函数中发生的错误写入 csv 文件,该函数在函数的 catch 块中调用。 我想在 Pester 中编写一个测试来检查我的功能是否正常工作,但老实说我不知道​​从哪里开始,我尝试了一些东西但它们对我不起作用,我也一直在阅读文档,但我仍然不清楚,我将不胜感激任何帮助/意见。

这是我想在 Pester 中编写测试的函数:

function Write-Logs {
    param (
        [ValidateSet("Error")]$MessageType,
        [string][Parameter(Mandatory=$true)]$Message,
        $LogFilePath,
        $Source
    )
    $CSVLogPath = Join-Path -Path $PSScriptRoot -ChildPath ".\errorslog.csv"
    $CSVLogObject = [PSCustomObject] @{
        Date = Get-Date
        Message = $Message
        MessageType = $MessageType
        Source = $Source
    }
    $CSVLogObject | Export-Csv -Path $CSVLogPath -NoTypeInformation -Encoding UTF8 -Append
}

所以我在 catch 块中调用函数:

    catch {
        Write-Logs -LogFilePath:$CSVLogPath -Message:$Error[0].Exception.Message `
        -Source:"FunctionName()" -MessageType:"Error"
        return
    }

继续我的评论,这里有一些代码。

首先通过实际使用-LogFilePath参数使函数可测试。 这样,您可以在测试期间将日志写入临时文件。 由于默认值,当从普通代码调用它时,您仍然可以在没有-LogFilePath的情况下使用它。

function Write-Logs {
    param (
        [ValidateSet("Error")]$MessageType,
        [string][Parameter(Mandatory=$true)]$Message,
        $LogFilePath = (Join-Path -Path $PSScriptRoot -ChildPath ".\errorslog.csv"),
        $Source
    )
    $CSVLogObject = [PSCustomObject] @{
        Date = Get-Date
        Message = $Message
        MessageType = $MessageType
        Source = $Source
    }
    $CSVLogObject | Export-Csv -Path $LogFilePath -NoTypeInformation -Encoding UTF8 -Append
}

测试代码:

BeforeAll {
    . $PSCommandPath.Replace('.Tests.ps1','.ps1')
}

Describe "Write-Logs" {
    BeforeEach{
        # Mock Get-Date so it returns a constant value suitable for testing
        $expectedDate = [DateTime]::new( 2022, 06, 28, 12, 36, 21 )
        Mock Get-Date { return $expectedDate }
    }   

    It "writes the expected CSV" {
    
        # You might read this from a file using Import-Csv
        $expectedCsv = [PSCustomObject]@{
            Date = $expectedDate
            Message = 'test message'
            MessageType = 'Error'
            Source = 'test source'
        }

        # Write log to temp file (Pester cleans it automatically, when It block ends)
        $testLogPath = "TestDrive:\test.log"
        Write-Logs -LogFilePath $testLogPath -MessageType $expectedCsv.MessageType -Message $expectedCsv.Message -Source $expectedCsv.Source

        $actualCsv = Import-Csv $testLogPath

        # Test if $expectedCsv equals $actualCsv
        Compare-Object $expectedCsv $actualCsv -Property Date, Message, MessageType, Source | Should -BeNullOrEmpty
    }
}
  • TestDrive:是 Pester 为每个脚本块创建的临时驱动器。 编写临时文件非常方便,因为 Pester 会在脚本块结束时自动清理它。 请参阅纠缠文档
  • 一旦您完成了一些基本测试,您可能希望通过使用数据驱动测试来改进您的测试代码。 这避免了重复,因为您只需要一个可以从不同数据集提供的测试。 请参阅Pester 文档,尤其是“为测试提供外部数据”部分。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM