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", " ", $false)
$req.setRequestHeader("Content-Type", "text/xml; charset=utf-8")
$req.setRequestHeader("SOAPAction", " ")
$req = new-object -com "Microsoft.XMLHTTP"
$req.open("POST", " ", $false)
$req.setRequestHeader("Content-Type", "text/xml; charset=utf-8")
$req.setRequestHeader("SOAPAction", " ")
$requestString = '<?xml version="1.0" encoding="utf-8"?>'
$requestString += '<soap:Envelope xmlns:xsi=" " xmlns:xsd=" " xmlns:soap="
$requestString += ' <soap:Body>'
$requestString += ' <TriMax xmlns="
$requestString += ' <x>4</x>'
$requestString += ' <y>8</y>'
$requestString += ' <z>6</z>'
$requestString += ' </TriMax>'
$requestString += ' </soap:Body>'
$requestString += '</soap:Envelope>'
$req.send($requestString)
$response = $req.responseText
write-host "`nResponse is $response`n"
$requestString += '<soap:Envelope xmlns:xsi=" " xmlns:xsd=" " xmlns:soap="
$requestString += ' <soap:Body>'
$requestString += ' <TriMax xmlns="
$requestString += ' <x>4</x>'
$requestString += ' <y>8</y>'
$requestString += ' <z>6</z>'
$requestString += ' </TriMax>'
$requestString += ' </soap:Body>'
$requestString += '</soap:Envelope>'
$req.send($requestString)
$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 "Pass"
}
else {
write-host "**FAIL**"
}
write-host "`nEnd test"