Can I Mock Web Services?

With Typemock Isolator, sure you can!

This came up in the forums. So here’s the explanation again, but with better graphics.

A web service is a great example for mocking dependencies. You have code that accesses the cloud. What if you’re working offline? Or, someone else is working on the service, and has not published it yet, while you’re stuck with the client code and no way to test it? Mocking to the rescue.

imageWhen you consume a web service, a class is generated for the service. The trick to find this proxy code is (thanks Roy!) to click “Show all files” when standing on the web reference. And you get something like this:

See the Reference.cs? That’s where the proxy code is created.
So let’s say we have the original wizard generated service. Here’s the code:

public class Service1 : System.Web.Services.WebService
{
[WebMethod]
public string HelloWorld()
{
return "Hello World";
}
}

For this web method, the generated proxy looks like this:

[Bunch of attributes removed]
public string HelloWorld()
{
object[] results = this.Invoke("HelloWorld", new object[0]);
return ((string)(results[0]));
}

Now that we have type and method we can reference, we can mock it. Here’s an example using reflective mocks:

[TestMethod]
public void ReflectiveMocksTestForWebService()
{
Mock mockService = MockManager.Mock<Service1>();
mockService.ExpectAndReturn("HelloWorld", "SomethingElse");
Service1 myService = new Service1();
Assert.AreEqual("SomethingElse", myService.HelloWorld());
}

And here’s one using Natural mocks:

[TestMethod]
public void NaturalMocksTestForWebService()
{
using (RecordExpectations rec = RecorderManager.StartRecording())
{
Service1 mockService = new Service1();
rec.ExpectAndReturn(mockService.HelloWorld(), "SomethingElse");
}
Service1 myService = new Service1();
Assert.AreEqual("SomethingElse", myService.HelloWorld());
}

There you go: simple yet powerful.

TOP