Pester: Testing endlessly looping function

This topic contains 1 reply, has 2 voices, and was last updated by  Dave Wyatt 2 years, 3 months ago.

  • Author
    Posts
  • #29013

    Sebastian Neumann
    Participant

    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

    Dave Wyatt
    Moderator

    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
    }
    

You must be logged in to reply to this topic.