2

Let's assumed that i've got simple method which gets some data from REST service. Method looks like:

public string GetDataFromRest(string uri) {
 string result = String.Empty;

 using(WebClient web = new WebClient()) {
  result = web.DownloadString(uri);
 }

 return result;
}

So, now i want to create unit test for this method. I don't want to use external REST service but i want fake response from any URI without real conecting to service. Something like every execute of GetDataFromRest(uri) in Unit Test -> always returns some XML.

1 Answers1

1

As the posted answer goes into some detail, part of your problem is you have a dependency on the WebClient class.

A sample wrapper for WebClient could look like:

public interface IWebClient
{
    string DownloadString(string address);
}

public class WebClientWrapper : IWebClient
{
    public string DownloadString(string address)
    {
        using(WebClient web = new WebClient()) {
            return result = web.DownloadString(uri);
        }
    }
}

public class MyClass
{

    private readonly IWebClient _webClient;

    public MyClass(IWebClient webClient)
    {
        _webClient = webClient;
    }

    public string GetDataFromRest(string uri) 
    {
        return _webClient.DownloadString(uri);
    }
}

Now of course going this route means WebClientWrapper can be unit tested with a "less real" URI or what that you specifically control. I've only implemented one method of the WebClient, but this externalizes the dependency within GetDataFromRest from a real URI, as you can now mock the return data. This also helps in that anything else you need a WebClient for, you can now use the wrapper class, and easily mock the returned data, as you are now programming to an interface, rather than a concretion.

Community
  • 1
  • 1
Kritner
  • 13,557
  • 10
  • 46
  • 72