mock HttpContext.Current.Server.MapPath using Moq?

前端 未结 4 1897
一生所求
一生所求 2020-12-31 08:26

im unit testing my home controller. This test worked fine until I added a new feature which saves images.

The method that’s causing the issue is this below.

4条回答
  •  醉梦人生
    2020-12-31 09:04

    Below works for me.

    string pathToTestScripts = @"..\..\..\RelatavePathToTestScripts\";
    string testScriptsFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, pathToTestScripts);
    
    var server = new Mock(); // Need to mock Server.MapPath() and give location of random.ps1
    server.Setup(x => x.MapPath(PowershellScripts.RANDOM_PATH)).Returns(testScriptsFolder + "random.ps1");
    
    var request = new Mock(); // To mock a query param of s=1 (which will make random.ps1 run for 1 second)
    request.Setup(x => x.QueryString).Returns(new System.Collections.Specialized.NameValueCollection { { "s", "1" } });
    
    var httpContext = new Mock();
    httpContext.Setup(x => x.Server).Returns(server.Object);
    httpContext.Setup(x => x.Request).Returns(request.Object);
    
    YourController controller = new YourController();
    controller.ControllerContext = new ControllerContext(httpContext.Object, new RouteData(), controller);
    

提交回复
热议问题