Skip to content

Instantly share code, notes, and snippets.

@johlju
Last active February 15, 2018 15:11
Show Gist options
  • Save johlju/0767c9ebde5fffb22335cfa237aa96b2 to your computer and use it in GitHub Desktop.
Save johlju/0767c9ebde5fffb22335cfa237aa96b2 to your computer and use it in GitHub Desktop.
function Get-Something
{
param
(
[Parameter()]
[System.Boolean]
$MockError
)
}
function Test-Something
{
param
(
[Parameter()]
[System.Boolean]
$MockError
)
Get-Something -MockError $MockError
return $true
}
<#
Calling the function that is under test in the Context-block.
Neither It-block will run since we are mocking a fault here to
illustrate a function that is throwing an unexpected error in
the code path.
#>
Describe 'Something' {
Context 'When this happens' {
BeforeAll {
Mock -CommandName Get-Something -MockWith {
if ($MockError)
{
throw 'Get-Something error'
}
else
{
Write-Verbose -Message 'Get-Something' -Verbose
}
}
}
$result = Test-Something -MockError $true
It 'Should do this in first code path' {
$result | Should -Be $true
Assert-MockCalled -CommandName Get-Something
}
It 'Should do this in second code path' {
$result | Should -Be $true
Assert-MockCalled -CommandName Get-Something
}
}
}
<#
Calling the function that is under test in the first It-block only.
We are mocking a fault here to illustrate a function that is throwing
an unexpected error in the code path.
Both It-blocks will run, but both will fail.
First one because of it throwing an error instead of returning the
correct value.
Second one because the first one did not return the correct value.
#>
Describe 'Something' {
Context 'When this happens' {
BeforeAll {
Mock -CommandName Get-Something -MockWith {
if ($MockError)
{
throw 'Get-Something error'
}
else
{
Write-Verbose -Message 'Get-Something' -Verbose
}
}
}
It 'Should do this in first code path' {
$result = Test-Something -MockError $true
$result | Should -Be $true
Assert-MockCalled -CommandName Get-Something
}
It 'Should do this in second code path' {
$result | Should -Be $true
Assert-MockCalled -CommandName Get-Something
}
}
}
<#
Calling the function that is under test in each It-block.
The first It-block will run, but the second It-block will fail since
we are mocking a fault in the second code path to illustrate a function
that is throwing an unexpected error.
#>
Describe 'Something' {
Context 'When this happens' {
BeforeAll {
Mock -CommandName Get-Something -MockWith {
if ($MockError)
{
throw 'Get-Something error'
}
else
{
Write-Verbose -Message 'Get-Something' -Verbose
}
}
}
It 'Should do this in first code path' {
$result = Test-Something -MockError $false
$result | Should -Be $true
Assert-MockCalled -CommandName Get-Something
}
It 'Should do this in second code path' {
$result = Test-Something -MockError $true
$result | Should -Be $true
Assert-MockCalled -CommandName Get-Something
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment