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.
When 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.WebServiceFor this web method, the generated proxy looks like this:
{
[WebMethod]
public string HelloWorld()
{
return "Hello World";
}
}
[Bunch of attributes removed]Now that we have type and method we can reference, we can mock it. Here's an example using reflective mocks:
public string HelloWorld()
{
object[] results = this.Invoke("HelloWorld", new object[0]);
return ((string)(results[0]));
}
[TestMethod]And here's one using Natural mocks:
public void ReflectiveMocksTestForWebService()
{
Mock mockService = MockManager.Mock<Service1>();
mockService.ExpectAndReturn("HelloWorld", "SomethingElse");
Service1 myService = new Service1();
Assert.AreEqual("SomethingElse", myService.HelloWorld());
}
[TestMethod]There you go: simple yet powerful.
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());
}
0 comments:
Post a Comment