开发者

How to mock Request.Files[] in MVC unit test class?

I want to test a controller method in MVC unit test. For my controller method to test, I require a Request.Files[] collection with length one. I want to mock Request.Files[] as I have used a file upload control on my view rendered by controller method. Can anyone please suggest how can I moc开发者_如何学Gok request.file collection in my unit test.

thanks, kapil


You didn't mention what mocking framework you are using but here's how you would do it with Rhino Mocks:

Controller:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View(Request.Files.Count);
    }
}

Unit test:

[TestMethod]
public void SomeTest()
{
    // arrange
    var controller = new HomeController();
    var context = MockRepository.GenerateStub<HttpContextBase>();
    var request = MockRepository.GenerateStub<HttpRequestBase>();
    var files = MockRepository.GenerateStub<HttpFileCollectionBase>();
    context.Stub(x => x.Request).Return(request);
    files.Stub(x => x.Count).Return(5);
    request.Stub(x => x.Files).Return(files);
    controller.ControllerContext = new ControllerContext(context, new RouteData(), controller);


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

    // assert
    Assert.IsInstanceOfType(actual, typeof(ViewResult));
    var viewResult = actual as ViewResult;
    Assert.IsInstanceOfType(viewResult.ViewData.Model, typeof(int));
    Assert.AreEqual(5, viewResult.ViewData.Model);
}

Remark: Using MVCContrib.TestHelper this test could be greatly simplified especially the context mocking part and the asserts as well:

[TestMethod]
public void SomeTest()
{
    // arrange
    var sut = new HomeController();
    InitializeController(sut);
    Files["test.txt"] = MockRepository.GenerateStub<HttpPostedFileBase>();

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

    // assert
    actual
        .AssertViewRendered()
        .WithViewData<int>()
        .ShouldBe(1);
}


Scott Hanselman has a blog post covering this using Moq.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜