Skip to content

Instantly share code, notes, and snippets.

@dlwyatt
Created February 14, 2015 13:25
Show Gist options
  • Save dlwyatt/384d720acea9d5971189 to your computer and use it in GitHub Desktop.
Save dlwyatt/384d720acea9d5971189 to your computer and use it in GitHub Desktop.
Pester Example
# Import the stuff you'll be testing. Could be dot-sourcing a ps1 file here, importing a module, whatever you need.
# If importing a mdoule, make sure you've only got one copy of it imported, or weird things can happen when you start
# to get into mocking.
Remove-Module [S]omeDscResource
Import-Module $PSScriptRoot\SomeDscResource.psm1
# All of the Pester tests in a script must go inside a Describe block; you can mave many Describe blocks in the same
# script, if you like. Make sure to put the opening brace on the same line as Describe, since this is just a function
# pretending to be a keyword; no assistance from the parser allowing us to put opening braces on their own lines.
Describe 'Test-TargetResource' {
# Pester tests go into blocks using the 'It' keyword. If the body of the It block throws a terminating error, it's
# a failed test. Otherwise, it succeeds. Output is ignored.
It 'Returns false when the item does not exist' {
$result = Test-TargetResource -Name SomeBogusName -Ensure Present
# Pester has some built-in assertions; check the about_Should help file. Aside from giving a slightly more
# human-readable look to the test script itself, they also give useful output when the test fails, such as
# the line number in the test file where the Should assertion came from, pointing out exactly where strings
# differ, that sort of thing.
$result | Should Be $false
}
# Inside a describe, you can optionally define a Context block as a child scope. This can be used to group
# similar tests together, and also has an impact on mocking. (Mocks defined within a Context go out of scope
# at the end of that Context without affecting the rest of the Describe.)
Context 'Whatever' {
It 'Tests something else' {
$true | Should Be $true
}
}
}
# Mocking is a much larger topic, and much of Pester's complexity is there. It allows you to stub out functions or
# cmdlets so your script can safely be tested without requiring external services or changing anything.
# https://github.com/pester/Pester/wiki/Mocking-with-Pester
# https://github.com/pester/Pester/wiki/Unit-Testing-within-Modules
@jrbella
Copy link

jrbella commented Nov 16, 2017

Line # 2 word four change from 'mdoule' to 'module'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment