Fabricating objects

Objects with specific properties can be simulated by creating a PS custom object (or PSObject):

[PSCustomObject]@{ 
    Property = "Value" 
} 

Methods can be added to an object using Add-Member:

[PSCustomObject]@{} | Add-Member MethodName -MemberType ScriptMethod -Value { } 

This approach can be extended to include objects instantiated by New-Object. The following function creates and uses instances of two different .NET types:

function Write-File {
$fileStream = New-Object System.IO.FileStream(
"C:Temp est.txt",
'OpenOrCreate'
)
$streamWriter = New-Object System.IO.StreamWriter($fileStream)
$streamWriter.WriteLine("Hello world")
$streamWriter.Close()
}

The following mocks replace the first call made to New-Object in the preceding script with null. The second call is replaced with an object that supports the methods used by the script:

Mock New-Object -ParameterFilter { $TypeName -eq 'System.IO.FileStream' }
Mock New-Object -ParameterFilter { $TypeName -eq 'System.IO.StreamWriter' } -MockWith { 
    [PSCustomObject]@{} |
        Add-Member WriteLine -MemberType ScriptMethod -Value { } -PassThru | 
        Add-Member Close -MemberType ScriptMethod -Value { } -PassThru 
}

At this point, it is possible to assert that the function creates each of the objects, but the test is blind to how the methods are used. If it is not desirable to let the methods act on a real object, it may be worth considering what could be done inside of a method implementation to signal activity to Pester.The following example changes the methods to make a change to a script-scoped variable. The variable can be accessed within the other tests. The content of the script-scoped variables is cleared before each test:

Describe Write-File {
BeforeAll {
Mock New-Object -ParameterFilter { $TypeName -eq 'System.IO.FileStream' }
Mock New-Object -ParameterFilter { $TypeName -eq 'System.IO.StreamWriter' } -MockWith {
[PSCustomObject]@{} |
Add-Member WriteLine -MemberType ScriptMethod -PassThru -Value {
$Script:WriteLine = $args[0]
} |
Add-Member Close -MemberType ScriptMethod -PassThru -Value {
$Script:Close = $true
}
}
}

BeforeEach {
$Script:WriteLine = ''
$Script:Close = $false
}

It 'Creates a file stream' {
Write-File

Assert-MockCalled New-Object -ParameterFilter { $TypeName -eq 'System.IO.FileStream' }
Assert-MockCalled New-Object -ParameterFilter { $TypeName -eq 'System.IO.StreamWriter' }
}

It 'Writes a line and closes the file stream' {
Write-File

$Script:WriteLine | Should -Be 'Hello world'
$Script:Close | Should -Be $true
}
}

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.97.189