Why do you have code that depends on HostingEnvironment.MapPath in an ASP.NET MVC application, where you have access to objects like HttpServerUtilityBase that allow you to achieve this and that can be easily mocked and tested on a module?
Take an example: a controller action that uses the abstract server class 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 unit tests can perform this controller action. Personally, I like to use MVcContrib.TestHelper .
But let's see how we can do this using the mocking framework out of the box. I am using 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); }
Darin Dimitrov Jan 05 2018-12-12T00: 00Z
source share