Trying to stub Server.MapPath with MvcContrib Test helpers and Rhino Mocks 3.5

和自甴很熟 提交于 2020-01-05 08:27:27

问题


I'm using MvcContrib's test helpers and Rhino Mocks 3.5 to test an ASP.NET MVC action method. I build my fake controller like so:

var _builder = new TestControllerBuilder();
_builder.InitializeController(_controller);

So I get a fake controller that contains fake HTTP Server etc.

I'm then trying to stub the Server.MapPath method like so

controller.Server.Stub(x => x.MapPath(Arg<string>.Is.Anything)).Return("/APP_DATA/Files/");

but in my method under test the call to Server.MapPath("/APP_DATA/Files/") returns null.

This is the test

    const string STOCK_NUMBER_ID = "1";
    const string FULL_FILE_PATH = "App-Data/Files";

    var controller = CreateStockController();
    _uploadedFileTransformer.Stub(x => x.ImageBytes).Return(new byte[10]);
    _uploadedFileTransformer.Stub(x => x.ConvertFileToBytes(FULL_FILE_PATH)).Return(true);

    controller.Server.Stub(x => x.MapPath(Arg<string>.Is.Anything)).Return("/App_Data/Files/");

    controller.AddImage(Guid.NewGuid(), STOCK_NUMBER_ID);

What I am missing?


回答1:


Old post but I was searching for this and I found a solution, MvcContrib's TestHelper probably got it fixed because for me it's working.

_builder.HttpContext.Server.Stub(s => s.MapPath("~/" + filepath)).Repeat.Once().Return(mapedPath);



回答2:


Looks like this is a bug in MVCContrib (at least with what I have on my machine -- v1.0.0.0). When setting up the controller context, it's using Rhino.Mocks record/replay mode, but (and this is the bug), it doesn't put the HttpServer mock into replay mode. It puts everything else in replay mode but not that one.

So a quick fix is to do:

controller.Server.Replay();

As part of your "arrange" section of your test. Then it works fine.



来源:https://stackoverflow.com/questions/3248270/trying-to-stub-server-mappath-with-mvccontrib-test-helpers-and-rhino-mocks-3-5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!