Mock Backup-DbaDatabase using Pester is not working

65 Views Asked by At

I have created a Powershell function that uses the Backup-DBADatabase in the DBATools module. It has some additional logic to create a framework for others to use consistently across the company. As a result I would like to use Pester to mock Backup-DBADatabase and test my other logic in the function.

I have two problems that are confusing me.

  1. When I say "Mock -CommandName Test-Path { $False }" my "Assert-VerifiableMock" still passes. It should fail if I am understanding the test correctly

  2. In this example Backup-DBADatabase is still being executed.

    Import-Module DBATools
    Function Backup-DBTemplate {
        [CmdletBinding(SupportsShouldProcess=$true)]
        Param (
            [Parameter(valueFromPipeline)]
                [string]$ServerInstance,
            [string]$DatabaseName,
            [string]$BackupDirectory
        )
        $FileExists = Test-Path "$BackupDirectory\$DatabaseName.bak" -Verbose:$VerbosePreference
    
        IF($FileExists ) {
            remove-item "$BackupDirectory\$DatabaseName.bak" -WhatIf:$WhatIfPreference -Verbose:$VerbosePreference
        }
        Backup-DbaDatabase -SqlInstance $ServerInstance -Path "$BackupDirectory" -Database $DatabaseName -FilePath "$DatabaseName.bak" -ReplaceInName -Checksum -CopyOnly -IgnoreFileChecks -WhatIf:$WhatIfPreference -Verbose:$VerbosePreference
    }
    describe -Tag 'DBATools' 'Backup-DBTemplate' {
    
        Context "BackupDirectory file Exists" {
            Mock -CommandName Remove-Item -Verifiable
            mock -CommandName Test-Path { $true }
            Mock -ModuleName 'DBATools' -CommandName 'Backup-DbaDatabase'
    
            It 'Remove Backup if it exists' {
                Backup-DBTemplate -ServerInstance localhost -DatabaseName DBname -BackupDirectory C:\temp
                Assert-VerifiableMock 
            }
        }
        
    }

Any help would be appreciated. Thanks,

0

There are 0 best solutions below