本文介绍了如何单元测试code使用HostingEnvironment.MapPath的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have some code that uses HostingEnvironment.MapPath which I would like to unit test.

如何设置 HostingEnvironment ,以便它在我的单元测试返回的路径,而不是(MSTest的)项目?

How can I setup HostingEnvironment so that it returns a path and not null in my unit test (mstest) project?

推荐答案

为什么你将有一个code取决于HostingEnvironment.MapPath在ASP.NET MVC应用程序,你必须访问对象一样的HttpServerUtilityBase,让你实现这一点,可以很容易地嘲笑和单元测试?

Why would you have a code that depends on HostingEnvironment.MapPath in an ASP.NET MVC application where you have access to objects like HttpServerUtilityBase which allow you to achieve this and which can be easily mocked and unit tested?

让我们看一个例子:它使用我们要进行单元测试抽象服务器级别的控制器操作:

Let's take an example: a controller action which uses the abstract Server class that we want to unit test:

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

现在,有很多方法进行单元测试该控制器的动作。我个人喜欢用。

Now, there are many ways to unit test this controller action. Personally I like using the MVcContrib.TestHelper.

不过,让我们看看我们如何能够用嘲讽的框架外的开箱做到这一点。我用犀牛嘲笑这个例子:

But let's see how we can do this using a mocking framework out-of-the-box. I use Rhino Mocks for this example:

[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);
}

这篇关于如何单元测试code使用HostingEnvironment.MapPath的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-26 13:47