1

I have this pester script block. When I run it, the "Test1" fails, which is good. The second "Test2" fail, but I want it to pass. For pester 5 this are the recomandations:

`Put all your code 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 you have a good reason to do so.

All misplaced code will run during Discovery, and its results won't be available during Run.`

This explains why my "Test2" fails. But If I put my code in one the proposed blocks, then I will not be able to use TestCases.

Is there a way to solve the issue ?

Describe "Sample" {
    $test = 1
    $testCase = @(
        @{var1 = $test; ExpectedResult = $true})

    It "Test1" -Tag "Update" -TestCase $testCase {
     param ($var1, $expectedresult)
        $var1 | should -be $null
        $test | should -be 1
    }

    it "Test2" -Tag "Fail" {
        $test | should -be 1
    }
}
Frode F.
  • 52,376
  • 9
  • 98
  • 114
  • 1
    The advice to put your code inside of one of those blocks is for *mostly* everything. One thing that you can and should do during discovery is create your test cases. Test cases are an exception to the rule and are saved for when Pester executes your tests. Think of it like this - Pester is scanning the file for tests before they run during discovery. Because you have built these tests and passed them as a param into the test, it finds them as part of the test and they remain available for use. – Efie Oct 21 '20 at 14:53

1 Answers1

0

As @Efie mentions, code to generate testcases are the common exeption to the rule. A new BeforeDiscovery-block was added in Pester 5.1 that you should use for this type of code.

In general, you should rarely mix concerns regarding re-using $test in your test. Your testcases should include the required variables. Actually, that's how you would pass the variable from Discovery to Run to make it possible, by providing it as a testcase-value. In your example you've done that, so $var1 should be available in the test and should be equal to 1 (same as $test in Discovery).

I often name the hashtable-key the same as the Discovery-variable (test in this scenario) to make the transfer feel seamless.

Frode F.
  • 52,376
  • 9
  • 98
  • 114
  • Also, there's no need for the `param($var1, $expectedresult)` block in Pester v5 when using hashtable for testcases. Each key in the hashtable will automatically get a variable. – Frode F. Aug 03 '22 at 22:16