Unit Testing .NET Code That Requires Web Server Responses

Sometimes we have an object which requires a Web server response to work properly. How are we gonna unit test it? Do we need an actual Web server returning all the responses we want for testing? Apparently we don’t because in .NET we can associate our requests with particular responses using WebRequest.RegisterPrefix

I have found this solution in a blog here and simplified it a little bit.

Basically what we need is a Creator which creates WebRequest which creates WebResponse.

That’s all. Yes, it’s that simple for our simple case.

Now we need a unit test:

Summary:

I have found a very easy way to mock Web server responses

Leave a Reply

Your email address will not be published. Required fields are marked *