简体   繁体   中英

Mix pester Discovery and Run variables

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
    }
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM