This is a function that I want to write a unit test for:
public object RequestAndSerializeJSON(string url, Type type) {
var request = (HttpWebRequest)WebRequest.Create(url);
request.Accept = "application/json";
var response = request.GetResponse();
using (var responseStream = response.GetResponseStream())
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(type);
return serializer.ReadObject(responseStream);
}
}
My first thought for testing this was to pass in a path to a file with test data in it for the url, but I can't do that because I'm casting it to an HttpWebRequest
and it throws an error with a file path because it creates a FileWebRequest
for file paths.
What is a good way to do this? I'm using the Visual Studio Test Tools for my testing.
You have a problem here. As you can see, your code does two things. It gets the request and then it creates an object.
If you want to unit-test it, i suggest splitting the functionality (which is a nice thing to do anyways)
(rule of thumb: if the name of your function is very long, uses the 'and' word or describes multiple things then you should be refactoring it. we want small methods with small responsabilities, so we can replace them or extend them or do something with them more easily in the future).
Something like..
public WebRequest GetRequest(string url);
public object DeSerializeJSON(WebRequest request, Type type);
might work.
Now you can inject a mocked request in a test method and test the functionality accordingly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With