Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I mock Request.Url.GetLeftPart() so my unit test passes

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

like image 949
Rob Avatar asked Dec 05 '22 23:12

Rob


2 Answers

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));
like image 184
jeroenh Avatar answered Dec 09 '22 14:12

jeroenh


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.

like image 36
Eilistraee Avatar answered Dec 09 '22 15:12

Eilistraee