views:

6051

answers:

5

How are you supposed to unit test a web service in C# with Visual Studio 2008? When I generate a unit test it adds an actual reference to the web service class instead of a web reference. It sets the attributes specified in:

http://msdn.microsoft.com/en-us/library/ms243399(VS.80).aspx#TestingWebServiceLocally

Yet, it will complete without executing the test. I attempted to add the call to WebServiceHelper.TryUrlRedirection(...) but the call does not like the target since it inherits from WebService not WebClientProtocol.

Thanks, Steven

+1  A: 

You can add a service reference to your unit test project or generate your client stub and put the class in your unit test project.

JoshBerke
Yes, I did that. I just was curious how you were supposed to do it the "Microsoft way." AKA the way the MSDN documents specify and how the unit test gets auto-generated.
Steven Behnke
my bad I missed that part. I always keep my web services implementation as small as possible and test my objects instead much easier;-)
JoshBerke
+8  A: 

What I usually do is not test directly against the web-service, but to try and put as little code as possible in the service, and call a different class which does all the real work. Then I write unit tests for that other class. It turns out that class can sometimes be useful outside of the web-service context, so this way - you gain twice.

Doron Yaacoby
+5  A: 

If you are writing a web service, try to put all logic in another (testable) layer. Each Web method should have a little code as possible. Then you will have little reason to test the web method directly because you can test the underlying layers.

[WebMethod] public void DoSomething() { hander.DoSomething(); }

If you are consuming a web method, wrap the generated caller in a class wrapper, and implement an interface for the class wrapper. Then, anytime you need to call the web service, use the interface to call the method. You want to use the interface so as to make the class wrapper swappable during testing (using Rhino Mocks, Moq, or TypeMock).

Chris Brandsma
A: 

Above my web method unit tests, I have the following:

// TODO: Ensure that the UrlToTest attribute specifies a URL to an ASP.NET page (for example,
// http://.../Default.aspx). This is necessary for the unit test to be executed on the web server,
// whether you are testing a page, web service, or a WCF service.
[HostType("ASP.NET")]
[UrlToTest("http://localhost/MyWebService")]

In addition to the usual:

[TestMethod()]
[DeploymentItem("MyWebService.dll")]

This code came about from using the Visual Studio 2008 Unit Test Wizard.

Sarah Vessels
A: 

I had problems with this as well, so i use this workaround: http://techkn0w.wordpress.com/2009/07/01/unit-testing-an-asmx-web-service-in-visual-studio-2008/

Ra