Reputation: 11
I've been using Pester for some time now to write (simple) tests for our powershell scripts, but naturally the further I get the more difficult the scripts get. I'm not a developer (just an automation QA) and therefore cannot really start changes the existing code, but I do need to write unit tests for them.
In the following script I have I'm running into 2 problems:
The function starts by running another .ps1 file using the call operator - This other script can only be run as an administrator and does some pre-deployment checks. Now I do not want to unit test this external script so I need a way to mock or bypass the & $PSScriptRoot\PreReqCheck.ps1 call. I thought simply mocking it would be nice but & is reserved for future use and it is advising to wrap in quotes as a string, which does not really seem to work.
The second (but I think this might be eeasier to solve) is the following:
After PreReqCheck has been run certain variables will be filled ($computerName, $masterNodes, $dataNodes) and continues with an If/Elseif/Elseif statement which depending on the variables sets, gets and starts a service. Like this piece of code:
If ($computerName = "X")
{
$masterNodes = @("1","2","3")
$dataNodes = @("01","02","03")
}
Elseif ($computerName = "Y")
{
$masterNodes = @("1","2","3")
$dataNodes = @("01","02","03")
}
Elseif ($computerName = "Z")
{
$masterNodes = @("1","2","3")
$dataNodes = @("01","02","03")
}
forEach ($masterNode in $masterNodes)
{
Does something
}
forEach ($dataNode in $dataNodes)
{
Does something
}
My question about this is. How can I best create a test where I can state which variables to use? I have tried something like this:
Describe "ReconfigureMainCluster" {
Context "test" {
Mock Set-Service
Mock Get-service
#Mock Write-Host
Mock Start-Service
$computerName = "X"
It "checks something" {
ReconfigureMainCluster
Assert-MockCalled 'Set-Service' -Exactly 12
Assert-MockCalled 'Write-Host' -Exactly 22
Assert-MockCalled 'Get-Service' -Exactly 6
}
It "checks computername"{
$computerName | Should be "X"
}
}
}
This passes, but when I write a similar test for computerName Y the variable $computerName stays X (I can see that because of commenting out Mock Write-Host and the same text is stated twice.
I think I will need to define the variables somewhere but not sure where or how...
Upvotes: 0
Views: 530
Reputation: 11
For the first part (the call operator) changing it to start-process seemed to work
For the second part changing the original powershell script part:
$computerName = "Y" to $computerName -eq "Y"
Seemed to work as well.
Not sure if this is the best way to do it though.
Upvotes: 0