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.