Unit Testing with PowerShell, Part II

Let’s continue looking at using PowerShell for very lightweight unit testing in a .NET environment. In order to perform unit testing, the first technique you must know how to perform is calling the method under test from PowerShell — and I showed how to do that in my last blog entry. Another requirement for unit testing is the ability to iterate through a text file — assuming you have your test case data stored that way. Suppose I have file TestCases.txt:
Each line represents one test case. For example, the first line means input point 1 is (3,0), point 2 is (0,4), and the expected result is 5.00.
I can use PowerShell to read through such a file like this:
# readFile.ps1
$file = get-content ‘TestCases.txt’
foreach ($line in $file)
  $tokens = $line.split(‘:’)
  $x1 = $tokens[0]
  $y1 = $tokens[1]
  $x2 = $tokens[2]
  $y2 = $tokens[3]
  $expected = $tokens[4]
  # process extracted values here
# end script
The script should be fairly self explanatory. I use the get-content PowerShell cmdlet to read the entire contents of the test case file into an interna object. I use the foreach control structure to explicitly iterate through each line. And I use the intrinsic split() method to parse each line. Very easy and very powerful.
This entry was posted in Software Test Automation. Bookmark the permalink.