chevron-thin-right chevron-thin-left brand cancel-circle search youtube-icon google-plus-icon linkedin-icon facebook-icon twitter-icon toolbox download check linkedin phone twitter-old google-plus facebook profile-male chat calendar profile-male
Welcome to Typemock Community! Here you can ask and receive answers from other community members. If you liked or disliked an answer or thread: react with an up- or downvote.
0 votes
Hi,

Is it possible to mock webservices ?? If so Please provide the samples.

Thanks,
Shane
asked by Shane (1.2k points)

1 Answer

0 votes
Hi Shane,

It is possible to mock web services. When your project consumes a web service, there's a class wrapper generated for it. You can mock this class.
Here are a couple of examples.

I've created a local web service (using VS wizard), and I didn't change a thing in that code. The only method there is:
[WebMethod]
public string HelloWorld()
{
     return "Hello World";
}



So, I want to mock this web method. I created a test project, and added the web reference. (To see the generated proxy, click on the reference, then click on ShowAllFiles. Under "reference map" you will find a C# file containing the proxy.)

Now all I need to do is write the tests:
using Microsoft.VisualStudio.TestTools.UnitTesting;
using TestProject1.localhost;
using TypeMock;

namespace TestProject1
{
    [TestClass]
    public class UnitTest1
    {
        [TestMethod]
        public void ReflectiveMocksTestForWebService()
        {
            Mock mockService = MockManager.Mock<Service1>();
            mockService.ExpectAndReturn("HelloWorld", "SomethingElse");

            Service1 myService = new Service1();
            Assert.AreEqual("SomethingElse", myService.HelloWorld());
        }
        
        [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());
        }
    }
}


Simple but powerful.

Let me know if you need further assistance.
answered by gilz (14.5k points)
...