Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to unit test C# Web Service with Visual Studio 2008

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.

like image 434
Steven Behnke Avatar asked Dec 16 '08 17:12

Steven Behnke


People also ask

Can you unit test C?

The most scalable way to write unit tests in C is using a unit testing framework, such as: CppUTest. Unity.

How do you run a unit test?

To run all the tests in a default group, choose the Run icon and then choose the group on the menu. Select the individual tests that you want to run, open the right-click menu for a selected test and then choose Run Selected Tests (or press Ctrl + R, T).


2 Answers

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.

like image 104
Doron Yaacoby Avatar answered Oct 25 '22 10:10

Doron Yaacoby


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).

like image 24
Chris Brandsma Avatar answered Oct 25 '22 10:10

Chris Brandsma