-
Notifications
You must be signed in to change notification settings - Fork 9
Description
Create a single HttpHelperFakes.cs file which can be easily added to the test projects using nuget.
This should be independent of Unit Test/Mocking frameworks. In fact mocking should not be used at all since most of these frameworks does not work in WP7/WinRT.
Here some sample usage for Facebook C# SDK.
[Fact]
public void Test()
{
var fb = new FacebookClient();
FakeHttpWebRequestWrapper fakeRequest = null;
FakeHttpWebResponseWrapper fakeResponse = null;
fb.HttpWebRequestFactory =
uri => fakeRequest =
new FakeHttpWebRequestWrapper()
.WithRequestUri(uri)
.FakeResponse()
.WithResponseStreamAs(
"{\"id\":\"4\",\"name\":\"Mark Zuckerberg\",\"first_name\":\"Mark\",\"last_name\":\"Zuckerberg\",\"link\":\"http:\\/\\/www.facebook.com\\/zuck\",\"username\":\"zuck\",\"gender\":\"male\",\"locale\":\"en_US\"}")
.WithContentType("text/javascript; charset=UTF-8")
.WithStatusCode(200)
.GetFakeHttpWebRequestWrapper();
dynamic result = fb.Get("4");
Assert.Equal("GET", fakeRequest.Method);
Assert.Equal("https://graph.facebook.com/4", fakeRequest.RequestUri.AbsoluteUri);
Assert.True(fakeRequest.ContentLength == 0);
Assert.IsAssignableFrom<IDictionary<string, object>>(result);
Assert.Equal("4", result.id);
Assert.Equal("Mark Zuckerberg", result.name);
}
This will allow us to fake the entire HttpWebRequest/HttpWebResponse and we will not need to have the actual request. So integration test would not be required. Since it also executes entire code line by line, test coverage is also highly increased.
It also allows us to test the request properties such as checking if the RequestUri was generated correctly or if the HttpMethod was set correctly and so on.
Also add helper methods for Exceptions and no internet connection.
new FakeHttpWebRequest().NoInternetConnection();
Assumed request got executed but when executing response the internet got disconnected.
new FakeHttpWebRequestWrapper()
.WithRequestUri(uri)
.FakeResponse()
.NoInternetConnection()