Using New-MockObject

The New-MockObject command provides a way to create an uninitialized version of a type. An instance of an uninitialized type has all of the properties and methods of the initialized instance, but without any of the code behind and potentially without some default values.

It is possible to use New-MockObject to generate an instance of the sqlConnection object used in the previous example. As the object is uninitialized, errors are likely when attempting to use the methods that the type provides:

PS> $sqlConnection = New-MockObject System.Data.SqlClient.SqlConnection
PS> $sqlConnection.Open()
Exception calling "Open" with "0" argument(s): "Object reference not set to an instance of an object."
At line:1 char:1
+ $sqlConnection.Open()
+ ~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : NullReferenceException

In this case, the Open and Close methods, and the State property, must still be overridden by using Add-Member before the object can be used. New-MockObject comes into its own when working with objects that you cannot easily create: objects that either have no constructor at all, or are very complex to create otherwise.

For example, the following function expects a CimSession object. New-MockObject provides a convenient way to create a CimSession to satisfy the parameter during testing:

function Get-CurrentUser {
[CmdletBinding(DefaultParameterSetName = 'UsingComputerName')]
param (
[Parameter(ParameterSetName = 'UsingComputerName')]
[String]$ComputerName,

[Parameter(Mandatory, ParameterSetName = 'UsingCimSession')]
[CimSession]$CimSession
)

(Get-CimInstance Win32_ComputerSystem -Property UserName @psboundparameters).UserName
}

A test may be created that ensures that a CimSession provided to the function is passed on to Get-CimInstance:

Describe Get-CurrentUser {
Context 'Using a CIM session' {
BeforeAll {
Mock Get-CimInstance -ParameterFilter { $CimSession } -MockWith {
[PSCustomObject]@{ UserName = 'UserFromCimSession' }
}
}

It 'When a CimSession is supplied, passes the CimSession to Get-CimInstance' {
Get-CurrentUser -CimSession (New-MockObject CimSession) |
Should -Be 'UserFromCimSession'
}
}
}
..................Content has been hidden....................

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