I’ve been working with Pester for a while and I thought it would be nice to have some Pester tests in the Autoruns module.
I don’t have very high expectations and thought I’d start with some tests to validate that previous issues encountered are still fixed and keep being remediated.
While writing these tests, I encountered two challenges.
- First challenge
The first one is that the module exports a single function and there are many functions in the begin block of this exported function.
I needed to find a solution to be able to test anything in the code whatever the function.
I decided to use the Abstract Syntax Tree (a.k.a AST) to extract every function and inject them in a fake module. In other words the function tree in the original module would be flatten in this fake module.
This way I can use the InModuleScope and test anything I want.
Here’s the only exported function from the original Autoruns module:
Here are the inner functions extracted from the original module and loaded in the FakeAutoRuns module:
Here’s the code that extracts the functions and loads them in a flat (fake) module:
- The 2nd challenge
The 2nd challenge was that I needed to mock some calls made to a .Net method.
I needed to mock the Test-Path, Get-Item cmdlets and especially the call to the method named GetSubKeyNames on the Microsoft.Win32.RegistryKey objects returned by the Get-Item cmdlet in the following example:
Here’s what I did to mock these cmdlets and their invocation of a .Net method
I feel that the learning curve is steep with Pester. If you know a better way to write Pester tests for this issue #26, please tell me, your input is more than welcome.
Pingback: Dew Drop – January 30, 2020 (#3123) | Morning Dew