asp.net mvc - TDD and MVC Model Binding -


let's have unit test:

    [test]     public void lastnameshouldnotbeempty()     {         examplecontroller controller = new examplecontroller();          person editedperson = new person { firstname = "j", lastname = "" };         controller.editperson(editedperson);          assert.areequal(controller.modelstate.isvalid, false);     } 

and code:

public class examplecontroller : controller {     public actionresult editperson(int personid)     {         // serve view, whatever         return view(person.loadperson(personid));     }      [httppost]     public actionresult editperson(person person)     {         if (modelstate.isvalid)         {             // todo - save modified person, whatever         }          return view(person);     } }  public class person {     public string firstname { get; set; }     [required] public string lastname { get; set; } } 

it's bothering me if tdd out requirement lastname can't empty, can't satisfy test using dataannotation attributes (the [required] before lastname declaration on person) because when controller's action method invoked unit test, mvc infrastructure hasn't gotten chance apply validation during model binding.

(if manually performed validation in controller's editperson method, though, , added error modelstate, verifiable unit test.)

am missing something? i'd specify validation behavior of system using unit tests, i'm not sure how satisfy unit test unless abandon dataannotation attributes altogether , perform validation manually inside controller's action methods.

i hope intent of question clear; there way force true model binding execute (including validation behavior, test haven't forgotten important validation attributes) automated unit test?

jeff

i believe should have unit tests test attributes themselves, outside of scope of mvc. should part of model tests, not controller tests. didn't write mvc validation code, don't try test it! test fact object has right attributes expecting.

this rough, idea...

[test] public void lastnameshouldberequired() {     var persontype = typeof(person);     var lastnamepropinfo = objtype.getproperty("lastname");     var requiredattrs = lastnamepropinfo.getcustomattributes(typeof(requiredattribute), true).oftype<requiredattribute>();     assert.istrue(requiredattrs.any()); } 

then in mvc tests test flow of controller, not validity of data annotations. can tell modelstate invalid test flow of happens if validation fails etc adding error manually, noted. it's controlled test of controller responsible for, not framework doing you.


Comments

Popular posts from this blog

ASP.NET/SQL find the element ID and update database -

jquery - appear modal windows bottom -

c++ - Compiling static TagLib 1.6.3 libraries for Windows -