mock HttpContext.Current.Server.MapPath using Moq?

前端 未结 4 1929
一生所求
一生所求 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:18

    It is sometimes handy to just mock the call to server.MapPath. This solution works for me using moq. I only mock the base path to the application.

            _contextMock = new Mock();
            _contextMock.Setup(x => x.Server.MapPath("~")).Returns(@"c:\yourPath\App");
            _controller = new YourController();
            _controller.ControllerContext = new ControllerContext(_contextMock.Object, new RouteData(), _controller);
    

    In your controller you can now user Server.MapPath("~").

提交回复
热议问题