Last week we spent some time in the office here getting to grips with Pester. I’ve written some Pester tests in a few projects I’ve got in GitHub, most notably PoshSSDTBuildDeploy (henceforth known as PBD) and have them running in the VSTS CI build here and the Publish build here. So I felt I was quite familiar with Pester testing.

But one thing I had missing in my tests was mocking. To be honest, I was a little confused by it. “How can you mock a SQL Server Instance?” I said out loud, especially as PBD build and deploys to something external of the module. “You don’t” was the response. Right so, what exactly is mocking? In the context of Pester, mocking is faking a result of any existing command within the scope of a Describe or Context block, so as to test that the result is correct. Case in point; PBD requires a minimal version of .NET to be installed. This version is checked prior to downloading the Nuget packages required. This is an excerpt from InstallMicrosoftSqlServerDacFxx64 -

$TestDotNetVersion = Test-NetInstalled -DotNetVersion "4.6.1"
    Write-Host ".NET Version is $($TestDotNetVersion.DotNetVersion), DWORD Value is $($TestDotNetVersion.DWORD) and Required Version is $($TestDotNetVersion.RequiredVersion)" -ForegroundColor White -BackgroundColor DarkMagenta
    if ($TestDotNetVersion.DWORD -le 394254) {
        Throw "Need to install .NET 4.6.1 at least!"
    $nugetArgs = @("install","Microsoft.SqlServer.DacFx.x64","-ExcludeVersion","-OutputDirectory",$WorkingFolder)
    if ($DacFxx64Version) {
        if ($DacFxx64Version -lt "130.3485.1") {
            Throw "Lower versions than 130.3485.1 will NOT work with Publish-DatabaseDeployment. For more information, read the post https://blogs.msdn.microsoft.com/ssdt/2016/10/20/sql-server-data-tools-16-5-release/"            
        $nugetArgs += "-version",$DacFxx64Version

Here, we can see that the function Test-NetInstalled goes and checks what version of .NET is installed prior to continuing. So if we want to check the path where we throw an exception, we have two choices: We can either install multiple versions of .NET during the testing, or we can mock the result of the call to Test-NetInstalled. In the test of Install-MicrosoftSqlServerDacFxx64 we mock the result of that function so that we can anticipate the error being thrown.

With thanks to bjh1977 for showing mw how mocking works. There’s a good example of how Arrange, Act and Assert works for unit testing in the newly added tests.