I would like to unit test my web requests, so on top of my head I came up with the solution below.
Since it seems to be working fine, I'm posting it on this site. Though it doesn't feel very dynamic, I would like your input. For example, this solution can't simulate response headers, which I'm also interested in mocking:
public interface IWebRequest
{
Task<string> DownloadString();
}
public class RealWebRequest : IWebRequest
{
private readonly string url;
public RealWebRequest(string url)
{
this.url = url;
}
public Task<string> DownloadString()
{
using (WebClient client = new WebClient())
{
return client.DownloadStringTaskAsync(new Uri(url));
}
}
}
public class FakeWebRequest : IWebRequest
{
private readonly string fakeReponse;
public FakeWebRequest(string fakeReponse)
{
this.fakeReponse = fakeReponse;
}
public Task<string> DownloadString()
{
return Task.Factory.StartNew(() => fakeReponse);
}
}
public class TestClass
{
private readonly IWebRequest request;
public TestClass(IWebRequest request)
{
this.request = request;
}
public async Task<string> DoStuff()
{
return await request.DownloadString();
}
}
"Real" usage example:
IWebRequest realRequest = new RealWebRequest("http://www.test.com");
TestClass test = new TestClass(realRequest);
string realResult = await test.DoStuff();
Unit test usage example:
IWebRequest fakeRequest = new FakeWebRequest("fake response string");
TestClass test = new TestClass(fakeRequest);
string fakeResponse = await test.DoStuff();