Wednesday, 2 April 2008

Testing .asmx Web Services in Visual Studio 2008

I was trying to test an asmx-style web-service with Visual Studio 2008. Using the "wizard way" created me a TestMethod that looks like this:-


[TestMethod()]
[HostType("ASP.NET")]
[UrlToTest("http://localhost/Website/Services/")]
public void GetMainArticlesTest()
{
Articles target = new Articles();
XmlDocument actual;
actual = target.GetMainArticles();
//Test goes here
Assert.IsNotNull(actual);
}

This looks fine, but when I try to run it, I get 403 Forbidden errors. I spent some time trying to rectify this, but didn't get anywhere. There are hints on the web that this method of running tests does not work with some methods of authentication...
(We also had problems debugging tests like the above - I think it runs in a brand new process each time which is not connected to automatically.)

I then tried removing the HostType and UrlToTest attributes. This appears to work, but in fact the Test Runner is just creating a copy of the Articles service class directly, without going through the .asmx page, and things like HttpServer do not exist, which causes problems (in my case, the necessary XSLT files are not available).

So going back to first principles, I added a Web Reference for the Articles.asmx to my Test Project (tried Web Service Reference - doesn't seem to want to work), and then created a new TestMethod like so...

[TestMethod()]
public void GetMainArticlesTest()
{
ArticlesService.Articles service = new ArticlesService.Articles();
XmlNode results = service.GetMainArticles();
//Test goes here
Assert.IsNotNull(results);
}

This is much happier now. It works and I can debug the test directly (debugging the web service itself requires attaching to w3wp).

No comments: