Skip to content

Commit

Permalink
Update New-MockObject examples to use type object as input (#2609)
Browse files Browse the repository at this point in the history
* 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š <[email protected]>
  • Loading branch information
fflaten and nohwnd authored Jan 20, 2025
1 parent e4a21df commit 856f2be
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
14 changes: 14 additions & 0 deletions src/functions/New-MockObject.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -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
```
Expand Down Expand Up @@ -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
<c2510c5c>.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
Expand Down
26 changes: 26 additions & 0 deletions tst/functions/New-MockObject.Tests.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down

0 comments on commit 856f2be

Please sign in to comment.