Skip to content

Mocking a function that is call by a method in a PowerShell class works on first run, but not on second run #797

@johlju

Description

@johlju

We have created a Pester test that tests a class-bases resource, that do work on the first run. The problem we are seeing is that the mocks only works on first run. On any subsequent run the mocks doesn't get hit, but instead the original function is called. This could be solved by running a new session for each run during development. But now we are starting to see problems in AppVeyor where we can't control that as easily.

We are hoping someone can shed a light on this problem.

Running Pester 4.0.3 on PS 5.1.16232.1000.

I have put together a minimal example scenario (repository) here; https://github.com/johlju/PesterTestClassBasedResource

1. Clone the repository

To run this example, do the following.

git clone https://github.com/johlju/PesterTestClassBasedResource
cd PesterTestClassBasedResource

2. Run the Pester test

First run

Invoke-Pester .\MyDscResource.Tests.ps1

Gives expected successful result.

Executing all tests in .\MyDscResource.Tests.ps1

Executing script .\MyDscResource.Tests.ps1

  Describing MyDscResource\Get()

    Context When the Get method is called
      [+] Should not throw an error 1.13s
Tests completed in 1.13s
Tests Passed: 1, Failed: 0, Skipped: 0, Pending: 0, Inconclusive: 0

Second run

Invoke-Pester .\MyDscResource.Tests.ps1

The test throws an error.

Executing all tests in .\MyDscResource.Tests.ps1

Executing script .\MyDscResource.Tests.ps1

  Describing MyDscResource\Get()

    Context When the Get method is called
      [-] Should not throw an error 179ms
        Expected: the expression not to throw an exception. Message was {Test-HelperFunction throw an error!}
            from V:\Source\_Random\PesterTestClassBasedResource\HelperFunctions.psm1:6 char:5
            +     throw 'Test-HelperFunction throw an error!'
            +     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        at <ScriptBlock>, V:\Source\_Random\PesterTestClassBasedResource\MyDscResource.Tests.ps1: line 17
        17:                 { $databaseMembershipClass.Get() } | Should Not Throw

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions