1

I want to set up powershell script testing but also limit the scope to functions. myscript.ps1 contains internal functions with each their own parameter dependencies also, but I will not test them, only interested in Get-Something.

  • How do I import the function from the script to my test without running the script?

myscript.ps1

<#
.SYNOPSIS
    Script with functions.
#>

Param (
    [string]$myVar,
    [string]$myVar2
)
function Get-SomeThing {
    Param (
        [string]$myVariable,
        [string]$myVariable2
    )

    $foo = "$($myVariable) $($myVariable2)"

    return $foo
}
function Get-SomeThingElse {
        Param (
            [string]$myVariableAgain,
            [string]$myVariableAgain2
        )
        $bar = Get-SomeThing -myVariable $myVariableAgain -myVariable2 $myVariableAgain2
    
        $foo2 = "$($bar) $($myVariable) $($myVariable2)"
    
        return $foo2
}

Get-SomeThingElse -myVariableAgain $myVar -myVariableAgain2 $myVar2

my.Tests.ps1

Describe 'My Tests' {
    BeforeAll {
        $myVar = 'Hello'
        $myVar2= 'World'
    }
    It 'Test Hello World' {
        (Get-SomeThing -myVariable $myVar -myVariable2 $myVar2) | Should Be 'Hello World'
    }
}

directories

Root/
-Tests/
--my.Tests.ps1
-myscript.ps1
user16908085
  • 95
  • 10

1 Answers1

0

As mentioned in the comments, you should think about building a module for these functions. As a stop gap before you get to that complexity, I would create a separate ps1 file that just contains the function definitions you want to test, and dot source them into myscript.ps1 and my.Tests.ps1

Root/
-Tests/
--my.Tests.ps1
-myscript.ps1
-myscriptfunctions.ps1

to dot source myscriptfunctions.ps1 from myscript.ps1:

. "$PSScriptRoot/myscriptfunctions.ps1"

to dot source myscriptfunctions.ps1 from my.Tests.ps1:

. "$(Split-Path $PSScriptRoot -Parent)/myscriptfunctions.ps1"

I like this pattern because for quick and dirty functions, I just declare them in myscript.ps1. As my code matures, and I need to test/make the functions better I move them into myscriptfunctions.ps1 and can write some quick tests. And then if I continue to use the function, I can put them into one of my modules where I ostensibly have better tests/CI infrastructure to ensure these functions are the most reliable.

Brandon McClure
  • 1,329
  • 1
  • 11
  • 32