2

The below script works when ran with a dot but fail to run when called with invoke-pester (running Pester version 4.6.0). Am I doing something wrong or is there an issue with invoke-pester?

using module "./Test.psm1"
Describe "Unit Test" -Tag 'Unit' {
  Context 'test' {
    It 'return' {
        mock Write-Verbose { write-host $Message }
        $T = [Test]::new()
        $T.createoutput()
        assert-MockCalled Write-Verbose
    }
  }
}

Test.psm1:

class Test{
    [void]createoutput(){
        Write-Verbose 'hello'
    }
}
user7786267
  • 137
  • 12
  • The script runs fine when using a dot. But when it run's using invoke-pester the 'assert-MockCalled Write-Verbose' return the fact it has 0 run. Why would 'using module' usage impact the way invoke-pester function? – user7786267 Mar 15 '19 at 16:43
  • I've hard coded the path for the test.psm1 and the result is the same – user7786267 Mar 15 '19 at 16:55
  • Here's the error I'm getting from pester "Expected Write-Verbose to be called at least 1 times but was called 0 times 9: assert-MockCalled Write-Verbose" – user7786267 Mar 15 '19 at 16:56
  • I did some additional research and have posted a working solution now. My previous assumptions were incorrect. – Maximilian Burszley Mar 15 '19 at 17:57

1 Answers1

2

The problem is with your mock setup. When mocking for modules, there is some additional work required.

In action:

using module ./Test.psm1

Describe 'Unit Test' -Tag 'Unit' {
    Context 'test' {
        It 'mocks correctly' {
            Mock Write-Verbose {} -ModuleName Test

            $T = [Test]::new()
            $T.createoutput()

            Assert-MockCalled Write-Verbose -ModuleName Test
        }
    }
}

Also important, read this note about class importing.

Maximilian Burszley
  • 18,243
  • 4
  • 34
  • 63