简体   繁体   English

有没有办法嘲笑$? 使用Pester返回?

[英]Is there a way to mock an $? return using Pester?

I'm writing tests for a PowerShell application, using Pester. 我正在使用Pester为PowerShell应用程序编写测试。

I have been able to create mocks for most functions, but I haven't been able to mock a function returning the $? 我已经能够为大多数函数创建模拟,但我无法模拟返回$的函数 variable. 变量。 I'm currently using it to evaluate the returns from AWS CLI commands. 我目前正在使用它来评估AWS CLI命令的返回值。

This is, for example, to mock a failing AWS CLI command return. 例如,这是模拟失败的AWS CLI命令返回。

Any thoughts? 有什么想法吗?

If you're looking to get mock code which performs the same function as $? 如果你想获得与$?执行相同功能的模拟代码$? , you can use something like this (it is quite limited in terms of how it actually returns if multiple lines are executed at once, etc., and it will likely need to be modified depending on the execution context): ,你可以使用这样的东西(如果一次执行多行,它在实际返回方面是非常有限的,等等,并且可能需要根据执行上下文进行修改):

Function Test-LastCommandError {
    $LastCommand = (History | Select -Last 1).CommandLine
    $LastError = $Error[-1].InvocationInfo.Line
    $LastCommand -eq $LastError
}

1/1#Success
Test-LastCommandError # Returns false

1/0#Error
Test-LastCommandError # Returns true

This works for me manually executing each line, but not in an ad-hoc ISE window (since it copy-pastes everything as one command on execute). 这对我来说可以手动执行每一行,但不适用于ad-hoc ISE窗口(因为它在执行时将所有内容复制粘贴为一个命令)。

We created an auxiliary function and passed the $? 我们创建了一个辅助函数并传递了$? value. 值。

function Test-LastExitCodeIsFalse ($last_exit) {
    if ($last_exit) {
       return $false
    }
    $true
}

And a usage being 一种用法

aws s3 <an aws command>
if (Test-LastExitCodeIsFalse($?)) {
   throw "AWS Exception"
}

Using Pester, then we just mock the Test-LastExitCodeIsFalse function to return false . 使用Pester,我们只是模拟Test-LastExitCodeIsFalse函数返回false And we have a unit test with a failing AWS instance :) 我们有一个失败的AWS实例的单元测试:)

你应该能够做到:

Mock AWC-CLI { $ = $true } -Verifiable

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM