[英]detect drag&Drop invocation in a windows script and cancel main operation
[英]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。
我尝试调查这个问题,但按照那里的建议并没有解决我的问题。
不幸的是,在我的真实场景中,我无法重新编写模块以更好地支持测试。
我在跑步:
有人有想法吗?
从您链接的 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.