Test array of values in a loop of assertions?

66 views
Skip to first unread message

cra...@gmail.com

unread,
Jun 25, 2015, 5:05:25 PM6/25/15
to pes...@googlegroups.com
Assuming a simple command:

# Invoke-Foo.ps1
function invoke-foo {
    param
(
       
[int]$Value
   
)
    $value
* 2
}

Is this an acceptable way to test multiple values:

# Invoke-Foo.Tests.ps1
$here
= Split-Path -Parent $MyInvocation.MyCommand.Path
$sut
= (Split-Path -Leaf $MyInvocation.MyCommand.Path).Replace(".Tests.", ".")
. "$here\$sut"

Describe "invoke-foo" {

    $Orignals
=@(2,4,6)

    $current
=$null

   
BeforeEach {
       
Write-Host 'BeforeEach'
       
Write-Host "Current: $Current"
   
}
   
AfterEach {
       
Write-Host 'AfterEach'
       
Write-Host "Current: $Current"
   
}

    $Orignals
| % {
        $current
=$_
       
It "Should return $_ x 2" {
       
            $Actual
= Invoke-Foo $current

            $Actual
| Should Be ($current*2)

       
}

   
}
}

I'm especially interested in utilizing the `BeforeEach` and `AfterEach` block with the value being tested in the `It` block.

Is there a more-efficient way to do so?

Dave Wyatt

unread,
Jun 25, 2015, 10:21:07 PM6/25/15
to pes...@googlegroups.com
You can write your own loops like that, if you want.  You can also use the -TestCases parameter of the It command, which looks something like this:

Describe "invoke-foo" {
    $testCases = @(
        @{ Value = 2; ExpectedResult = 4 }
        @{ Value = 4; ExpectedResult = 8 }
        @{ Value = 6; ExpectedResult = 12 }
    )

    It "Should return <Value> x 2 (<ExpectedResult>)" -TestCases $testCases {
        param ($Value, $ExpectedResult)

        $Actual = Invoke-Foo $Value
        $Actual | Should Be $ExpectedResult

cra...@gmail.com

unread,
Jun 26, 2015, 11:59:18 AM6/26/15
to pes...@googlegroups.com
Is there a way to pass the current values of $value and $expecteresult to the BeforeEach and AfterEach blocks? 

This doesn't work:

    BeforeEach -TestCases $testCases {

        param
($Value, $Expected)

       
Write-Host "Value: $value"
       
Write-Host "Expected: $Expected"

   
}

Manuel Henke

unread,
Jun 30, 2015, 8:29:08 AM6/30/15
to pes...@googlegroups.com
Describe "invoke-foo" {
    $testCases
= @(
       
@{ Value = 2; ExpectedResult = 4 }
       
@{ Value = 4; ExpectedResult = 8 }
       
@{ Value = 6; ExpectedResult = 12 }
   
)

   
It "Should return <Value> x 2 (<ExpectedResult>)" -TestCases $testCases {
        param
($Value, $ExpectedResult)
        $Actual
= Invoke-Foo
$Value
        write
-verbose -Message ('Actual: {0}' -f $Actual) -Verbose
        $Actual
| Should Be $ExpectedResult
   
}
}
Reply all
Reply to author
Forward
0 new messages