简体   繁体   中英

How to force TryUpdateModel return false in unit testing

I need to force TryUpdateModel return false in unit testing in asp.net mvc web application, but it always return true.

my controller action is:

public JsonResult SaveStep(string path, string title, string definitionOfDone, int limit, bool isNewStep)
{
    Step step = new Step();

    if (TryUpdateModel(step)){
        // code    
    }
}

Simply add an error to the model state in the arrange phase of your unit test:

_controllerUnderTest.ModelState.AddModelError("key", "error message");

Now when you invoke the _controllerUnderTest.SaveStep in the act phase of your unit test the ModelState.IsValid will return false.

In my case, I was attempting to call TryUpdateModel after ensuring ModelState.IsValid was true, so adding an error to the ModelState wasn't helpful. What helped me in this case was to find a non-nullable field in the view model, set that field to null in arranging the unit test, and the TryUpdateModel returned false, even when the ModelState.IsValid returned true for the unit test.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM