my code does this
string domainUrl = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority);
int result = string.Compare(domainUrl, "http://www.facebookmustdie.com");
// do something with the result...
How can I mock this so my unit test passes, do I have to mock the whole HttpContext class? And if that was the case how would I inject that into the code so the 'correct' HttpContext is used when the unit test is run
You don't need to mock it:
var sb = new StringBuilder();
TextWriter w = new StringWriter(sb);
var context = new HttpContext(new HttpRequest("", "http://www.example.com", ""), new HttpResponse(w));
HttpContext.Current = context;
Console.WriteLine(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority));
The HttpContext singleton can't be easily mocked, and don't play well with unit testing either, because it ties you with the IIS infrastructure.
It's true that Moles can do the job too, but the true issue is the heavy couplage with IIS.
You should rather pass the relevant request data (url for exemple in your case) to your function or class, in order to be able to isolate your logic from the infrastructure. This way, you will be able to separate it from IIS, and run it on a testing infrastructure easily.
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