简体   繁体   English

如何强制TryUpdateModel在单元测试中返回false

[英]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. 我需要强制TryUpdateModel在asp.net mvc web应用程序的单元测试中返回false,但它总是返回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. 现在,当您在单元测试的act阶段调用_controllerUnderTest.SaveStep ,ModelState.IsValid将返回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. 在我的情况下,我在确保ModelState.IsValid为true后尝试调用TryUpdateModel,因此向ModelState添加错误没有帮助。 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. 在这种情况下帮助我的是在视图模型中找到一个不可为空的字段,在安排单元测试时将该字段设置为null,并且TryUpdateModel返回false,即使ModelState.IsValid为单元测试返回true也是如此。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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