Janek
Janek

Reputation: 1491

How to unit test a class that consumes a web service?

I have a class (lets call it A) that:

I started to create a unit test that:

Although that web service has plenty of methods.

Upvotes: 5

Views: 6600

Answers (3)

Nylo Andy
Nylo Andy

Reputation: 152

When you unit test a class, you always want to make sure to only test that class and not include its dependencies. To do that, you will have to mock your WS to have it return dummy data when methods are called. Depending on your scenarios, you do not have to mock ALL the methods for each test, I would say only those that are used.

For an example about mocking, you can read this article: http://written-in-codes.blogspot.ca/2011/11/unit-tests-part-deux.html

Upvotes: 1

Greg Smith
Greg Smith

Reputation: 2469

You should create a wrapper interface around your webservice, and make your class under test take a dependency on that interface, rather than directly on the webservice; you can then mock the interface. Only make that interface expose the methods of the webservice that you find interesting. This is known as a facade pattern, and is detailed here.

Without having a clue about what you're testing, aim for something like this:

public interface IWebserviceWrapper
{
    Whatever DoStuff(int something);
}

public class WebserviceWrapper : IWebserviceWrapper
{
    private WebService _theActualWebservice;

    public WebserviceWrapper(Webservice theService)
    {
        _theActualWebService = theService;
    }

    public Whatever DoStuff(int something)
    {
         return _theActualWebservice.DoSomething(something);
    }

}

Then your test would look like this (in this case, using MOQ)

public void Test_doing_something()
{
    Mock<IWebserviceWrapper> _serviceWrapperMock = new Mock<IWebserviceWrapper>();

    _serviceWrapperMock.SetUp(m => m.DoStuff(12345)).Returns(new Whatever());

    var classUnderTest = new ClassUnderTest(_serviceWrapperMock.Object);

    var result = classUnderTest.Dothings(12345);

    Assert.Whatever....

}

Upvotes: 5

damiankolasa
damiankolasa

Reputation: 1510

Short answer Yes :). Long answer you should use some kind of mocking lib for example: http://code.google.com/p/mockito/ and in your unit test mock the WS stub and pass it to the tested class. That is the way of the force :)

Upvotes: 1

Related Questions