asp.net – 如何单元测试使用HostingEnvironment.MapPath的代码

我有一些使用HostingEnvironment.MapPath的代码,我想进行单元测试。

如何设置HostingEnvironment,以便在我的单元测试(mstest)项目中返回一个路径,而不是空值?

解决方法

为什么在ASP.NET MVC应用程序中有一个依赖于HostingEnvironment.MapPath的代码,您可以访问像HttpServerUtilityBase这样的对象,这样可以实现这一点,哪些可以容易地被嘲笑和单元测试?

让我们举个例子:一个使用我们要单元测试的抽象服务器类的控制器动作:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        var file = Server.MapPath("~/App_Data/foo.txt");
        return View((object)file);
    }
}

现在,有很多方法来单元测试这个控制器的动作。我个人喜欢使用MVcContrib.TestHelper

但是让我们看看我们如何使用一个嘲弄的框架来开箱即可。这个例子我使用Rhino Mocks:

[TestMethod]
public void Index_Action_Should_Calculate_And_Pass_The_Physical_Path_Of_Foo_As_View_Model()
{
    // arrange
    var sut = new HomeController();
    var server = MockRepository.GeneratePartialMock<HttpServerUtilityBase>();
    var context = MockRepository.GeneratePartialMock<HttpContextBase>();
    context.Expect(x => x.Server).Return(server);
    var expected = @"c:\work\App_Data\foo.txt";
    server.Expect(x => x.MapPath("~/App_Data/foo.txt")).Return(expected);
    var requestContext = new RequestContext(context,new RouteData());
    sut.ControllerContext = new ControllerContext(requestContext,sut);

    // act
    var actual = sut.Index();

    // assert
    var viewResult = actual as ViewResult;
    Assert.AreEqual(viewResult.Model,expected);
}

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....