纠缠模拟一个改变输出的脚本

Pester Mocking a script that varies output

大家好我写了一个脚本来显示当前用户信息,我想写一个应该模拟输出的Pester测试用例,如果我在函数中没有return怎么办我也为此写了一个测试

function Get-CurrentUserInfo
{

    $domain = [Environment]::UserDomainName
    $user = [Environment]::UserName
    if (!([string]::IsNullOrEmpty($domain))) { $domain = $domain + '\' }

    $currentUser = $domain + $user

    #return $currentUser I have commented out so that it will not return any output
}

这是我的测试用例,当有 return

$here = Split-Path -Parent $MyInvocation.MyCommand.Path
. "$here\Get-CurrentUserInfo.ps1"
Describe "CurrentUser" {
    It "CurrentUser Info" {
        Get-CurrentUserInfo | Should be 'MY-PC\username'
    }
}

这在我的 PC 上运行良好,但是当我在其他 PC 上执行相同的操作时,它会失败,所以我怎样才能使它独一无二

您可以模拟环境变量:

$here = Split-Path -Parent $MyInvocation.MyCommand.Path
. "$here\Get-CurrentUserInfo.ps1"
Describe "CurrentUser" {
    $originaldomain = [Environment]::UserDomainName
    $originaluser = [Environment]::UserName

    [Environment]::UserDomainName = "testdomain"
    [Environment]::UserName = "testuser"


    It "CurrentUser Info" {
        Get-CurrentUserInfo | Should be 'testdomain\testuser'
    }

    [Environment]::UserDomainName = $originaldomain 
    [Environment]::UserName = $originaluser
}