Question

In the below contrived example, I want to write a unit test on Foo in foo.psm1. In order to do this I must mock out function Bar in bar.psm1, which foo.psm1 imports.

However, the mock isn't working because foo.psm1 only recognizes the version of Bar it imported. How can I achieve this?

**Making all the files .ps1 solves this issue, but I don't want to use .ps1 files because I want all the meta data and discovery that comes with modules.

foo_test.ps1

import-module 'C:\DEV\powershell\mocks\foo.psm1' 

function Bar {
    write-host 'BarMock'
}

Foo  #outputs Bar not BarMock

foo.psm1

import-module 'C:\DEV\powershell\mocks\bar.psm1' 

function Foo { 
    Bar
}

bar.psm1

function Bar { 
    write-host 'Bar' 
}

Any help is much appreciated.

**Update - Solution provided by Steve Murawski (any errors attributed to me).

You need to get the contents of the imported module as a string and import it using Invoke-Expression so that everything is imported into the global scope.

new foo_test.ps1

$contents = gc 'C:\DEV\powershell\mocks\foo.psm1' | out-string
invoke-expression $contents


function Bar {
    write-host 'BarMock'
}

Foo

No correct solution

OTHER TIPS

Have you tried Remove-module and then re-import.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top