Pester 不调用模拟函数(Invoke-RestMethod),而是调用真实函数

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

概要:

Invoke-RestMethod
设置模拟时,我的测试正在调用真正的实现,而不是我的模拟。`

  • Pester版本:5.6.1 C:\Program 文件\WindowsPowerShell\模块\Pester .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
powershell pester
1个回答
1
投票

使用

Mock 参数在 
-ModuleName
调用中包含模块名称

Mock Invoke-RestMethod { $givenQuery } -ModuleName Client
© www.soinside.com 2019 - 2024. All rights reserved.