Model state validation in unit tests

后端 未结 4 654
予麋鹿
予麋鹿 2020-12-08 14:44

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

public HttpResponseMessage PostLogin(LoginModel model)
{
    if (!ModelState.IsValid)
        return new         


        
4条回答
  •  失恋的感觉
    2020-12-08 15:12

    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 :)

提交回复
热议问题