---
title: "Demystifying Pester Mocking: A Comprehensive Tutorial"
description: "Learn command mocking in Pester with this hands-on tutorial. Improve your testing skills and create more robust PowerShell scripts."
canonical: "https://adamtheautomator.com/pester-mock/"
---

# Demystifying Pester Mocking: A Comprehensive Tutorial

> Learn command mocking in Pester with this hands-on tutorial. Improve your testing skills and create more robust PowerShell scripts.

Source: https://adamtheautomator.com/pester-mock/

---

ATA Learning

Tap to hide

[

ATA Learning

](/)

*   [Home](/)
*   [Tutorials](/tutorials/)
*   [Instructors](/author/)
*   [Advertising](/advertising/)
*   [Recommended Resources](/resources/)
*   [About Adam](/about-adam/)

Search for:  

*   [](https://twitter.com/adbertram)
*   [](https://github.com/Adam-the-Automator)
*   [](https://www.linkedin.com/company/adam-the-automator-llc)
*   [](/feed/)

![Demystifying Pester Mocking: A Comprehensive Tutorial](https://adamtheautomator.com/wp-content/uploads/2019/12/what-is-pester-for-powershell-test-670091_1280.png)

# Demystifying Pester Mocking: A Comprehensive Tutorial

[![](https://secure.gravatar.com/avatar/d0b9d42e21e5622713f8b693aa5c0f9244d5f7dd200ed29b8398f52dee5de337?s=192&d=mm&r=g)Adam Bertram](https://adamtheautomator.com/author/adam-bertram/)4 December 20193 min. read

Categories: [IT Ops](/category/it-ops/)

Tags:[Pester](/tag/pester/)[PowerShell](/tag/powershell/)

Table of Contents

*   [Mocking Demonstration](#mocking-demonstration)
*   [Summary](#summary)

If you want to ensure your PowerShell code is in tip-top shape, you need to be unit testing it. [Pester](https://github.com/pester/Pester) is a popular unit-testing framework built for PowerShell code that allows you to ensure the code you write is as you expect and stays that way.

When unit testing, it’s essential to ensure your code isn’t influenced in any way by the environment its being run on or by any other outside functions or modules. Unit testing tests individual _units_ of code as one to ensure developers can accurately determine if a single “unit” behaves as expected.

One way to ensure unit tests are accurate and unaffected by other code is through a concept called mocking. Mocking is a feature in Pester that allows you to “replace” commands your “unit” is calling with ones of your own. Mocking enables you to set up various scenarios commands inside of your testing “unit” will adhere to figure out what might happen given various circumstances.

If this doesn’t make sense now, hopefully, a brief demonstration will make the light bulb turn on! To follow along with the demo, I will expect you to have a beginner-intermediate level understanding of the Pester testing framework.

> _If you’d like to dive deep into mocking and many real-world examples, be sure to check out [The Pester Book](https://leanpub.com/pesterbook/)._

## Mocking Demonstration

Let’s say you have a [PowerShell function](https://adamtheautomator.com/powershell-functions/ "PowerShell function") that creates a file only if that file doesn’t already exist. To do this, you first check to see if that file exists with the [`Test-Path`](https://adamtheautomator.com/powershell-test-path/ "Test-Path") command and if it returns `False`, you then create the file.

Your function looks like this:

```powershell
function New-FictionalFile {
    [CmdletBinding()]
    param(
        [Parameter()]
        [string]$FilePath
    )
    if (-not (Test-Path -Path $FilePath)) {
        $null = New-Item -Path $FilePath -ItemType File
    }
}
```

A typical Pester test for this function would look like below. I’m assuming the function above is in a script called _C:\\New-FictionalFile.ps1_.

The test below is testing to ensure the function creates the file if it doesn’t already exist. This is great, but it has two problems; it depends on the environment (the storage to hold the file), and it’s not testing the scenario when the file already exists.

```powershell
describe 'New-FictionalFile' {
    context 'when the file path does not exist' {
        ## Ensure the test file isn't there
        $null = Remove-Item -Path '~\file.txt' -ErrorAction Ignore
        $null = New-FictionalFile -FilePath '~\file.txt'
        
        it 'creates the file' {
            '~\file.txt' | Should -Exist
        }
    }
}
```

To build a proper unit test, you must remove the environment requirement from the test. You must also test the scenario when the file already exists. To do that, you need to ensure the `New-Item` cmdlet is _not_ called. The only way to solve these two problems is to use mocking.

You need to mock or “replace” the functionality of both the `Test-Path` and `New-Item` cmdlets to control their output without relying on the environment.

You can see below that the code to ensure a file is created or removed (`New-Item` and `Remove-Item`) as well as mocking code added. Since you’ve now taken control of the output of all commands, there’s no need to depend on the environment anymore. Now, this unit test can be run anywhere without regard for the local filesystem.

```powershell
describe 'New-FictionalFile' {
    ## This ensures New-Item will never run. It's just being used as a 
    ## flag to test if it attempts to execute
    mock 'New-Item'

    context 'when the file path does not exist' {
        ## This ensures Test-Path always returns $false "mimicking" the file does not exist
        mock 'Test-Path' { $false }
        
        $null = New-FictionalFile -FilePath '~\file.txt'

        it 'creates the file' {
            ## This checks to see if New-Item attempted to run. If so, we know the script did what we expected
            $assMParams = @{
                CommandName = 'New-Item'
                Times = 1
                Exactly = $true
            }
            Assert-MockCalled @assMParams
        }
    }
    
    context 'when the file path already exists' {
        ## This ensures Test-Path always returns $true "mimicking" the file does not exist
        mock 'Test-Path' { $true }

        $null = New-FictionalFile -FilePath '~\file.txt'

        it 'does not attempt to create a file' {
            ## This checks to see if New-Item did not attempt to run (Times = 0). If it did not
            ## that means that it did not attempt to create the file
            $assMParams = @{
                CommandName = 'New-Item'
                Times = 0
                Exactly = $true
            }
            Assert-MockCalled @assMParams
        }
    }
}
```

> _To learn more about the `Assert-MockCalled` command, be sure to check out the [Pester documentation](https://github.com/pester/Pester/wiki/Assert%E2%80%90MockCalled)._

## Summary

The concept of mocking in Pester can be confusing for those new to unit testing. It’s a powerful feature to control your code better and to ensure tests run the same regardless of the environment they’re in.

If you’d like to learn more about mocking in Pester, check out [The Pester Book](https://leanpub.com/pesterbook/). In the book, you’ll learn mocking works at a deep level and how to apply it across many different scenarios.

Share this article

[Share on X](https://twitter.com/intent/tweet?url=https%3A%2F%2Fadamtheautomator.com%2Fpester-mock%2F&text=Demystifying%20Pester%20Mocking%3A%20A%20Comprehensive%20Tutorial)[Share on Facebook](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Fadamtheautomator.com%2Fpester-mock%2F)[Share on LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fadamtheautomator.com%2Fpester-mock%2F)

## Related Posts

![](https://adamtheautomator.com/wp-content/uploads/2025/06/featured-image-6.png)

### [How to Add Timeouts to Pester Tests with PowerShell Runspaces](/pester-test-timeout-runspaces/)

Prevent Pester tests from hanging indefinitely using PowerShell runspaces. Learn to handle variable scoping, module loading, TestDrive access, and stream capture challenges with timeout protection.

![](https://adamtheautomator.com/wp-content/uploads/2025/01/featured-image-1.png)

### [PowerShell Pester 101: A Practical Guide for Beginners](/powershell-pester-testing-guide/)

Learn how to validate your PowerShell scripts with Pester testing. This hands-on guide shows you how to write tests that ensure your code works as intended.

![](https://adamtheautomator.com/wp-content/uploads/2024/05/2024-05-10_08-07-57.jpg)

### [PowerShell Testing Mastery with Data-Driven Pester](/pester-infrastructure-data-driven-tests/)

I’ve been using Pester for a long time off and on. I’ve always been obsessed with ensuring reliability in my PowerShell code. After writing the Pester Book and

## Categories

*   [IT Ops](/category/it-ops/)
*   [Cloud](/category/cloud/)
*   [DevOps](/category/devops/)
*   [Home Ops](/category/home-ops/)
*   [Information Security](/category/infosec/)
*   [Software Development](/category/software-development/)

## Site

*   [Home](/)
*   [Tutorials](/tutorials/)
*   [Instructors](/author/)
*   [Advertising](/advertising/)
*   [Recommended Resources](/resources/)
*   [About Adam](/about-adam/)

Copyright 2026© ATA Learning | [Privacy Policy](/privacy/)
