Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing a unit test for a function with a web request

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.

like image 755
dontangg Avatar asked Dec 09 '22 08:12

dontangg


1 Answers

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.

like image 161
mcabral Avatar answered Dec 11 '22 22:12

mcabral