Well, in my current project, this question appeared very early on. Since, I am doing Test-Driven Development, I need to test my web service data layer, but I don’t need it all of the time. I used a pattern called Constructor based Dependency Injection. This allows you to replace the service with a different implementation. For my situation, the implementation is for removing an external dependency for testing. I removed this dependency, by mocking the object with NMock. NMock allows you to pass parameters, setup return values, exceptions and do sequence actions.
Download location: http://nmock.org/download.html
Now for the implementation, so here come the 2.0 Framework to the rescue. When you add a web service, a reference.cs or (reference.vb) file gets created in the directory with the web service WSDL. Fortunately, this class is created as a partial class; I used this knowledge to create another partial class that I can control. You don’t really want to update the reference.cs or .vb class from the web service, because it can change when you update the web service reference and all of your changes are gone. The summary below details the steps that are required to implement this.
// Provider that will consume the web service.
public class Provider
{
private IService apservice;
public Provider()
this.apservice = new MyWebService();
}
/// <summary>
/// Constructor that allows NMock testing
/// </summary>
/// <param name="service">Interface for Web Service</param>
public Provider(IMyService service)
this.apservice = service;
public string Method1(string name)
return apservice.MyCall(name,string.Empty);
// Interface for the Web Service
public interface IDiscussionService
Results MyCall(string param1,string param2);
// Partial class for the Web Service
public partial class MyWebService : System.Web.Services.Protocols.SoapHttpClientProtocol, IMyService
string IMyService.MyCall(string param1, string param2)
return this.MyCall(param1, param2);
//Unit Test that will NMock the web service[TestMethod] public void GetSitesTest() {
Mockery mock = new Mockery();IMyService service = mock.NewMock<IMyService>();
String expected = “Hello World”;Expect.Once.On(service).Method("MyCall").Will(Return.Value(expected));Provider target = new SiteProvider(service);
string actual = target.Method1(“Name”);
Assert.AreEqual(expected,actual);mock.VerifyAllExpectationsHaveBeenMet();
Tags: NMock, Web Services, Injection, TDD