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:
1 |
<span class="kwrd">public</span> <span class="kwrd">class</span> Service1 : System.Web.Services.WebService<br />{<br /> [WebMethod]<br /> <span class="kwrd">public</span> <span class="kwrd">string</span> HelloWorld()<br /> {<br /> <span class="kwrd">return</span> <span class="str">"Hello World"</span>;<br /> }<br />} |
For this web method, the generated proxy looks like this:
1 |
[Bunch of attributes removed]<br /><span class="kwrd">public</span> <span class="kwrd">string</span> HelloWorld()<br />{<br /> <span class="kwrd">object</span>[] results = <span class="kwrd">this</span>.Invoke(<span class="str">"HelloWorld"</span>, <span class="kwrd">new</span> <span class="kwrd">object</span>[0]);<br /> <span class="kwrd">return</span> ((<span class="kwrd">string</span>)(results[0]));<br />} |
Now that we have type and method we can reference, we can mock it. Here’s an example using reflective mocks:
1 |
[TestMethod]<br /><span class="kwrd">public</span> <span class="kwrd">void</span> ReflectiveMocksTestForWebService()<br />{<br /> Mock mockService = MockManager.Mock<Service1>();<br /> mockService.ExpectAndReturn(<span class="str">"HelloWorld"</span>, <span class="str">"SomethingElse"</span>);<br /> Service1 myService = <span class="kwrd">new</span> Service1();<br /> Assert.AreEqual(<span class="str">"SomethingElse"</span>, myService.HelloWorld());<br />} |
And here’s one using Natural mocks:
1 |
[TestMethod]<br /><span class="kwrd">public</span> <span class="kwrd">void</span> NaturalMocksTestForWebService()<br />{<br /> <span class="kwrd">using</span> (RecordExpectations rec = RecorderManager.StartRecording())<br /> {<br /> Service1 mockService = <span class="kwrd">new</span> Service1();<br /> rec.ExpectAndReturn(mockService.HelloWorld(), <span class="str">"SomethingElse"</span>);<br /> }<br /> Service1 myService = <span class="kwrd">new</span> Service1();<br /> Assert.AreEqual(<span class="str">"SomethingElse"</span>, myService.HelloWorld());<br />} |
There you go: simple yet powerful.