Context is often a problem when unit testing code, for example if your code utilizes HttpContext.Current this can be a real problem. There are several ways to get around this problem, I'll try and explain the approach we're currently taking, hopefully if someone else out there have a better approach they'll provide a link in comments.

Basically we wrap all the calls to HttpContext.Current in a HttpContextWrapper class, below is a very simplified example to try and get the basics across, you could extend this to include your favourite mocking framework:

 

1 /* 2 * Created by: 3 * Created: 12 February 2007 4 */ 5 6 using System; 7 using System.IO; 8 using System.Web; 9 10 namespace BlogExamples 11 { 12 public class HttpContextWrapper 13 { 14 [ThreadStatic] 15 private static HttpContext _context; 16 17 private static HttpContext Current 18 { 19 get 20 { 21 if (HttpContext.Current == null) 22 { 23 if (_context != null) 24 { 25 StringWriter writer = new StringWriter(); 26 HttpRequest request = new HttpRequest("null.html", "http://localhost/null", ""); 27 HttpResponse response = new HttpResponse(writer); 28 _context = new HttpContext(request, response); 29 } 30 } 31 else 32 { 33 return HttpContext.Current; 34 } 35 return _context; 36 37 } 38 } 39 } 40 }

This approach has one major downfall, namely that you have to use the HttpContextWrapper in your code rather than just straight calls to HttpContext, this means you will need to control the code your trying to test, which for the most part is the case, however as with everything in life, there are exceptions.

How would you solve this problem ? Im quite interested in seeing how other people apporach this as it is a fairly common scenario, leave a comment if you have any suggestions.