难以模拟Invoke-WebRequest的BasicHtmlWebResponseObject

问题描述 投票:2回答:1

我正在尝试测试PowerShell函数的这一部分:

# post
$Response = Invoke-WebRequest -Method POST -Uri $Uri -Body $Body -ContentType 'application/xml'

# parse Response.Content; return as System.Xml.XmlDocument
[xml]$Response.Content

模拟BasicHtmlWebResponseObject返回的Invoke-WebRequest

Mock Invoke-WebRequest { 

    $WebResponse = [System.Net.HttpWebResponse]::new()
    [System.Net.HttpWebResponse].GetField('m_StatusCode', 'NonPublic, Instance').SetValue(
        $WebResponse,
        200,
        'NonPublic,SetField',
        $null,
        (Get-Culture)
    )

    $Content = '<?xml version="1.0" encoding="UTF-8"?><response><control>failure<status></status></control><operation><result><status>failure</status></result></operation></response>'
    $Response = [Microsoft.PowerShell.Commands.BasicHtmlWebResponseObject]::new($WebResponse,$Content)
    return $Response
}

此断言失败,因为我没有正确创建HttpWebResponseBasicHtmlWebResponseObject

It "returns the response's Content object" {
    # act
    $Content = Send-Request -Session $Session

    # assert
    Assert-MockCalled Invoke-WebRequest
    $Content | Should -BeOfType [xml]
    $Content.response.control.status | Should -Be 'success'
    $Content.response.operation.result.status | Should -Be 'success'
}

**编辑**

我考虑过使用New-MockObject

Mock Invoke-WebRequest { 
    New‐MockObject -Type [Microsoft.PowerShell.Commands.BasicHtmlWebResponseObject]
}

但是它会产生异常:

CommandNotFoundException:术语'New-MockObject'不被识别为cmdlet,函数,脚本文件或可操作程序的名称。检查名称的拼写,或者是否包含路径,请验证路径是否正确,然后重试。

使用Pester 4.10.1。

** / edit **

我想念什么?

powershell powershell-core pester
1个回答
1
投票

在PowerShell Core上,这对我不起作用:

[System.Net.HttpWebResponse].GetField('m_StatusCode', 'NonPublic, Instance')

这就是为什么您的Mock无法返回您期望的结果。但是,该行在Windows PowerShell上有效。不确定PSCore上的功能是否合适,需要研究,但我想我会在此之前带您到这为止。

© www.soinside.com 2019 - 2024. All rights reserved.