-
I have a custom function that makes a few Azure Rest API calls. The start of the function is the Acquisition of the AccessToken and it is here that I am completely stumped on how to correctly create a Mock for obtaining an Access Token for the Azure Rest API. I'm not sure if anyone has done this before and can guide me through what you have implemented to achieve a successful test. $azProfile = Invoke-Expression "[Microsoft.Azure.Commands.Common.Authentication.Abstractions.AzureRmProfileProvider]::Instance.Profile"
$profileClient = New-Object -TypeName Microsoft.Azure.Commands.ResourceManager.Common.RMProfileClient -ArgumentList ($azProfile)
$token = $profileClient.AcquireAccessToken("ValidTenantId")
$authHeader = @{
'Content-Type'='application/json'
'Authorization'='Bearer ' + $token.AccessToken
} Oddly, when I run the tests, without any Mocks, the first failure is "Exception calling "AcquireAccessToken" with "1" arguments: "Object reference not set to an instance of an object. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
I'd try mocking Describe 'd' {
It 'i' {
# Create mocked RMProfileClient with required method and output
Mock -CommandName 'New-Object' -ParameterFilter { $TypeName -eq 'Microsoft.Azure.Commands.ResourceManager.Common.RMProfileClient' } -MockWith {
$p = @{
Type = 'Microsoft.Azure.Commands.ResourceManager.Common.RMProfileClient'
Methods = @{
AcquireAccessToken = { param($TenantId) @{ AccessToken = "myFakeTokenForTenant$TenantId" } }
}
}
New-MockObject @p
}
# Not sure why you use Invoke-Expression for this. Feels unnecessary.
$azProfile = Invoke-Expression '[Microsoft.Azure.Commands.Common.Authentication.Abstractions.AzureRmProfileProvider]::Instance.Profile'
$profileClient = New-Object -TypeName Microsoft.Azure.Commands.ResourceManager.Common.RMProfileClient -ArgumentList ($azProfile)
$token = $profileClient.AcquireAccessToken('ValidTenantId')
$authHeader = @{
'Content-Type' = 'application/json'
'Authorization' = 'Bearer ' + $token.AccessToken
}
$authHeader | Out-String | Write-Host -ForegroundColor Green
}
}
# output
Starting discovery in 1 files.
Discovery found 1 tests in 29ms.
Running tests.
Name Value
---- -----
Authorization Bearer myFakeTokenForTenantValidTenantId
Content-Type application/json
[+] /workspaces/Pester/Samples/demoMockNewObject.tests.ps1 67ms (18ms|21ms)
Tests completed in 69ms
Tests Passed: 1, Failed: 0, Skipped: 0 NotRun: 0 |
Beta Was this translation helpful? Give feedback.
I'd try mocking
New-Object
and return a mocked object with the necessary method and output. Ex.