我正在尝试测试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
}
该断言失败,因为我没有正确创建
HttpWebResponse
或BasicHtmlWebResponseObject
: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 {
$Response = New‐MockObject -Type Microsoft.PowerShell.Commands.BasicHtmlWebResponseObject
$Response.Content = '<?xml version="1.0" encoding="...'
}
但是,
Content
属性是只读的。** /编辑**
我想念什么?
最佳答案
一个稍微简单的替代方法可能是将您的invoke-webrequest包装在一个函数中,然后对其进行模拟。例如。
function Get-XmlFromUri
{
param( $Uri, $Method, $Body )
$Response = Invoke-WebRequest -Method $Method -Uri $Uri -Body $Body -ContentType 'application/xml’
[xml]$Response.Content
}
现在,您可以模拟Get-XmlFromUri并仅从硬编码的xml返回System.Xml.XmlDocument对象,这比需要反射调用旋转的BasicHtmlWebResponseObject容易得多。
Mock Get-XmlFromUri {
[xml] '<?xml version="1.0" encoding="UTF-8"?>
<response>
<control><status>success</status></control>
<operation><result><status>success</status></result></operation>
</response>'
}
或者,根据您的代码需要它与BasicHtmlWebResponseObject的相似程度,您可以从invoke-webrequest模拟返回一个具有所需属性的哈希表:
Mock Invoke-WebRequest {
new-object pscustomobject -property @{
Content = '<?xml version="1.0" encoding="UTF-8"?>
<response>
<control><status>success</status></control>
<operation><result><status>success</status></result></operation>
</response>’
}
}
(对代码格式的道歉-当前,凌晨4点在iPhone上打字,一个抱着一个不是很困的婴儿:-S)
关于powershell - 难以模拟Invoke-WebRequest的BasicHtmlWebResponseObject,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/60193524/