如何在Pester测试中模拟Read-Host? [英] How do I mock Read-Host in a Pester test?

查看:104
本文介绍了如何在Pester测试中模拟Read-Host?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我具有此功能:

Function Test-Foo {

    $filePath = Read-Host "Tell me a file path"
}

如何模拟读取主机以返回我想要的东西?例如我想做这样的事情(不起作用):

How do i mock the Read-Host to return what i want? e.g. I want to do something like this (which doesn't work):

Describe "Test-Foo" {
  Context "When something" {
        Mock Read-Host {return "c:\example"}

        $result = Test-Foo

        It "Returns correct result" {
            $result | Should Be "c:\example"
        }
    }
}

推荐答案

此行为是正确的:

您应该将代码更改为

Import-Module -Name "c:\LocationOfModules\Pester"

Function Test-Foo {
    $filePath = Read-Host "Tell me a file path"
    $filePath
}

Describe "Test-Foo" {
  Context "When something" {
        Mock Read-Host {return "c:\example"}

        $result = Test-Foo

        It "Returns correct result" { # should work
            $result | Should Be "c:\example"
        }
         It "Returns correct result" { # should not work
            $result | Should Be "SomeThingWrong"
        }
    }
}

这篇关于如何在Pester测试中模拟Read-Host?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆