0

I have the following controller method:

public ActionResult Contact()
{
  HttpPostedFileBase theFile = Reqeust.Files["myfile"];
  ViewBag.Message = "Contact Page";
  return View();
}

In the unit test, I do this:

HomeController controller = new HomeController();
controller.Contact();

Request will be null when Contact() is called. I've tried a number of different ways to initialize the Request object but nothing is working. I've tried the HttpContextWrapper() but nothing converts to an HttpRequestBase. Also, controller.Request is read only so any HttpContext.Current I create doesn't work there.

Any ideas?

2 Answers 2

4

You need to mock it and set the ControllerContext. Let's suppose that you have picked up Moq as such framework to simplify things. Your test might look like this

// arrange
var mockHttpContext = new Mock<HttpContextBase>();
var response = new Mock<HttpResponseBase>();
mockHttpContext.SetupGet(x => x.Response).Returns(response.Object);

var controller = new HomeController()
{
    ControllerContext = new ControllerContext() 
    { 
        HttpContext = mockHttpContext.Object 
    }
};

// act    
controller.Contact();

// assert

Of course if you want the Files property of the Request object to return something you need to set the proper expectation for the mock. At the moment your controller action doesn't seem to be doing anything useful with this file. I guess that in your real code this controller action actually works with the uploaded file. So you will mock the HttpPostedFileBase and then you could assert that some methods on it have been called or whatever you need to verify the correct behavior of this action.

Sign up to request clarification or add additional context in comments.

1 Comment

I notice you coded for Response. I just change it out for Request and it also works. Can you elaborate on how that would work for HttpPostedFileBase?
1

When instantiating your controller in your test, you can pass a new ControllerContext to it that includes a mock of an HttpContext + mock Request:

controller = new HomeController {
    ControllerContext = new ControllerContext { HttpContext = new MockHttpContext() }
};

Alternatively, you could use a framework like Moq or RhinoMocks.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.