How can I make fun of Request.Url.GetLeftPart () so that my unit test passes

my code does it

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 that my unit test passes, do I need to make fun of the whole HttpContext class? And if that were the case, how would I inject this into the code, so the “correct” HttpContext will be used when the unit test is run

+3
source share
5 answers

The HttpContext syntax cannot be easily ridiculed and does not work very well with unit testing, as it connects you to the IIS infrastructure.

It is true that Mols can do the job too, but the true problem is the poor connection with IIS.

(url ) , . , IIS .

+2

:

        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));
+12

, :

0

I don’t know what type of project you are writing this code for, but if it is an MVC project, I would suggest rewriting your code instead of HttpContextBase - if possible. You can then create a stub or mock this and enter this for your tests. Request.Url returns System.Uri, so you need to instantiate this and set it to your stub / mock context.

0
source

Example above:

namespace Tests
{
   [TestClass()]
   public class MyTests
   {
      [ClassInitialize()]
      public static void Init(TestContext context)
      {
        // mock up HTTP request
        var sb = new StringBuilder();
        TextWriter w = new StringWriter(sb);
        var httpcontext = new HttpContext(new HttpRequest("", "http://www.example.com", ""), new HttpResponse(w));

        HttpContext.Current = httpcontext;

      }
      [TestMethod()]
      public void webSerivceTest()
      {
        // the httpcontext will be already set for your tests :)
      }
   }
}
0
source

All Articles