摘要:在为设置 Mock 时Invoke-RestMethod
,我的测试正在调用真正的实现,而不是我的模拟。`
- 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
我整理了以下简单示例来演示该问题
所有文件都位于同一目录中
客户端.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
}
}
客户端.测试.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