开发者

ASP.NET MVC does not add ModelError when invoking from unit test

开发者 https://www.devze.com 2022-12-26 07:42 出处:网络
I have a model item public class EntryInputModel { ... [Required(ErrorMessage = \"Description is required.\", AllowEmptyStrings = false)]

I have a model item

public class EntryInputModel
{
    ...

    [Required(ErrorMessage = "Description is required.", AllowEmptyStrings = false)]
    public virtual string Description { get; set; }
}

and a controller action

public ActionResult Add([Bind(Exclude = "Id")] EntryInputModel newEntry)
{
    if (ModelState.IsValid)
    {
        var entry = Mapper.Map<EntryInputModel, Entry>(newEntry);

        repository.Add(entry);
        unitOfWork.SaveChanges();
        return RedirectToAction("Details", new { id = entry.Id });
    }
    return RedirectToAction("Create");
}

When I create an EntryInputModel in a unit test, set the Description property to null and pass it to the action method, I still get ModelState.IsValid == true, even though I have debugged and verified that newEntr开发者_如何学JAVAy.Description == null.

Why doesn't this work?


This is because model binding doesn't take place when you invoke an action from a test. Model binding is the process of mapping posted form values to a type and pass it as a parameter to an action method.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号