tags:

views:

972

answers:

3

Hi!

In a upcoming project I'm going to write an application in C# which partly has to communicate with a HTTP server. I'm very fond of writing my code TDD-style, and I would just love it if I could mock all of the HTTP requests in my tests.

Does any one here know about an easly mockable HTTP client framework?

Ps. I usually use Moq for mocks. If you know of some free mocking framework that would be better to mock HTTP requests, that would be nice too.

A: 

I don't think there is actually any framework which handles the things you want to archive. After all only you know what each Http request should do. So basically you have 2 options:

  1. Making the calls and using a dummy implementation on the other side. This may be a simple console application which returns dummy data. If you need more logic I would consider using an object database - in my opinion they fit perfectly for these applications.
  2. Use a mock- implementation on the application side. If this implementation has much logic don't use any mocking framework - create a custom mock class which has all the logic.

Hope this helps

ollifant
+5  A: 

DotNetOpenId, an open source project from which you may reuse code, uses HTTP wrapper classes through which all calls are made. During testing, a mock HTTP handler is injected so that the responses can be programmatically set before the call is made. It has another mode where it hosts its own ASP.NET site so that the full actual stack can be exercised.

This works well, although it hasn't been pulled out as a standalone solution. If you're interested in reusing it, here are some relevant links to the source. And you can ask for help integrating it at [email protected].

Live one: StandardWebRequestHandler.cs

Mocks: MockHttpRequest.cs, TestWebRequestHandler.cs

Andrew Arnott
Thanks! Very helpful!
theringostarrs
+4  A: 

I suggest you use the framework support for this i.e. System.Net.WebRequest.

Define a really simple interface, and a simple wrapper for the webrequest. This way you will get what you want, and won't add an external dependency for something the framework already does well.

eglasius