I wrote a test that asserts that ModelState.IsValid is false but the test keeps failing. On closer examination, I find that ModelState.IfValid is always returning true for my controller tests. I had used Data annotations to mark up the model with required
attributes.
Simply executing a method during a unit test does just that - executes a method, and no more. The MVC pipeline doesn't run, so binding and validation don't run.
If you want to unit test your action's behavior for when ModelState is invalid, you need to manually make ModelState invalid. You can use
controller.ModelState.AddModelError("", "dummy error message") from within your unit test to force ModelState to be invalid.
Marked as answer by ricka6 on Feb 25, 2010 07:31 PM
Pita.O
Member
41 Points
22 Posts
My ModelState remains valid in Controller test even when it's not.
Feb 25, 2010 04:15 PM|LINK
Hi everyone,
I wrote a test that asserts that ModelState.IsValid is false but the test keeps failing. On closer examination, I find that ModelState.IfValid is always returning true for my controller tests. I had used Data annotations to mark up the model with required attributes.
Am I missing anything?
ModelState
ricka6
All-Star
15088 Points
2277 Posts
Microsoft
Moderator
Re: My ModelState remains valid in Controller test even when it's not.
Feb 25, 2010 06:25 PM|LINK
What are you doing to invalidate your model state? Why do you expect it to return false?
Pita.O
Member
41 Points
22 Posts
Re: My ModelState remains valid in Controller test even when it's not.
Feb 25, 2010 06:46 PM|LINK
For instance, I would set up a model and exclude a required parameter. Then, i would pass that new model onto the new Controller.Action(model) method.
my action method signature uses
public ActionResult ActionMethod(Model model){ if(ModelState.IsValid){ // Do the right thing return RedirectToAction("Index"); } return View(); }levib
Star
7702 Points
1099 Posts
Microsoft
Re: My ModelState remains valid in Controller test even when it's not.
Feb 25, 2010 06:57 PM|LINK
Simply executing a method during a unit test does just that - executes a method, and no more. The MVC pipeline doesn't run, so binding and validation don't run.
If you want to unit test your action's behavior for when ModelState is invalid, you need to manually make ModelState invalid. You can use controller.ModelState.AddModelError("", "dummy error message") from within your unit test to force ModelState to be invalid.
Pita.O
Member
41 Points
22 Posts
Re: My ModelState remains valid in Controller test even when it's not.
Feb 25, 2010 07:54 PM|LINK
Many thanks.
P
bustoscarlos
Member
2 Points
1 Post
Re: My ModelState remains valid in Controller test even when it's not.
Jun 15, 2010 12:56 AM|LINK
Did you solved the problem?
What is your framework version ? 3.5 ? 4 ?
I had the same problem. I updated from framework 3.5 to 4 and works like a charm