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

Update New-MockObject examples to use type object as input #2609

Merged
merged 4 commits into from
Jan 20, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading