单元测试中的模型状态验证 [英] Model state validation in unit tests

查看:122
本文介绍了单元测试中的模型状态验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为这样的控制器编写单元测试:

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

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

模型如下:

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

}

实际上ModelState已验证...这对我来说很奇怪,因为这两个字段都是必需的... 有人可以建议吗?

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

推荐答案

模型状态有效的原因是,当您新建控制器时会创建一个新的模型状态. Web API在这里没有为您做参数绑定,因此它甚至没有机会添加模型状态错误.

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

,然后尝试针对内存服务器进行测试.针对您的情况的一个小提示是,您可能希望在请求上使用StringContent而不是ObjectContent,以确保Web API尝试正确地反序列化并绑定主体.

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.

这篇关于单元测试中的模型状态验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆