From 856f2be955bbdaece3bfe9797e1889987b4b6b8d Mon Sep 17 00:00:00 2001 From: Frode Flaten <3436158+fflaten@users.noreply.github.com> Date: Mon, 20 Jan 2025 09:41:56 +0100 Subject: [PATCH] Update New-MockObject examples to use type object as input (#2609) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Add New-MockObject example and tests for internal class * Wrap test in version check for easier backport * fix something please * Add default ctors to make code run under Profiler --------- Co-authored-by: Jakub Jareš --- src/functions/New-MockObject.ps1 | 14 ++++++++++++++ tst/functions/New-MockObject.Tests.ps1 | 26 ++++++++++++++++++++++++++ 2 files changed, 40 insertions(+) diff --git a/src/functions/New-MockObject.ps1 b/src/functions/New-MockObject.ps1 index 26f088de6..95d56b203 100644 --- a/src/functions/New-MockObject.ps1 +++ b/src/functions/New-MockObject.ps1 @@ -32,6 +32,10 @@ .EXAMPLE ```powershell $obj = New-MockObject -Type 'System.Diagnostics.Process' + $obj.GetType().FullName + System.Diagnostics.Process + + $obj = New-MockObject -Type ([System.Diagnostics.Process]) $obj.GetType().FullName System.Diagnostics.Process ``` @@ -64,6 +68,16 @@ Create a mock of a process-object and mocks the object's `Kill()`-method. The mocked method will keep a history of any call and the associated arguments in a property named `_Kill` + .EXAMPLE + ```powershell + $someObj = Get-ObjectFromModule + $mock = New-MockObject -Type $someObj.GetType() + $mock.GetType().FullName + .MyInternalClass + ``` + + Create a mock by providing a TypeInfo, e.g. to mock output using an internal module class. + .LINK https://pester.dev/docs/commands/New-MockObject diff --git a/tst/functions/New-MockObject.Tests.ps1 b/tst/functions/New-MockObject.Tests.ps1 index 5817637bc..fd15d2fcc 100644 --- a/tst/functions/New-MockObject.Tests.ps1 +++ b/tst/functions/New-MockObject.Tests.ps1 @@ -35,6 +35,32 @@ Describe 'New-MockObject' { { New-MockObject $type } | Should -Not -Throw } + It 'Mock using type input' { + New-MockObject -Type ([System.Diagnostics.Process]) | Should -BeOfType ([System.Diagnostics.Process]) + } + + if ($PSVersionTable.PSVersion.Major -ge 5) { + It 'Mock internal classes using type' { + # Simulate a internal module class like https://github.com/pester/Pester/issues/2564 + $someObj = & { + class MyInternalClass { + MyInternalClass() { } + + [string] $Name = 'Default' + [string] GetName() { return $this.Name } + } + $obj = [MyInternalClass]::new() + $obj.Name = 'Real' + $obj + } + + { [MyInternalClass] } | Should -Throw -ErrorId 'TypeNotFound' + $mock = New-MockObject -Type $someObj.GetType() -Properties @{ Name = 'Mocked' } + $mock.GetType().Name | Should -Be 'MyInternalClass' + $mock.GetName() | Should -Be 'Mocked' + } + } + Context 'Methods' { It "Adds a method to the object" { $o = New-Object -TypeName 'System.Diagnostics.Process'