簡體   English   中英

如何用 Pester 模擬腳本調用?

[英]How to mock script invocation with Pester?

我想用 Pester 創建一個模擬,它應該被調用而不是腳本。 下面的簡化示例。

一些cmd.ps1

# This is the script I want to not be called in my test.

Write-Host "Output from somecmd.ps1"
throw "Error, should have been mocked"

一些模塊.psm1

# This is the module I am testing.

function ModuleFunction{
    .\somecmd
}

function somecmd {
    Write-Host "Output from somecmd in somemodule"
    throw "Error, should never be called"
}

somemodule.Tests.ps1

# This is my Pester test.

BeforeAll {
    Import-Module .\somemodule.psm1 -Force
}

Describe 'SomeTest' {
    It 'Should mock' {
        # How must I declare the mock below so that somecmd.ps1 is not invoked?
        Mock somecmd { Write-Host "Output from mock" } -ModuleName somemodule
        ModuleFunction
    }
}

如上面評論中所述,我的問題是我無法弄清楚如何聲明模擬,因此測試將使用它而不是實際調用 somecmd.ps1。

我嘗試調查這個問題,但按照那里的建議並沒有解決我的問題。

不幸的是,在我的真實場景中,我無法重新編寫模塊以更好地支持測試。

我在跑步:

  • PowerShell:5.1.19041.1682
  • 糾纏:5.3.3

有人有想法嗎?

從您鏈接的 GitHub 問題中,我認為您不能直接模擬 *.ps1 腳本。

但是,一個簡單的解決方法是將您對.\somecmd.ps1的調用包裝在單獨的 function 中,然后模擬...

一些模塊.psm1

function Invoke-SomeCmd
{
    .\somecmd
}

function ModuleFunction{
    # do some stuff
    Invoke-SomeCmd
    # do some more stuff
}

somemodule.Tests.ps1

BeforeAll {
    Import-Module .\somemodule.psm1 -Force
}

Describe 'SomeTest' {
    It 'Should mock' {
        Mock "Invoke-SomeCmd" {
            Write-Host "Output from mock"
        } -ModuleName somemodule
        ModuleFunction
    }
}

然后你得到這個 output:

Starting discovery in 1 files.
Discovery found 1 tests in 327ms.
Running tests.
Output from mock
[+] C:\src\so\pester\somemodule.tests.ps1 992ms (274ms|433ms)
Tests completed in 1.02s
Tests Passed: 1, Failed: 0, Skipped: 0 NotRun: 0

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM