-1

How can I mock HttpContext.Current.Request.Form["something"] data in the tested controller? I can mock HttpContext.Current and it works but Request is readonly. I can not change the implementation of the controller where the Form data is used. I only have to write a test.

Dharman
  • 21,838
  • 18
  • 57
  • 107
  • 3
    Why can't you change the implementation of the controller? If the controller is reading directly from the Request, it shouldn't be. MVC has model binding to posted form values for a reason - you should be modifying the controller to take advantage of that. – mason Oct 09 '19 at 13:54
  • Unfortunately though I agree with you @mason the OP says they can't change the implementation of the controller. Did you try mocking the request object and returning that from your Moq proxy? That mock itself can then return a mock for the form object? What code have you tried so far? – Charleh Oct 09 '19 at 14:03
  • @Charleh Yes, I saw what they said, you don't need to remind me. Which is why I asked why they can't change it. Often people paint themselves into a corner for silly reasons, so asking why may help us determine whether they truly are constrained. – mason Oct 09 '19 at 14:05
  • Possible duplicate of [Mock HttpContext.Current in Test Init Method](https://stackoverflow.com/questions/4379450/mock-httpcontext-current-in-test-init-method) – André Sanson Oct 09 '19 at 14:08
  • The reason why I can't change the code is because it's my bosses code - and I have "just to write test". I must not challenge his programming skills :-) – Ivan Koreček Oct 10 '19 at 08:44

1 Answers1

0

If you really can't change the implementation of the controller to use modelbinding, you can mock the request object easily enough:

var formData = new FormCollection(new Dictionary<string, Microsoft.Extensions.Primitives.StringValues> { { "test", "value" } });

var requestMock = new Mock<HttpRequest>();
requestMock.SetupGet(x => x.Form).Returns(formData);

var contextMock = new Mock<HttpContext>();
contextMock.SetupGet(x => x.Request).Returns(requestMock.Object);

Setup FormCollection how you need your example data to look.

As others have stated, it makes way more sense to use modelbinding since it abstracts away this requirement.

Actually, you didn't mention if you were using ASP.NET or Core, I assume .NET based on HttpContext.Current?

Charleh
  • 13,285
  • 3
  • 34
  • 54