Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running Pester Tests inside Visual Studio

After installing PowerShell Tools for Visual Studio 2015 I created a new Powershell Module Project which creates a MyProject.psd1 a MyProject.psm1 and a MyProject.tests.ps1 file.

MyProject.tests.ps1 file looks like this

Describe "Connect-Database" {
    Context "When Connection To Database" {
        $result = Connect-Database -host localhost -user admin -pass pass
        It "Should Return True" {
            $result | Should Be $True
        }
    }
}

Connect-Database is a function from MyProject.psm1 and is exported via MyProject.psd1

# Functions to export from this module
FunctionsToExport = 'Connect-Database'

Running a powershell console and executing

Import-Module .\MyProject.psd1
Invoke-Pester

works great and returns

Describing Connect-Database
   Context When Connection To Database
    [+] Should Return True 627ms
Tests completed in 627ms
Passed: 1 Failed: 0 Skipped: 0 Pending: 0

Here comes my problem: PowerShell Tools come with a test adapter and my test shows in Test Explorer.

But If I execute it, it always fails with The term Connect-Database is not recognized as cmdlet function script file or operable program

Even adding Import-Module .\MyProject.psd1 to the MyProject.tests.ps1 file does not help. Any ideas how to load my module prior to running the tests?

like image 712
Jürgen Steinblock Avatar asked Sep 02 '25 09:09

Jürgen Steinblock


1 Answers

I added Get-Location | Write-Host to MyProject.tests.ps1 file and figured out that the working directory was C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE

I didn't check that in the first place because I believed the test adapter would just execute Invoke-Pester in the working directory

Eventually I solved this with

Split-Path $PSCommandPath | Set-Location
Import-Module (".\" + (Split-Path -Leaf $PSCommandPath).Replace(".tests.ps1", ".psd1"))
like image 130
Jürgen Steinblock Avatar answered Sep 05 '25 01:09

Jürgen Steinblock