Home > Back-end >  Pester and test internal function
Pester and test internal function

Time:01-27

In my Pester-test I've created a function to Test-SQLConnection. I can test the function like this:

param(
 [string]
 $Server,
 [string]
 $Database

  )

  BeforeAll {
  $testDbServer = $Server
  $testDatabase = $Database

  }

Describe "Status Databaseserver" {
  It "Should login with integrated security" {
  
   Test-SQLConnection "Data Source=$testDbServer; Database=$testDatabase;Integrated 
 Security=True"; | Should -BeTrue 
}
}

function Test-SQLConnection
{    
 [OutputType([bool])]
 Param
  (
    [Parameter(Mandatory=$true,
                ValueFromPipelineByPropertyName=$true,
                Position=0)]
    $ConnectionString
  )
   try
    {
      $sqlConnection = New-Object System.Data.SqlClient.SqlConnection $ConnectionString;
      $sqlConnection.Open();
      $sqlConnection.Close();

      return $true;
  }
   catch
  {
    return $false;
  }
 }

This approach works when I run the test locally on my machine. But when I test from Azure release pipeline I get this error:

CommandNotFoundException: The term 'Test-SQLConnection' is not recognized as the name of a cmdlet, function, script file, or operable program.

What am I doing wrong here?

CodePudding user response:

Per the comments, your function needs to be in the BeforeAll block because with Pester v5 and newer Pester now performs a "discovery" phase before executing your tests:

All code should now be put into It, BeforeAll, BeforeEach, AfterAll, or AfterEach. Put no code directly into Describe, Context or on the top of your file without wrapping it in one of these blocks (unless for good reason).

If code is not put in the proper place, it will run in Discovery, and the results will not be available during Run. During the Run phase, the internal tree of containers, blocks, and tests are run.

-- https://www.sapien.com/blog/2021/01/20/migrating-from-pester-4-to-pester-5/

I suspect what was occurring for you is that your local machine has an older version of Pester, but when run on Azure DevOps its using the latest.

  • Related