Testing an ASP.NET Web Service using PowerShell

In a recent post I described a very easy way to programmatically test an ASP.NET Web service using JavaScript and the XMLHTTP COM object. Windows PowerShell, the new command shell and scripting language, has generated a lot of interest in the testing community here at Microsoft, and so, several people asked me about testing a Web service using PowerShell. Well, because PowerShell can call COM objects, one easy way of testing a Web service with PowerShell is almost identical to testing with JavaScript. In both cases the idea is to use an XMLHTTP object to send a request to the Web service under test, fetch the XML response, and examine the response for an expected value. Suppose you create an ASP.NET Web Service which contains a dummy Web Method named TriMax(x,y,z) which simply returns the largest of integers x, y, and z. Listed below is the basic skeleton of a PowerShell test automation script which sends 4,8,6 to TriMax() and looks for a result of 8. The XMLHTTP object is normally used to send asynchronous requests to an AJAX Web application, but by setting the second parameter to "false" you can send a synchronous request. You can determine the HTTP POST data using Visual Studio by instructing the ASP.NET Web Service to run — it gives you the POST template that you can copy-paste into your PowerShell script.
# testWebService.ps1
write-host "`nBegin Web service test"
$req = new-object -com "Microsoft.XMLHTTP"
$req.open("POST", "http://localhost/MyService/Service.asmx", $false)
$req.setRequestHeader("Content-Type", "text/xml; charset=utf-8")
$req.setRequestHeader("SOAPAction", "http://tempuri.org/TriMax")
$requestString  = ‘<?xml version="1.0" encoding="utf-8"?>’
$requestString += ‘<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">’
$requestString += ‘  <soap:Body>’
$requestString += ‘    <TriMax xmlns="http://tempuri.org/">’
$requestString += ‘      <x>4</x>’
$requestString += ‘      <y>8</y>’
$requestString += ‘      <z>6</z>’
$requestString += ‘    </TriMax>’
$requestString += ‘  </soap:Body>’
$requestString += ‘</soap:Envelope>’
$response = $req.responseText
write-host "`nResponse is $response`n"
if ($response.indexOf("<TriMaxResult>8</TriMaxResult>") -ge 0) {
  write-host "Pass"
else {
  write-host "**FAIL**"
write-host "`nEnd test"
This entry was posted in Software Test Automation. Bookmark the permalink.