mercredi 24 juin 2015

How to use Pester to mock functions in anonymous advanced functions

I recently discovered that I don't need to use Import-Module to use my advanced powershell functions, I can just define a function anonymously in a ps1 file.

Unfortunately, my Pester unit tests are broken. I can't seem to mock the call to New-Object in the listing below anymore. Typically, I would dot source the below code and have the function Get-StockQuote defined in my scope. Now dot sourcing the ps1 file does not help because I invoke the function via the file name anyway.

How can I use Pester to test the below code with a mock implementation of New-Object?

Note: This code is obviously trivial for the purpose of the question, the tests for code I am working with really does need a mock implementation of New-Object.

# Source listing of the file: Get-StockQuote.ps1
<#
.Synopsis
Looks up a stock quote
.Description
Uses the yahoo api to retrieve a recent quote for a given stock.
.Parameter Symbol
The stock trading symbol
.Example
Get-StockQuote.ps1 -Symbol AMZN
Prints the following line to the output
440.84
#>
[CmdletBinding()]
Param(
    [parameter(Mandatory=$false)]
    [string]$Symbol
)
BEGIN {
    Set-StrictMode -Version 1
}
PROCESS {
    (New-Object System.Net.WebClient).DownloadString("http://ift.tt/1JjEmzJ")
}
END {
}

Aucun commentaire:

Enregistrer un commentaire