Pester 中 REST API 的模拟响应
我有一个 PowerShell 脚本,它从 REST API 调用返回一个字符串。我正在使用
$Response = Invoke-RestMethod -Method Post -Uri $Uri -Body $Body -ContentType 'application/x-www-form-urlencoded'
return $Response.ToString()
我能够模拟请求,但我也应该能够模拟响应,以便它返回 $Response 的虚拟字符串值。目前,我收到错误 RuntimeException:您无法在空值表达式上调用方法。
我已尝试使用以下代码作为响应,但出现相同的错误。
Mock Invoke-RestMethod -MockWith{return "abc"}
有什么想法吗?
I have a PowerShell script that returns a string from a REST API call. I am using
$Response = Invoke-RestMethod -Method Post -Uri $Uri -Body $Body -ContentType 'application/x-www-form-urlencoded'
return $Response.ToString()
I am able to mock the request but I should also be able to mock the response so that it returns a dummy string value for $Response. Currently I get an error RuntimeException: You cannot call a method on a null-valued expression.
I have tried the below code as a response but i get the same error.
Mock Invoke-RestMethod -MockWith{return "abc"}
Any thoughts?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我看不出你正在尝试做的事情有任何问题。这对我有用:
I can't see any issue with what you're trying to do. This works for me:
当我在模块中使用 Invoke-RestMethod 时,我遇到了这种情况。我想嘲笑它,但它没有。必须指定我自己的模块的模块名称(不是 PowerShell.Utility),然后它就可以工作了。
编辑:
要测试的文件:TestModule.psm1
Pester 文件:TestModule.Tests.ps1 包含:
I had this situation when I used the Invoke-RestMethod in a Module. I wanted to mock it but it didn't. Had to specify the module name of my own module (not the PowerShell.Utility) and then it worked.
Edit:
File to test: TestModule.psm1
Pester file: TestModule.Tests.ps1 containing: