我如何模拟Request.Url.GetLeftPart()以便我的单元测试通过

Rob*_*Rob 4 c# asp.net unit-testing

我的代码做到了这一点

string domainUrl = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority);
int result = string.Compare(domainUrl, "http://www.facebookmustdie.com");
// do something with the result...
Run Code Online (Sandbox Code Playgroud)

我如何模拟这个以便我的单元测试通过,我是否必须模拟整个HttpContext类?如果是这种情况,我将如何将其注入代码中,以便在运行单元测试时使用"正确的"HttpContext

jer*_*enh 14

你不需要嘲笑它:

        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));
Run Code Online (Sandbox Code Playgroud)