Model state validation in unit tests

TL;DR
If you don’t want to read the entire article provided by Youssef and want a quick solution to how to make ModelState.IsValid return false. Do this.

[TestMethod]
public void TestLogin_InvalidModel()
{
    AccountController controller = CreateAccountController();
    // new code added -->
    controller.ModelState.AddModelError("fakeError", "fakeError");
    // end of new code
    ...
    var response = controller.PostLogin(new LoginModel() {  });

    Assert.AreEqual(HttpStatusCode.BadRequest, response.StatusCode);

}

Now I can imagine the CreateAccountController() looks something like this for minimum ->

return new AccountApiController()
{
    Request = new HttpRequestMessage(),
    Configuration = new HttpConfiguration()
};

Hope this gives a quick answer for those googling 🙂

Leave a Comment

techhipbettruvabetnorabahisbahis forumuedusedueduseduedueduseduedusedusedu