开发者

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 'c开发者_开发百科orrect' 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.


Basically, there are two possibilities:

  1. Use TypeMock Isolator or Moles to mock HttpContext.
  2. Introduce an interface for the whole HttpContext class or just for a UrlHelper and pass an instance of a class that implements that interface into your class. Keyword: Dependency Injection (DI)


I don't know what type of project you're writing this code for, but if it's an MVC project I'd suggest re-writing your code to use HttpContextBase instead - if that's possible. Then you can create a stub or mock of this and inject that for your tests. Request.Url returns System.Uri so you'll have to create an instance of this and set that on your context stub/mock.


Example for 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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜