Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I test ModelState?

Tags:

c#

asp.net-mvc

How can I test Controller.ViewData.ModelState? I would prefer to do it without any mock framework.

like image 289
eKek0 Avatar asked Nov 13 '08 02:11

eKek0


People also ask

How do I know if my ModelState is valid?

Below the Form, the ModelState. IsValid property is checked and if the Model is valid, then the value if the ViewBag object is displayed using Razor syntax in ASP.Net MVC.

What is the point of checking ModelState?

The ModelState has two purposes: to store the value submitted to the server, and to store the validation errors associated with those values.

What is ModelState IsValid method where we use it?

ModelState. IsValid indicates if it was possible to bind the incoming values from the request to the model correctly and whether any explicitly specified validation rules were broken during the model binding process. In your example, the model that is being bound is of class type Encaissement .

Can you unit test controllers?

When unit testing controller logic, only the contents of a single action are tested, not the behavior of its dependencies or of the framework itself. Set up unit tests of controller actions to focus on the controller's behavior. A controller unit test avoids scenarios such as filters, routing, and model binding.


1 Answers

You don't have to use a Mock if you're using the Repository Pattern for your data, of course.

Some examples: http://www.singingeels.com/Articles/Test_Driven_Development_with_ASPNET_MVC.aspx

// Test for required "FirstName".    controller.ViewData.ModelState.Clear();     newCustomer = new Customer    {        FirstName = "",        LastName = "Smith",        Zip = "34275",        };     controller.Create(newCustomer);     // Make sure that our validation found the error!    Assert.IsTrue(controller.ViewData.ModelState.Count == 1,                   "FirstName must be required."); 
like image 125
Scott Hanselman Avatar answered Oct 03 '22 09:10

Scott Hanselman