Reputation: 18941
Has any one some example code of mocking request.form in a unit test, calling a controller and have the controller successfully bind the mock request.form to a view model using the Bind
attribute or Controller.TryUpdateModel(model)
?
This would appear to me to be a relatively common requirement, but alas a morning has gone and I am yet to find anything that's both adequate and working.
p.s. I've been chasing this all morning and have had no luck as the model binding is failing.
Upvotes: 1
Views: 2622
Reputation: 18941
this always felt far harder than it needed to be. In the end the solution is simple and reasonably elegant although I'd prefer to see some conventional way to do this.
The trick is to add a FormCollection parameter to the Action:
this will be injected at run-time by MVC but allows mocking at test-time:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Search([Bind(Prefix = "")] ManageUsersViewModel manageUsersViewModel, FormCollection form)
{
in the test:
var form = new FormCollection
{
{"FindCriteria.SearchText", "searchText"},
{"FindCriteria.AccountIsPending", "true"},
{"FindCriteria.TermsHaveBeenAccepted", "true"}
};
sut.Search(new ManageUsersViewModel(), form);
Edit
Also it appears you will need two other things - Bind - does not work, you will need to make sure your controller has a controllercontext AND you will need to explicity call UpdateModel:
controller.ControllerContext = new ControllerContext();
...
UpdateModel(manageUsersViewModel, form.ToValueProvider());
MVC 3 and I'm having to revert to this to test a simple form submission. INSANE IN THE MEMBRANE
Upvotes: 1