I just started working Pester and Mocking and I can’t seem Mocking to work. I bought The Pester Book and I’ve been using the advice to create a Pester test for some functions that I am created to abstract a Credential store. I’m abstracting the Credential store because we are using Windows Credential store in a tactical deployment and long term we will be moving to a Vault based credential store.
One of the functions retrieve a credential from the store. The function currently uses the Get-StoredCredential from the CredentialManager module to retrieve the credential. So, for the Pester test, I was thinking of using Mock to mock this command to return a PSCredential object as appose to actually retrieve a credential from the credential store.
Function Get-ServerCredential {
Param (
[Parameter(Mandatory=$True,Position=0)]
[string]$serverFQDN,
[Parameter(Mandatory=$True,Position=1)]
[string]$serverAccount
)#End Param
Import-Module CredentialManager -Force
$storeURL = ($serverAccount -replace ('@','.')) + '.' + $serverFQDN
$storedCred = Get-StoredCredential -Target $storeURL
if ($storedCred){
Write-Output $storedCred
} else {
throw "Invalid Account"
}
}
The Pester test verifies that a PSCredential Object is returned, but every time I run the Pester test, it doesn’t appear to be using the Mock and I get an error message stating the the test failed. Here is the Pester test file
$Here = "$(Split-Path -parent $MyInvocation.MyCommand.Path)"
$ModuleName = Get-ChildItem "$Here\..\*.psd1"
Import-Module $ModuleName -force
Import-Module CredentialManager -force
$testCases = @( @{AccountName = 'root'})
Describe 'Get-ServerCredential when it''s an valid account'{
mock Get-StoredCredential -MockWith {New-MockObject -Type 'System.Management.Automation.PSCredential'}
It "Should Return a PSCredential Object" -TestCases $testCases {
param($AccountName)
Get-ServerCredential -serverFQDN "some server FQDN" -serverAccount $AccountName|Should BeOfType PSCredential
}
}
I banging my head over this. I have change the Mock several different times. I’ve use a “return New-Object -Type ‘System.Management.Automation.PSCredential’” to MockWith. I seem to be missing something. Does anybody see something with this code that would be preventing me from using Mock??