Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Can't mock Out-File #1617

Closed
drache42 opened this issue Jun 25, 2020 · 1 comment
Closed

Can't mock Out-File #1617

drache42 opened this issue Jun 25, 2020 · 1 comment

Comments

@drache42
Copy link

1. General summary of the issue

Mocking Out-File doesn't do anything and original Out-File is still called.

2. Describe Your Environment

Pester version : 5.0.2 C:\Users\sfroehlich\Documents\PowerShell\Modules\Pester\5.0.2\Pester.psd1
PowerShell version : 7.0.2
OS version : Microsoft Windows NT 10.0.18362.0

3. Expected Behavior

When mocking Out-File it should not call the built in Out-File and try to write to disk

Example code that repros the issue

Describe 'Test-Out-File' {    
    BeforeAll{
        Mock Out-File { }
    }

    Context 'Testing Out-File' {

        "Hello World" | Out-File 'c:\test.txt'

        It 'Should work' {
            Assert-MockCalled Out-File -Exactly 1 
        }
    }
}

The above code fails at "Hello World" | Out-File 'c:\test.txt' with error

System.UnauthorizedAccessException: Access to the path 'C:\test.txt' is denied.
   at System.IO.FileStream.ValidateFileHandle(SafeFileHandle fileHandle)
   at System.IO.FileStream.CreateFileOpenHandle(FileMode mode, FileShare share, FileOptions options)
   at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options)

4.Current Behavior

It tries to write to disk, fails because it doesn't have access

5. Possible Solution

6. Context

@asears
Copy link
Contributor

asears commented Jun 29, 2020

Pester 5 has a change to require code to be within BeforeAll/BeforeEach/AfterAll/AfterEach blocks or within the It context.

This seems to be ok.

Describe 'Test-Out-File' {    
    BeforeAll {
        Mock Out-File { }
    }

    Context 'Testing Out-File' {

        It 'Should work' {
            "Hello World" | Out-File 'c:\test.txt'
            Assert-MockCalled Out-File -Exactly 1 
        }
    }
}

Also see:

https://dsccommunity.org/blog/converting-tests-to-pester5/
#1319

Some of the docs appear out of date.
https://pester.dev/docs/usage/mocking

@nohwnd nohwnd closed this as completed Jul 27, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants