Moq: unit testing a method relying on HttpContext

后端 未结 6 1020
情话喂你
情话喂你 2020-11-29 03:53

Consider a method in a .NET assembly:

public static string GetSecurityContextUserName()
{             
 //extract the username from request              
 st         


        
6条回答
  •  感动是毒
    2020-11-29 04:34

    [TestInitialize]
    public void TestInit()
    {
      HttpContext.Current = new HttpContext(new HttpRequest(null, "http://tempuri.org", null), new HttpResponse(null));
    }
    

    Also you can moq like below

    var controllerContext = new Mock();
          controllerContext.SetupGet(p => p.HttpContext.Session["User"]).Returns(TestGetUser);
          controllerContext.SetupGet(p => p.HttpContext.Request.Url).Returns(new Uri("http://web1.ml.loc"));
    

提交回复
热议问题