Skip to content
Jon Wagner edited this page Mar 20, 2013 · 2 revisions

Setup and TearDown

Part of the test process is getting your test scenario to a well-known point before executing the test. With PowerShell code, this often involves setting up variables, files, folders, or other system components. PSate supports setup and teardown blocks that are automatically run before and after each test.

You can add a setup or teardown block to any test group (i.e. TestFixture, TestScope, Describing, or Given) block. Simply add your setup code before the tests, and teardown code after the tests.

In the case below, the variables $x and $y are set up twice, once before each It block.

Describing "Calculator" {
	Given "two numbers" {
		# Setup is called once per test
		$x = 1
		$y = 2

        It "adds them" {
            $x + $y | Should Be 3
        }

        It "subtracts them" {
            $x - $y | Should Be -1
        }
    }
}

BDD-Style tests, it is very common to have the setup reflect the statement/name of the Given blocks.

Another case is setting up and cleaning up files:

Describing "FileWatcher" {
	Given "a file" {
		# Setup
		$file = New-Item -Name "temp.file" -Path $env:temp -Type File -Force

        It "writes to the file" {
			"foo" | Set-Content $file
        }

		# TearDown
		$file | Remove-Item
    }
}

You can have Setup/TearDown at any level of nesting. Setup/TearDown is processed once for each item in the test group. This can help set up and manage complicated scenarios.

TestScope "FolderProcessing" {
	# Setup
	$folder = New-Item -Name "temp.folder" -Path $env:temp -Type Folder -Force

	TestFixture "FileProcessing" {
		# Setup
		$file = New-Item -Name "temp.file" -Path $folder -Type File -Force

        TestCase "writes to the file" {
			"foo" | Set-Content $file
        }

		# TearDown
		$file | Remove-Item
    }

	# TearDown
	$file | Remove-Item
}

Note that when dealing with files, folders, or anything else that can be cleaned up with Remove-Item, check out Temporary Files and Resources.