Search code examples
powershell-3.0pester

Pester Mocking a script that varies output


Hi all I have written a script to display the current user info, I would like to write Pester test case that should mock the output, also if I don't have return in the function how can I write a test for that too

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 is my test case when there is return

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

Which works fine with my PC but when I execute the same in other PC it will fail so how can I make it unique


Solution

  • You can mock the env variables:

    $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
    }