testCoder
testCoder

Reputation: 7385

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    
    }
}

Upvotes: 0

Views: 359

Answers (2)

Joel Nelson
Joel Nelson

Reputation: 1

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.

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1038820

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.

Upvotes: 2

Related Questions