Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7524007
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 30, 20262026-05-30T02:57:58+00:00 2026-05-30T02:57:58+00:00

I have a Mock challenge – I’m using MVC 3 with the nunit framework

  • 0

I have a Mock challenge – I’m using MVC 3 with the nunit framework and trying to mock a controller has an HttpPostedFileBase as a parameter. The controller signature looks like this:

 public ActionResult UploadAttachment(AttachmentViewModel clientAttachment, HttpPostedFileBase file, string clientName)

I set up a Mock reference for my “file” parameter, but it complains that it will not take a Mock Object. I’m guessing that I need to set up a ControllerContext for this scenario, but I haven’t had any luck with that, either. For the first test I simply need the HttpPostedFileBase to return a null file (in the case that a blank file reference gets in). I have also read Scott Hanselman’s excellent article on this subject (computer Zen). It seems like the key sentence in the MVC section for my concern is “you’ll get a dynamically generated derived Mock of an HttpRequestBase while running outside a Webserver (like inside a test) when you’ve made your own ControllerContext.” That seems to be where I’m running into walls.

I know I need these elements:

controller.ControllerContext = new ControllerContext(mockContext.Object, new RouteData(), controller);
mockContext.SetupGet(c => c.Request).Returns(mockRequest.Object);
mockRequest.Setup(c => c.HttpMethod).Returns([not sure what to evoke here]);

I’m in the state of being stuck. Thank you for any advice or nudges in the right direction.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-30T02:58:00+00:00Added an answer on May 30, 2026 at 2:58 am

    Assuming you use a real view model (which is used by your controller action, instead of using a gazillion of parameters):

    public class MyViewModel
    {
        public HttpPostedFileBase File { get; set; }
    
        // those won't be used in my example but you get the point
        public string ClientName { get; set; }
        public AttachmentViewModel ClientAttachment { get; set; }
    }
    

    and a controller with an action that you are trying to unit test:

    public class HomeController : Controller
    {
        [HttpPost]
        public ActionResult UploadAttachment(MyViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return View(model);
            }
    
            var file = Path.Combine(Server.MapPath("~/App_Data"), model.File.FileName);
            model.File.SaveAs(file);
            return RedirectToAction("succes");
        }
    }
    

    you now have 2 cases to cover:

    • invalid modelstate => a view is returned
    • valid modelstate => the file is saved and we redirected.

    Let’s get rolling:

    [TestMethod]
    public void UploadAttachment_Should_Return_View_If_ModelState_Is_Not_Valid()
    {
        // arrange
        var sut = new HomeController();
        var model = new MyViewModel();
        sut.ModelState.AddModelError("file", "please select a file");
    
        // act
        var actual = sut.UploadAttachment(model);
    
        // assert
        Assert.IsInstanceOfType(actual, typeof(ViewResult));
    }
    

    and the second case of course:

    [TestMethod]
    public void UploadAttachment_Should_Save_File_If_Model_Is_Valid_And_Redirect()
    {
        // arrange
        var sut = new HomeController();
        var file = new Mock<HttpPostedFileBase>();
        file.Setup(x => x.FileName).Returns("foo.txt");
        var model = new MyViewModel
        {
            File = file.Object
        };
        var server = new Mock<HttpServerUtilityBase>();
        server.Setup(x => x.MapPath("~/App_Data")).Returns(@"c:\wwwroot\App_Data");
        var httpContext = new Mock<HttpContextBase>();
        httpContext.Setup(x => x.Server).Returns(server.Object);
        sut.ControllerContext = new ControllerContext(httpContext.Object, new RouteData(), sut);
    
        // act
        var actual = sut.UploadAttachment(model);
    
        // assert
        Assert.IsInstanceOfType(actual, typeof(RedirectToRouteResult));
        file.Verify(x => x.SaveAs(@"c:\wwwroot\App_Data\foo.txt"));
    }
    

    Hope this will put you on the right track. Sorry it uses MSTest instead of NUnit but the port should be more than trivial (shouldn’t take you more than 30man-seconds of work). Replace [TestMethod] with [Test] and you should not be far from the target. And yeah, I bet 2¢ that this Assert.IsInstanceOfType has an equivalent in NUnit.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am trying to mock java.awt.Toolkit.beep() using JMockit Expectations. I have the following code
I am using RhinoMocks, and I have a Mock which has a property I
I have to mock the following security step using EasyMock or UnitilsMock. Could you
I have a basic understanding of mock and fake objects, but I'm not sure
I have a unit test that creates a mock calls my method to be
I'm working on a media library mock-up and I have a database of songs
I'm new to mock objects, but I understand that I need to have my
I need to mock a GrailsControllerClass interface. Instance should have a static variable defined.
I'm attempting to mock some file operations. In the real object I have: StreamWriter
Have just started using Google Chrome , and noticed in parts of our site,

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.