Pester: Testing endlessly looping function

Welcome Forums General PowerShell Q&A Pester: Testing endlessly looping function

This topic contains 1 reply, has 2 voices, and was last updated by

3 years, 8 months ago.

  • Author
  • #29013

    Topics: 4
    Replies: 19
    Points: 0
    Rank: Member

    Hey guys,

    I hope you can help me figure out how to test my New-FileSystemWatcher properly.

    As you can see the function is used in a psake build file to continuously monitor a directory for changes. When a change is detected a pester test is run. You can exit the loop with Ctrl+C.

    Is the only option to test the FileSystemWatcher function to mock it's functionality? Thanks in advance!

  • #29138

    Topics: 9
    Replies: 2322
    Points: 0
    Rank: Member

    That's tricky. As you say, your function runs forever, which isn't good for being testable. And even if it didn't run forever, you'd also need to run some code in parallel (one to run the filesystemwatcher, and another to make some file system changes). That's doable, but you have to be careful that timing doesn't cause your tests to fail. If you add a timeout parameter to your function, something along these lines should work:

    It 'Should return the proper result object for creation' {
        $job = Start-Job -ScriptBlock { Start-Sleep -Milliseconds 500; New-Item -Path "$($args[0])\file.txt" } -ArgumentList $TestDrive
        $result = New-FileSystemWatcher -Path $TestDrive -Timeout 2000 # -Timeout parameter doesn't exist yet, but you get the idea
        $job | Wait-Job | Remove-Job | Out-Null
        $path = Join-Path $TestDrive file.txt
        $matchingResult = $result | Where { $_.Path -eq $Path -and $_.OperationResult -eq 'Created' }
        $matchingResult | Should Not Be $null

The topic ‘Pester: Testing endlessly looping function’ is closed to new replies.

denizli escort samsun escort muğla escort ataşehir escort kuşadası escort