Pester: Testing endlessly looping function

This topic contains 1 reply, has 2 voices, and was last updated by Profile photo of Dave Wyatt Dave Wyatt 1 year, 1 month ago.

Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
  • #29013
    Profile photo of Sebastian Neumann
    Sebastian Neumann

    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!

    Profile photo of Dave Wyatt
    Dave Wyatt

    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
Viewing 2 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic.