pester

Mocking AzureRm Commands with Pester. New-AzureRmDnsRecordSet

Most of my readers already know how much I love Pester. Hi mom! Ha. I can’t get enough of it. But mocking some of the AzureRm commands can be exceedingly painful. A lot of the AzureRm commands require specific object types to be passed thru, even when trying to mock them. Creating those specific object types is a lot of trial and error. Even though my Google-Fu is quite strong, I seemed to strike out when searching for how others were mocking these commands. So to help my fellow engineers, I’ve decided to start posting how I was able to mock some of the more finicky AzureRm modules as I come across them.

 

Mocking New-AzureRmDnsRecordSet was a bit of a hurdle. We need to pass in a valid DNS record set. Returning $null doesn’t work. I originally thought I would just let New-AzureRmDnsRecordConfig to run with a dummy value (not mock it at all) but for whatever reason, it requires you to login to the portal!

This is what I ended up with:
function Add-CustomDnsRecord {
  $params = @{
    Name = 'custom-a-record'
    RecordType = 'A'
    ResourceGroupName = 'myresourcegroupname'
    TTL = 60
    ZoneName = 'internalDNS'
    DnsRecords =  New-AzureRmDnsRecordConfig -Ipv4Address 127.0.0.1
  }

  New-AzureRmDnsRecordSet @params
}

Describe Add-CustomDnsRecord {
  Mock New-AzureRmDnsRecordSet { }
  Mock New-AzureRmDnsRecordConfig {
    return @(
      New-Object Microsoft.Azure.Commands.Dns.ARecord
      New-Object Microsoft.Azure.Commands.Dns.CnameRecord
    )
  }
  It 'mocks correctly' {
    Add-CustomDnsRecord
    Assert-MockCalled New-AzureRmDnsRecordSet -Exactly 1 -Scope It
  }
}
 dns_mock_ss

 

 

Till the next command!

Thanks for reading, please post any comments or questions below.

Advertisements

VS Code + Integrated Console + Pester = No Excuse Testing

Following up on an earlier post where I lightly touch on using the PowerShell Extension for the VS Code editor, I’d love to share how easy it is to Pester test and hopefully¬†convince you to start testing your code today! If you’re not familiar with me, I’m a huge fan of Pester. I mean this is such a great module that it’s baked into Windows! I Pester test EVERYTHING. Even things outside of my custom PowerShell functions… ETL executions, Jenkins job statuses, all kinds of things. I did a post about Pester testing SQL Server stuff, check it out if you haven’t seen it!

Using VS Code and the PowerShell extension, writing Pester tests has never been easier!!

(more…)