Author Posts

May 11, 2015 at 11:32 am

I am trying to wrap my head around Pester with a relatively simple script that sets the HomeDirectory attribute of an AD account, and optionally sends output to a log file. The script uses Get-ADUser and Set-ADUser, so I am trying to Mock these in my Pester tests. I am not mocking or testing the logging function, and instead let the test create a real log file.

When I run my tests, they all fail with something like:

Expected: {True}
But was:  {}

My log shows the output I expect.

Here is an example of one of three Contexts in my Describe block:

Describe "Set-TheHomeFolder" {
    Mock Set-ADUser {}
    
    Context "When HomeDirectory empty" {
        Mock Get-ADUser { return @{
                'DistinguishedName' = 'CN=TesUser,OU=Users,DC=domain,DC=com';
                'Enabled'           = $True;
                'GivenName'         = 'Test';
                'HomeDirectory'     = '';
                'SamAccountName'    = 'TestUser';
                'Surname'           = 'User'
            }
        }
        $result = Set-TheHomeFolder -samAccountName TestUser
        It "Confirms HomeDirectory value is empty" {
            $HasHomeDirectory | Should Be $false
        }
    }
    ...
}

I have attached sanitized versions of my script, tests. My log looks like this:
"SamAccountName","TimeStamp","CurrentHomeDirectory","NewHomeDirectory","HasHomeDirectory","DirectoriesMatch"
"TestUser","5/11/2015 3:18:41 PM","\\files\users\TestUser","\\files\TestUser","True","False"
"TestUser","5/11/2015 3:18:41 PM","\\files\TestUser","\\files\TestUser","True","True"
"TestUser","5/11/2015 3:18:41 PM","","\\files\TestUser","True","False"

Edited: Splats were missing semicolons.

May 11, 2015 at 11:40 am

The problem is that your Set-TheHomeFolder function doesn't output anything. Your $HasHomeDirectory variable is local to that function, and doesn't get returned to the caller in any way. Because of that, the variables aren't there to be evaluated in your Pester tests.

The way your code is currently written, you'd have to use the $LogFile parameter, import the resulting CSV file, and write your tests based on that file's contents. A better practice would be to have your function just output objects to the pipeline, and let people pipe those results to Export-Csv if they wanted to. Then you could write tests based on the $result variable out in your Tests script.

May 11, 2015 at 11:58 am

Well, that makes all kinds of sense.

Deleted logfile parameter, removed logfile condition, and changed my It blocks to check on $result.HasHomeFolder. Works like a charm!

Thanks, Dave.

May 11, 2015 at 12:06 pm

No problem! 🙂