Pester测试未调用模拟Invoke-RestMethod,仍调用真实函数问题
问题:Mock Invoke-RestMethod后仍调用真实实现
概要:为Invoke-RestMethod设置Mock后,测试仍调用其真实实现而非模拟函数。
环境信息
- Pester版本:5.6.1(路径:C:\Program Files\WindowsPowerShell\Modules\Pester\5.6.1\Pester.psm1)
- PowerShell版本:5.1.19041.4648
- 操作系统版本:Microsoft Windows NT 10.0.19045.0
复现示例
所有文件位于同一目录:
Client.psm1
class Client { [string] $Query Client([string] $query) { $this.Query = $query } [string] Google() { $url = "https://www.google.com/?q=$($this.Query)" $response = Invoke-RestMethod -Uri $url ` -Method GET return $response } }
Client.Tests.ps1
using module .\Client.psm1 Describe "Client_Tests" { It "Google_queryIsPopulated_ReturnsSearchResultsContainingQuery" { # Arrange $givenQuery = "fooBar" $expectedResult = "fooBar" Mock Invoke-RestMethod { $givenQuery } $systemUnderTest = [Client]::new($givenQuery) # Act $actualResults = $systemUnderTest.Google() # Assert $actualResults | Should -Be $expectedResult } }
测试错误输出
执行命令Invoke-Pester .\Client.Tests.ps1后得到以下错误:
Starting discovery in 1 files. Discovery found 1 tests in 53ms. Running tests. [-] Client_Tests.Google_queryIsPopulated_ReturnsSearchResultsContainingQuery 478ms (476ms|2ms) Expected strings to be the same, but they were different. Expected length: 6 Actual length: 54403 Strings differ at index 0. Expected: 'fooBar' But was: '<!doctype html><html itemscope="" itemtype="http://schema.org/WebPage" lang="en"><head><meta content...' ^ at $actualResults | Should -Be $expectedResult, C:\Users\dgleason\Downloads\example for mock invoke-restmethod\v1\Client.Tests.ps1:21 at <ScriptBlock>, C:\Users\dgleason\Downloads\example for mock invoke-restmethod\v1\Client.Tests.ps1:21 Tests completed in 602ms Tests Passed: 0, Failed: 1, Skipped: 0, Inconclusive: 0, NotRun: 0
内容的提问来源于stack exchange,提问作者Devin Gleason Lambert
相关产品推荐
相关产品推荐

