Pester: I am doing something very wrong

This topic contains 3 replies, has 2 voices, and was last updated by  Dave Wyatt 2 years, 5 months ago.

  • Author
  • #25099

    Robert Derickson

    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:
    "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.

  • #25103

    Dave Wyatt

    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.

  • #25104

    Robert Derickson

    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.

  • #25105

    Dave Wyatt

    No problem! 🙂

You must be logged in to reply to this topic.