Search code examples
c#unit-testingasp.net-web-apivs-unit-testing-frameworkmodel-validation

Model state validation in unit tests


I am writing a unit test for a controller like this:

public HttpResponseMessage PostLogin(LoginModel model)
{
    if (!ModelState.IsValid)
        return new HttpResponseMessage(HttpStatusCode.BadRequest);
}

the model looks like:

public class LoginModel
{
    [Required]
    public string Username { set; get; }
    [Required]
    public string Password { set; get; }
}

Then I have unit test like this one:

[TestMethod]
public void TestLogin_InvalidModel()
{
    AccountController controller = CreateAccountController();

    ...
    var response = controller.PostLogin(new LoginModel() {  });

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

}

Actually the ModelState is validated... which is weird for me as both fields are required... Could anybody advise?


Solution

  • The reason the model state is valid is that a new model state is created when you new up a controller. Web API isn't doing the parameter binding for you here, so it doesn't even have a chance to add model state errors.

    If you want to keep this as a unit test, then you should add the model state errors yourself and test what happens.

    If you want to test that the model state would be invalid on a real request, I recommend you read this blog post:

    http://blogs.msdn.com/b/youssefm/archive/2013/01/28/writing-tests-for-an-asp-net-webapi-service.aspx

    and try testing against an in-memory server. One minor note for your case would be that you may want to use a StringContent instead of an ObjectContent on the request to make sure that Web API tries to deserialize and bind the body properly.