0

大家好,我已经编写了一个脚本来显示当前用户信息,我想编写应该模拟输出的 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
}

这是我返回时的测试用例

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

这适用于我的电脑,但是当我在其他电脑上执行相同的操作时,它会失败,所以我怎样才能让它独一无二

4

1 回答 1

1

您可以模拟环境变量:

$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
}
于 2016-08-18T10:00:22.343 回答