Asp.net
如何對使用 HostingEnvironment.MapPath 的程式碼進行單元測試
我有一些
HostingEnvironment.MapPath我想進行單元測試的程式碼。如何設置
HostingEnvironment以使其返迴路徑而不是null在我的單元測試 (mstest) 項目中?
為什麼你會有一個依賴於 ASP.NET MVC 應用程序中的 HostingEnvironment.MapPath 的程式碼,你可以訪問像 HttpServerUtilityBase 這樣的對象,這些對象允許你實現這一點並且可以輕鬆地模擬和單元測試?
讓我們舉個例子:一個控制器動作,它使用我們想要單元測試的抽象 Server 類:
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); }